<?php
// edit_student_profile.php
// Handles the form to edit the student's profile.

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

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || $_SESSION['user_role'] !== 'student') {
    header("Location: index.php?page=login");
    exit();
}

require_once 'config/database.php';

$user_id = $_SESSION['user_id'] ?? null;
$profile_data = null;
$message = '';
$is_error = false;

// Fetch current profile data to pre-fill the form
if ($user_id) {
    try {
        $stmt = $pdo->prepare("
            SELECT 
                u.username,
                s.full_name,
                s.phone_number,
                s.address
            FROM users u
            JOIN student_profiles s ON u.id = s.user_id
            WHERE u.id = ?
        ");
        $stmt->execute([$user_id]);
        $profile_data = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$profile_data) {
            $message = "Profile not found.";
            $is_error = true;
        }

    } catch (PDOException $e) {
        $message = "Database error fetching profile: " . $e->getMessage();
        $is_error = true;
        error_log("Student Profile Fetch Error: " . $e->getMessage());
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$is_error) {
    $full_name = trim($_POST['full_name'] ?? '');
    $phone_number = trim($_POST['phone_number'] ?? ''); // Updated variable name
    $address = trim($_POST['address'] ?? '');

    if (empty($full_name)) {
        $message = "Full Name is required.";
        $is_error = true;
    }

    if (!$is_error) {
        try {
            // Update the correct table and column
            $stmt = $pdo->prepare("
                UPDATE student_profiles 
                SET 
                    full_name = ?,
                    phone_number = ?,
                    address = ?
                WHERE user_id = ?
            ");
            $stmt->execute([$full_name, $phone_number, $address, $user_id]);
            
            // Update session username if full name changed
            $_SESSION['username'] = $full_name;

            $message = "Profile updated successfully!";

        } catch (PDOException $e) {
            $message = "Database error updating profile: " . $e->getMessage();
            $is_error = true;
            error_log("Student Profile Update Error: " . $e->getMessage());
        }
    }
}

?>
<div class="w-full max-w-2xl mx-auto p-6 bg-white rounded-lg shadow-xl">
    <div class="flex justify-between items-center mb-8 pb-4 border-b border-gray-200">
        <h1 class="text-3xl font-extrabold text-gray-900">Edit Profile</h1>
        <a href="index.php?page=student_profile" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md hover:bg-gray-300 transition duration-300">
            Cancel
        </a>
    </div>

    <?php if ($message && !$is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-green-100 text-green-700 border border-green-200">
            <?php echo $message; ?>
        </div>
    <?php elseif ($is_error): ?>
        <div class="mb-6 p-4 rounded-md text-center text-lg bg-red-100 text-red-700 border border-red-200">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if ($profile_data): ?>
        <form action="index.php?page=edit_student_profile" method="POST" class="space-y-6">
            <div>
                <label for="full_name" class="block text-sm font-medium text-gray-700">Full Name</label>
                <input type="text" name="full_name" id="full_name" required value="<?php echo htmlspecialchars($profile_data['full_name']); ?>" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div>
                <label for="phone_number" class="block text-sm font-medium text-gray-700">Phone Number</label>
                <input type="tel" name="phone_number" id="phone_number" value="<?php echo htmlspecialchars($profile_data['phone_number']); ?>" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
            </div>
            <div>
                <label for="address" class="block text-sm font-medium text-gray-700">Address</label>
                <textarea name="address" id="address" rows="3" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"><?php echo htmlspecialchars($profile_data['address']); ?></textarea>
            </div>
            <div>
                <button type="submit" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    Save Changes
                </button>
            </div>
        </form>
    <?php endif; ?>
</div>