<?php
// /includes/user_settings.php

// handler for show/hide functionality
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'toggle_visibility') {
    header('Content-Type: application/json');
    
    try {
        if (empty($_POST['id']) || empty($_POST['status'])) {
            throw new Exception('Missing required parameters');
        }
        
        $id = $_POST['id'];
        $isHidden = ($_POST['status'] === 'visible') ? 1 : 0;
        
        // Verify the case belongs to the current user
        $stmt = $pdo->prepare("SELECT user_id FROM wp_groupusers_data WHERE id = ?");
        $stmt->execute([$id]);
        $caseUserId = $stmt->fetchColumn();
        
        if ($caseUserId != $_SESSION['front_user_id']) {
            throw new Exception('Permission denied');
        }
        
        $stmt = $pdo->prepare("UPDATE wp_groupusers_data SET case_hidden = ? WHERE id = ?");
        $success = $stmt->execute([$isHidden, $id]);
        
        if (!$success) {
            throw new Exception('Failed to update case visibility');
        }
        
        echo json_encode(['success' => true]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}


function displayUserSettings($userId) {
    global $pdo;
    
    try {
        $table_name = PREFIX . 'users';
        $stmt = $pdo->prepare("SELECT * FROM $table_name WHERE ID = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_OBJ);

        if (!$user) {
            echo "User not found.";
            return;
        }

        $group_name = '';
		if ($user->group_id) {
			$group_table = PREFIX . 'groups';
			$stmt = $pdo->prepare("SELECT group_name FROM $group_table WHERE id = ?");
			$stmt->execute([$user->group_id]);
			$group_name = $stmt->fetchColumn();
		}
		
		// query for show/hide functionality
		$cases_query = "SELECT 
			id,
			left(user_data, instr(user_data, '\n') - 1) AS user_data_trunc,
			DATE_FORMAT(datetime, '%Y-%m-%d %l:%i %p') AS dateformatted,
			case_grade,
			case_score,
			instructor_notes,
			case_hidden
		FROM wp_groupusers_data 
		WHERE user_id = ? AND (case_hidden = 0 OR case_hidden IS NULL)
		ORDER BY datetime DESC";

        ?>

        <div class="user-settings">
			<div class="user-settings-top">
				<div class="user-settings-container">
					<h2>User Details</h2>
					<p><strong>Name:</strong> <?php echo htmlspecialchars($user->first_name . ' ' . $user->last_name); ?></p>
					<button id="changeProfileName">Change Profile Name</button>

					<form id="changeNameForm" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="display:none; margin-top: 10px;">
						<input type="hidden" name="action" value="update_name">
						<input type="text" name="first_name" placeholder="First Name" value="<?php echo htmlspecialchars($user->first_name); ?>" required>
						<input type="text" name="last_name" placeholder="Last Name" value="<?php echo htmlspecialchars($user->last_name); ?>" required>
						<button type="submit">Save</button>
						<button type="button" id="cancelNameButton">Cancel</button>
					</form>
					
					<p><strong>Email:</strong> <?php echo htmlspecialchars($user->user_email); ?></p>
					<p><strong>Joined On:</strong> <?php 
					// echo htmlspecialchars($user->user_registered); 
					echo date("F j, Y", strtotime($user->user_registered)); ?></p>
					<br>
					<p><strong>Group:</strong> <?php echo htmlspecialchars($group_name); ?></p>
					<p><strong>User Type:</strong> <?php echo htmlspecialchars(ucfirst($user->user_type)); ?></p>
					<?php if ($user->is_admin == 1): ?>
						<p><strong>Administrator of:</strong> <?php echo htmlspecialchars($group_name); ?></p>
					<?php endif; ?>
				</div>
				<div class="profile-picture-container">
				<h2>Profile Picture</h2>
					<?php
					$profile_picture_url = getProfilePictureUrl($userId);
					if ($profile_picture_url) {
						echo '<img src="' . htmlspecialchars($profile_picture_url) . '" alt="Profile Picture" class="profile-picture">';
						// echo '<button id="removeProfilePicture">Remove Profile Picture</button>';
					} else {
						echo '<p>No profile picture set.</p>';
					}
					?>
				</div>
				<button id="changeProfilePicture">Change Profile Picture</button>
			</div>
		</div>
        <?php
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}
// include('change_profile.php');

function generateUniqueId($length = 16) {
    return bin2hex(random_bytes($length / 2));
}

function ensureUniqueId($pdo, $length = 16) {
    $table_name = PREFIX . 'users';
    
    do {
        $unique_id = generateUniqueId($length);
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM $table_name WHERE unique_id = ?");
        $stmt->execute([$unique_id]);
        $exists = $stmt->fetchColumn();
    } while ($exists > 0);

    return $unique_id;
}

function hasProfilePicture($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';
    
    $stmt = $pdo->prepare("SELECT profile_picture FROM $table_name WHERE ID = ?");
    $stmt->execute([$userId]);
    $profile_picture = $stmt->fetchColumn();

    return !empty($profile_picture);
}

function getProfilePictureUrl($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';
    
    $stmt = $pdo->prepare("SELECT unique_id, profile_picture FROM $table_name WHERE ID = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_OBJ);

    if ($user && $user->profile_picture) {
        return "/images/profiles/" . $user->unique_id . "/" . $user->profile_picture;
    }
    
    return ''; // Return empty string if no profile picture is set
}

function handleProfilePictureUpload($userId) {
    global $pdo;
    $table_name = PREFIX . 'users';

    // Check if file was uploaded without errors
    if(isset($_FILES["profile_picture"]) && $_FILES["profile_picture"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["profile_picture"]["name"];
        $filetype = $_FILES["profile_picture"]["type"];
        $filesize = $_FILES["profile_picture"]["size"];
    
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) {
            return json_encode(["success" => false, "message" => "Error: Please select a valid file format."]);
        }
    
        // Verify file size - 5MB maximum
        $maxsize = 5 * 1024 * 1024;
        if($filesize > $maxsize) {
            return json_encode(["success" => false, "message" => "Error: File size is larger than the allowed limit."]);
        }
    
        // Verify MIME type of the file
        if(in_array($filetype, $allowed)){
            // Check if user already has a unique_id
            $stmt = $pdo->prepare("SELECT unique_id FROM $table_name WHERE ID = ?");
            $stmt->execute([$userId]);
            $unique_id = $stmt->fetchColumn();

            if(!$unique_id) {
                $unique_id = generateUniqueId();
                $stmt = $pdo->prepare("UPDATE $table_name SET unique_id = ? WHERE ID = ?");
                $stmt->execute([$unique_id, $userId]);
            }

            // Create user folder if it doesn't exist
            $user_folder = $_SERVER['DOCUMENT_ROOT'] . "/images/profiles/" . $unique_id . "/";
            if (!file_exists($user_folder)) {
                mkdir($user_folder, 0777, true);
            }

            // Generate new filename
            $new_filename = bin2hex(random_bytes(8)) . "." . $ext;

            // Save the file
            if(move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $user_folder . $new_filename)){
                // Update database
                $stmt = $pdo->prepare("UPDATE $table_name SET profile_picture = ? WHERE ID = ?");
                $stmt->execute([$new_filename, $userId]);

                return json_encode([
                    "success" => true, 
                    "message" => "Your profile picture was uploaded successfully.",
                    "newImageUrl" => "/images/profiles/" . $unique_id . "/" . $new_filename,
                    "originalFileName" => $filename  // Add this line to return the original file name
                ]);
            } else {
                return json_encode(["success" => false, "message" => "Error: There was a problem uploading your file. Please try again."]);
            }
        } else {
            return json_encode(["success" => false, "message" => "Error: There was a problem uploading your file. Please try again."]);
        }
    } else {
        return json_encode(["success" => false, "message" => "Error: " . $_FILES["profile_picture"]["error"]]);
    }
}


ob_start();

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/* edit user fields */
$userId = $_SESSION['front_user_id'];
$user = getUserDetails($userId);

$needRedirect = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $updateData = [
        'first_name' => $_POST['first_name'],
        'last_name' => $_POST['last_name'],
        'user_email' => $_POST['user_email']
		/*
		'user_login' => $_POST['user_login'],
		'display_name' => $_POST['display_name'],
		'user_nicename' => $_POST['user_nicename'],
		'user_url' => $_POST['user_url']
		*/
    ];

    /*
    if (!empty($_POST['new_password'])) {
        if (changePassword($userId, $_POST['new_password'])) {
            $successMessage .= " Password changed successfully.";
        } else {
            $errorMessage .= " Failed to change password.";
        }
    }
    */
	
    if (updateUserSettings($userId, $updateData)) {
        $_SESSION['success_message'] = "Settings updated successfully!";
    } else {
        $_SESSION['error_message'] = "Failed to update settings.";
    }

    // No redirect here, just let the script continue
    // Refresh user data after update
    $user = getUserDetails($userId);
	
    $needRedirect = true;
}

// Display messages if they exist
if (isset($_SESSION['success_message'])) {
    echo "<div class='success-message'>" . htmlspecialchars($_SESSION['success_message']) . "</div>";
    unset($_SESSION['success_message']);
} elseif (isset($_SESSION['error_message'])) {
    echo "<div class='error-message'>" . htmlspecialchars($_SESSION['error_message']) . "</div>";
    unset($_SESSION['error_message']);
}

	
?>

    <script src="../js/settings.js" defer></script>
	
    <div class="settings-switch">
        <div class="view-settings">View Details</div>
		<div class="view-cases">View Cases</div>
        <div class="change-settings">Change Settings</div>
    </div>

<div class="user-settings-bottom">
	<div class="settings-edit-form">
		<h2>Change Settings</h2>
		<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">

			<div>
				<label for="first_name">First Name:</label>
				<input type="text" id="first_name" name="first_name" value="<?php echo htmlspecialchars($user['first_name']); ?>">
			</div>

			<div>
				<label for="last_name">Last Name:</label>
				<input type="text" id="last_name" name="last_name" value="<?php echo htmlspecialchars($user['last_name']); ?>">
			</div>

			<? /* 
			<div>
				<label for="user_email">Email:</label>
				<input type="email" id="user_email" name="user_email" value="<?php echo htmlspecialchars($user['user_email']); ?>">
			</div>
			
			<div>
				<label for="user_login">Username:</label>
				<input type="text" id="user_login" name="user_login" value="<?php echo htmlspecialchars($user['user_login']); ?>">
			</div>

			<div>
				<label for="display_name">Display Name:</label>
				<input type="text" id="display_name" name="display_name" value="<?php echo htmlspecialchars($user['display_name']); ?>">
			</div>

			<div>
				<label for="user_nicename">Nice Name (for URLs):</label>
				<input type="text" id="user_nicename" name="user_nicename" value="<?php echo htmlspecialchars($user['user_nicename']); ?>">
			</div>

			<div>
				<label for="user_url">Website:</label>
				<input type="url" id="user_url" name="user_url" value="<?php echo htmlspecialchars($user['user_url']); ?>">
			</div>

			<div>
				<label for="new_password">New Password (leave blank to keep current):</label>
				<input type="password" id="new_password" name="new_password">
			</div> */ ?>

			<div>
				<button type="submit">Update Settings</button>
			</div>
		</form>
	</div>
</div>

<div class="user-cases" style="display: none; width: 100%;">
    <h2>Your Cases</h2>
    <div id="cases-list">
        <?php /* Cases list will be loaded here via AJAX */ ?>
    </div>
    <div id="case-details" style="display: none;">
        <?php /* Individual case details will be loaded here via AJAX */ ?>
    </div>
</div>

<script>
function showCasesList() {
    document.getElementById('cases-list').style.display = 'block';
    document.getElementById('case-details').style.display = 'none';
}

function loadCases() {
    fetch('/api/toggle_case_visibility.php', {
        method: 'GET'  // This will get the updated list
    })
    .then(response => response.json())
    .then(data => {
        const casesList = document.getElementById('cases-list');
        if (!casesList) return;
        
        // Hide the current row/item that was toggled instead of reloading everything
        const toggledRow = document.querySelector(`[data-id="${id}"]`).closest('tr');
        if (toggledRow) {
            toggledRow.style.display = 'none';
        }
    })
    .catch(error => {
        console.error('Error updating cases list:', error);
    });
}

// hide.show function
document.addEventListener('DOMContentLoaded', function() {
	document.addEventListener('click', function(e) {
		if (e.target && e.target.matches('.visibility-toggle-btn')) {
			const button = e.target;
			const id = button.dataset.id;
			const currentStatus = button.dataset.status;
			const row = button.closest('tr');
			
			fetch('/api/toggle_case_visibility.php', { 
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
				},
				body: `id=${id}&status=${currentStatus}`
			})
			.then(response => response.json())
			.then(data => {
				if (data.success) {
					const headers = document.querySelectorAll('.overview-title');
					const hiddenTableHeader = Array.from(headers).find(h => h.textContent === 'Hidden Cases');
					const hiddenTableBody = hiddenTableHeader.nextElementSibling.querySelector('tbody');
					const allTables = document.querySelectorAll('.home-table');
					const yourCasesTable = allTables[1];

					if (currentStatus === 'visible') {
						const hiddenTable = document.querySelector('.hidden-cases-table');  // Get main hidden table div
						row.remove(); // Remove from visible immediately
						
						// Add to hidden table (even if not shown)
						const tbody = hiddenTable.querySelector('tbody');
						if (tbody) {
							const newRow = row.cloneNode(true);
							tbody.appendChild(newRow);
						}
						
						// Always show popup regardless of table visibility
						const popup = document.createElement('div');
						popup.className = 'confirmation-popup hide-confirmation';
						popup.textContent = 'Case hidden';
						document.body.appendChild(popup);
						setTimeout(() => popup.remove(), 2000);
					} else {
						row.remove();
						const headerRow = yourCasesTable.querySelector('tr');
						headerRow.parentNode.insertBefore(row.cloneNode(true), headerRow.nextSibling);
					}

					button.textContent = currentStatus === 'visible' ? 'Show' : 'Hide';
					button.dataset.status = currentStatus === 'visible' ? 'hidden' : 'visible';

					const popup = document.createElement('div');
					popup.className = `confirmation-popup ${currentStatus === 'visible' ? 'hide-confirmation' : 'show-confirmation'}`;
					popup.textContent = currentStatus === 'visible' ? 'Case hidden' : 'Case shown';
					document.body.appendChild(popup);
					setTimeout(() => popup.remove(), 2000);       
					
					// Update toggle text
					const showHiddenToggle = document.getElementById('showHiddenToggle');
					const toggleText = showHiddenToggle.parentElement.nextElementSibling;
					toggleText.textContent = showHiddenToggle.checked ? 'Hide Hidden Cases' : 'Show Hidden Cases';
				}
			});
		}
	});
	const showHiddenToggle = document.getElementById('showHiddenToggle');
		if (showHiddenToggle) {
			const toggleText = showHiddenToggle.parentElement.nextElementSibling;
			const hiddenCasesTable = document.querySelector('.hidden-cases-table');
			
			showHiddenToggle.addEventListener('change', function() {
				toggleText.textContent = this.checked ? 'Hide Hidden Cases' : 'Show Hidden Cases';
				if (hiddenCasesTable) {
					hiddenCasesTable.style.display = this.checked ? 'block' : 'none';
				}
			});

			// Set initial text state
			if (showHiddenToggle.checked) {
				toggleText.textContent = 'Hide Hidden Cases';
			}
		}
});
</script>

<?php
if ($needRedirect) {
    // Clear any output that might have been generated
    ob_clean();
    
    // Output a meta refresh
    echo '<meta http-equiv="refresh" content="0;url=/settings">';
    echo '<script>window.location.href = "/settings";</script>';
    echo 'If you are not redirected, please <a href="/settings">click here</a>.';
}

// End and flush the output buffer
ob_end_flush();

// Usage:
// displayUserSettings($current_user_id);
?>