<?php
require_once 'config.php';
require_login();

if (is_admin()) {
    header('Location: dashboard.php');
    exit();
}

$studentId = $_SESSION['user_id'];
$message = '';

// --- Fix 1: Change 'name' to 'first_name' in SELECT query to match users.sql ---
// Fetch current user data (Using first_name as the primary name field)
$stmt = $pdo->prepare("SELECT first_name, email, a_l_year, image_url, telegram_username, contact_info FROM users WHERE id = ?");
$stmt->execute([$studentId]);
$userData = $stmt->fetch();
$contactInfo = json_decode($userData['contact_info'] ?? '{}', true);

// Get potential message from redirect
$message = $_GET['msg'] ?? '';

// Handle Profile Update
if (isset($_POST['update_profile'])) {
    $fullName = trim($_POST['full_name']); // We assume this input maps to the 'first_name' column
    $telegram = trim($_POST['telegram_username']);
    $mobile = trim($_POST['mobile_number']);
    $guardianName = trim($_POST['guardian_name']);
    $guardianPhone = trim($_POST['guardian_phone']);

    $newContactInfo = json_encode([
        'mobile_number' => $mobile,
        'guardian_name' => $guardianName,
        'guardian_phone' => $guardianPhone,
    ]);

    // --- START: Image Upload Logic ---
    $imageUpdateSql = "";
    // --- Fix 2: Order of parameters must match SQL. The parameters are: (name, telegram, contact_info, studentId) ---
    $params = [$fullName, $telegram, $newContactInfo, $studentId];
    $isImageUploaded = false;

    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == UPLOAD_ERR_OK) {
        $target_dir = "uploads/logo/";
        
        // 1. Ensure the directory exists
        if (!is_dir($target_dir)) {
            // Use 0755 for more secure permissions if possible, but 0777 is used for maximum compatibility
            mkdir($target_dir, 0777, true); 
        }

        $file_extension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif'];
        
        // 2. Simple Validation
        if (!in_array(strtolower($file_extension), $allowed_extensions)) {
            $message = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed.';
        } else if ($_FILES['profile_image']['size'] > 5000000) { // 5MB limit
            $message = 'Sorry, your file is too large (max 5MB).';
        } else {
            // 3. Generate unique filename (using user ID and timestamp)
            $new_file_name = $studentId . '_profile_' . time() . '.' . $file_extension;
            $target_file = $target_dir . $new_file_name;

            // 4. Move uploaded file
            if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $target_file)) {
                // Successful upload: Prepare SQL update and parameters
                $imageUpdateSql = ", image_url = ?";
                // Insert the new image path just before the final $studentId parameter
                // Original array: [fullName, telegram, newContactInfo, studentId]
                // We insert $target_file at position 3 (index 3)
                array_splice($params, count($params) - 1, 0, [$target_file]); 
                $isImageUploaded = true;
                
                // Optional: Delete old image if it exists and is not the default
                // This logic is commented out but kept for reference
                /*
                $default_image_path = 'assets/default_profile.png';
                if (!empty($userData['image_url']) && $userData['image_url'] != $default_image_path && file_exists($userData['image_url'])) {
                    // unlink($userData['image_url']); 
                }
                */
            } else {
                $message = 'Error uploading file. Check directory permissions.';
            }
        }
    }
    // --- END: Image Upload Logic ---

    // Only proceed with DB update if no fatal upload error occurred or if no file was uploaded
    // Note: The original logic here was a bit complex. Simplifying: if $message is set AND the image upload failed, we skip the DB update.
    if (!isset($message) || $isImageUploaded || !isset($_FILES['profile_image']) || $_FILES['profile_image']['error'] == UPLOAD_ERR_NO_FILE) { 
        try {
            // --- Fix 3: Change 'name' to 'first_name' in UPDATE query to match users.sql ---
            // Construct the final SQL statement
            $sql = "UPDATE users SET first_name = ?, telegram_username = ?, contact_info = ?{$imageUpdateSql} WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            
            $final_message = $message ?: 'Profile updated successfully!';

            // Update session and refresh
            $_SESSION['user_name'] = $fullName;
            
            // Redirect to refresh data and show message
            header("Location: profile.php?msg=" . urlencode($final_message));
            exit();

        } catch (PDOException $e) {
            $message = 'Error updating profile: ' . htmlspecialchars($e->getMessage());
        }
    }
    
    // Re-fetch data if there was a non-redirecting error (like an upload failure)
    // --- Fix 4: Ensure the re-fetch query also uses 'first_name' ---
    $stmt = $pdo->prepare("SELECT first_name, email, a_l_year, image_url, telegram_username, contact_info FROM users WHERE id = ?");
    $stmt->execute([$studentId]);
    $userData = $stmt->fetch();
    $contactInfo = json_decode($userData['contact_info'] ?? '{}', true);
}


// Re-fetch data for initial display or after a non-redirecting error (redundant but safe after the POST block)
// --- Fix 5: Ensure the initial display query also uses 'first_name' ---
$stmt = $pdo->prepare("SELECT first_name, email, a_l_year, image_url, telegram_username, contact_info FROM users WHERE id = ?");
$stmt->execute([$studentId]);
$userData = $stmt->fetch();
// Use 'first_name' for display
$nameForDisplay = $userData['first_name'] ?? '';
$contactInfo = json_decode($userData['contact_info'] ?? '{}', true);

// Set default image path if image_url is empty
$display_image_url = !empty($userData['image_url']) ? htmlspecialchars($userData['image_url']) : 'https://placehold.co/160x160/2563EB/ffffff?text=DP';


require_once 'layouts.php';
render_header('My Profile');
// The name variable in the PHP content below refers to the 'first_name' from the DB fetch.
render_sidebar($_SESSION['user_role'], basename(__FILE__));
render_topbar('My Profile', $display_image_url);
?>
        <div class="flex items-center mb-6">
            <img src="profile.gif" alt="Classes Icon" class="w-8 h-8 mr-3" />
            <h2 class="text-2xl font-extrabold text-gray-900">My Profile</h2>
        </div>
<div class="flex flex-col lg:flex-row gap-8">
    <!-- Left Column: Image and ID -->
    <div class="lg:w-1/3 bg-white p-6 rounded-xl shadow-lg flex flex-col items-center text-center">
        
        <!-- Profile Picture Wrapper (Clickable) -->
        <label for="profile_image" class="relative w-40 h-40 mb-4 cursor-pointer group">
            <!-- Display Image -->
            <img id="current_profile_image" src="<?php echo $display_image_url; ?>" alt="Profile Picture" 
                class="w-full h-full rounded-full object-cover border-4 border-indigo-200 transition duration-300 group-hover:opacity-70" 
                onerror="this.onerror=null;this.src='https://placehold.co/160x160/2563EB/ffffff?text=DP';">
            
            <!-- Overlay Icon on hover -->
            <div class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-30 rounded-full opacity-0 group-hover:opacity-100 transition duration-300">
                <!-- Camera Icon SVG (Simple) -->
                <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
                    <circle cx="12" cy="13" r="4"/>
                </svg>
            </div>
        </label>
        
        <!-- --- Fix 6: Use 'first_name' for display --- -->
        <h3 class="text-2xl font-bold text-gray-900"><?php echo htmlspecialchars($userData['first_name'] ?? 'Student'); ?></h3>
        <p class="text-lg text-gray-500 mb-4">ID: CK<?php echo htmlspecialchars($studentId + 100000); // Mock Student ID ?></p>
        <p class="text-sm font-semibold text-indigo-600 border border-indigo-200 bg-indigo-50 px-3 py-1 rounded-full">
            <?php echo htmlspecialchars($userData['a_l_year'] ?? 'N/A'); ?>
        </p>
    </div>

    <!-- Right Column: Form -->
    <div class="lg:w-2/3 bg-white p-8 rounded-xl shadow-lg">
        <h2 class="text-2xl font-bold text-gray-900 mb-6 border-b pb-2">Student Details</h2>

        <?php if ($message): ?>
            <!-- Ensure message variable is used if set -->
            <div class="bg-<?php echo strpos($message, 'Error') !== false || strpos($message, 'Sorry') !== false ? 'red' : 'green'; ?>-100 border-l-4 border-<?php echo strpos($message, 'Error') !== false || strpos($message, 'Sorry') !== false ? 'red' : 'green'; ?>-500 text-<?php echo strpos($message, 'Error') !== false || strpos($message, 'Sorry') !== false ? 'red' : 'green'; ?>-700 p-4 mb-6 rounded-lg" role="alert"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>

        <!-- IMPORTANT: enctype must be set for file uploads -->
        <form method="POST" action="profile.php" enctype="multipart/form-data" class="space-y-6">
            
            <!-- HIDDEN: Profile Picture Upload Input -->
            <!-- We link this input to the clickable image via the 'for' attribute in the <label> -->
            <input id="profile_image" name="profile_image" type="file" accept="image/png, image/jpeg, image/gif" class="hidden" onchange="previewImage(event)">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Full Name -->
                <div>
                    <label for="full_name" class="block text-sm font-medium text-gray-700">Full Name</label>
                    <!-- --- Fix 7: Use 'first_name' for form value --- -->
                    <input id="full_name" name="full_name" type="text" value="<?php echo htmlspecialchars($userData['first_name'] ?? ''); ?>" required
                            class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <!-- Email (Readonly) -->
                <div>
                    <label for="email" class="block text-sm font-medium text-gray-700">Email Address</label>
                    <input id="email" type="email" value="<?php echo htmlspecialchars($userData['email'] ?? ''); ?>" readonly
                            class="mt-1 block w-full px-4 py-2 bg-gray-100 border border-gray-300 rounded-lg cursor-not-allowed">
                </div>
                <!-- Telegram Username -->
                <div>
                    <label for="telegram_username" class="block text-sm font-medium text-gray-700">Telegram Username</label>
                    <input id="telegram_username" name="telegram_username" type="text" value="<?php echo htmlspecialchars($userData['telegram_username'] ?? ''); ?>" placeholder="@username"
                            class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <!-- A/L Year (Readonly) -->
                <div>
                    <label for="a_l_year" class="block text-sm font-medium text-gray-700">A/L Year</label>
                    <input id="a_l_year" type="text" value="<?php echo htmlspecialchars($userData['a_l_year'] ?? ''); ?>" readonly
                            class="mt-1 block w-full px-4 py-2 bg-gray-100 border border-gray-300 rounded-lg cursor-not-allowed">
                </div>
                
            </div>

            <h3 class="text-xl font-bold text-gray-900 pt-4 border-t mt-6">Contact & Guardian Information</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Mobile Number -->
                <div>
                    <label for="mobile_number" class="block text-sm font-medium text-gray-700">Mobile Number</label>
                    <input id="mobile_number" name="mobile_number" type="tel" value="<?php echo htmlspecialchars($contactInfo['mobile_number'] ?? ''); ?>"
                            class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <!-- Guardian Name -->
                <div>
                    <label for="guardian_name" class="block text-sm font-medium text-gray-700">Guardian Name</label>
                    <input id="guardian_name" name="guardian_name" type="text" value="<?php echo htmlspecialchars($contactInfo['guardian_name'] ?? ''); ?>"
                            class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                </div>
                <!-- Guardian Phone -->
                <div>
                    <label for="guardian_phone" class="block text-sm font-medium text-gray-700">Guardian Phone</label>
                    <input id="guardian_phone" name="guardian_phone" type="tel" value="<?php echo htmlspecialchars($contactInfo['guardian_phone'] ?? ''); ?>"
                            class="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-indigo-500 focus:border-indigo-500">
                </div>
            </div>

            <button type="submit" name="update_profile" class="w-48 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 font-semibold transition duration-150 shadow-md">
                Save Changes
            </button>
        </form>
    </div>
</div>

<script>
    /**
     * Previews the selected image file locally before uploading.
     * @param {Event} event The file change event.
     */
    function previewImage(event) {
        const imageElement = document.getElementById('current_profile_image');
        const file = event.target.files[0];
        
        if (file) {
            const reader = new FileReader();
            
            // Basic client-side check for file type
            if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
                // You could display a visible error message here if needed.
                console.error('Invalid file type selected.');
                return;
            }
            
            reader.onload = function(e) {
                imageElement.src = e.target.result;
            }
            reader.readAsDataURL(file);
        }
    }
</script>

<?php render_main_content_end(); ?>