<?php
/**
 * ===================================================================================
 * Edit Teacher Page
 * ===================================================================================
 *
 * File: edit_teacher.php
 * Location: /homework_portal/admin/edit_teacher.php
 *
 * Purpose:
 * 1. Provides a form for Super Admins to edit an existing teacher's details.
 * 2. Fetches the teacher's current information to pre-fill the form.
 * 3. Handles form submission to update the teacher's record in the database.
 */

require_once '../config.php';

// --- Security Check ---
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$teacher_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$errors = [];
$success_message = '';

if ($teacher_id <= 0) {
    header('Location: manage_teachers.php');
    exit();
}

// --- Fetch existing teacher data ---
try {
    $stmt = $pdo->prepare("SELECT id, full_name, email FROM teachers WHERE id = ?");
    $stmt->execute([$teacher_id]);
    $teacher = $stmt->fetch();
    if (!$teacher) {
        header('Location: manage_teachers.php?error=Teacher not found.');
        exit();
    }
} catch (PDOException $e) {
    die("Database error fetching teacher data.");
}

// --- Handle Form Submission to UPDATE teacher ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_teacher'])) {
    $full_name = trim($_POST['full_name'] ?? '');
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
    $password = $_POST['password'] ?? ''; // Password is optional

    // Validation
    if (empty($full_name)) $errors[] = "Full name is required.";
    if (empty($email)) $errors[] = "A valid email is required.";

    // Check if new email is taken by ANOTHER teacher
    if (empty($errors)) {
        $check_stmt = $pdo->prepare("SELECT id FROM teachers WHERE email = ? AND id != ?");
        $check_stmt->execute([$email, $teacher_id]);
        if ($check_stmt->fetch()) {
            $errors[] = "Another teacher is already using this email address.";
        }
    }

    if (empty($errors)) {
        // Prepare SQL based on whether password is being changed
        if (!empty($password)) {
            if(strlen($password) < 8) {
                 $errors[] = "New password must be at least 8 characters long.";
            } else {
                // If new password is provided
                $password_hash = password_hash($password, PASSWORD_DEFAULT);
                $sql = "UPDATE teachers SET full_name = ?, email = ?, password_hash = ? WHERE id = ?";
                $params = [$full_name, $email, $password_hash, $teacher_id];
            }
        } else {
            // If password field is left blank
            $sql = "UPDATE teachers SET full_name = ?, email = ? WHERE id = ?";
            $params = [$full_name, $email, $teacher_id];
        }

        if(empty($errors)) {
            try {
                $pdo->prepare($sql)->execute($params);
                $success_message = "Teacher details updated successfully!";
                // Re-fetch data to show updated info in the form
                $stmt->execute([$teacher_id]);
                $teacher = $stmt->fetch();
            } catch (PDOException $e) {
                $errors[] = "Database error: Could not update teacher.";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Teacher - Admin Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f9ff; }
        .font-brand { font-family: 'Baloo 2', cursive; }
    </style>
</head>
<body class="min-h-screen">
    <div class="max-w-2xl mx-auto py-10">
        <div class="mb-4">
            <a href="manage_teachers.php" class="flex items-center text-blue-600 hover:text-blue-800 font-medium">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                Back to Manage Teachers
            </a>
        </div>
        <div class="bg-white p-8 rounded-lg shadow-lg">
            <h1 class="text-2xl font-bold text-gray-800 mb-6 font-brand">Edit Teacher: <?php echo e($teacher['full_name']); ?></h1>

            <?php if ($success_message): ?><div class="p-4 mb-4 text-sm text-green-800 bg-green-100 rounded-lg"><?php echo e($success_message); ?></div><?php endif; ?>
            <?php if (!empty($errors)): ?><div class="p-4 mb-4 text-sm text-red-800 bg-red-100 rounded-lg"><ul class="list-disc list-inside"><?php foreach ($errors as $error) echo "<li>" . e($error) . "</li>"; ?></ul></div><?php endif; ?>

            <form action="edit_teacher.php?id=<?php echo $teacher_id; ?>" 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" value="<?php echo e($teacher['full_name']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                </div>
                <div>
                    <label for="email" class="block text-sm font-medium text-gray-700">Email Address</label>
                    <input type="email" name="email" id="email" value="<?php echo e($teacher['email']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                </div>
                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700">New Password (Optional)</label>
                    <input type="password" name="password" id="password" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" placeholder="Leave blank to keep current password">
                </div>
                <div class="flex justify-end pt-4 border-t">
                    <a href="manage_teachers.php" class="px-6 py-2 text-gray-600 font-medium rounded-lg hover:bg-gray-100 mr-4">Cancel</a>
                    <button type="submit" name="update_teacher" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow hover:bg-blue-700">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>
