<?php
/**
 * ===================================================================================
 * Edit Student Page (for Teachers)
 * ===================================================================================
 *
 * File: edit_student.php
 * Location: /homework_portal/teacher/edit_student.php
 *
 * Purpose:
 * 1. Provides a form for a teacher to edit a student's details.
 * 2. Ensures a teacher can only edit students in their assigned classes.
 * 3. Includes a "Back" button for better navigation.
 */

require_once '../config.php';

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

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

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

try {
    // --- Ownership Verification ---
    $sql = "
        SELECT s.id, s.full_name, s.index_number, s.parent_phone, s.class_id
        FROM students s
        WHERE s.id = ? AND s.class_id IN (
            SELECT tsc.class_id FROM teacher_subject_class tsc WHERE tsc.teacher_id = ?
        )
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$student_id, $teacher_id]);
    $student = $stmt->fetch();

    if (!$student) {
        header('Location: manage_students.php?error=Student not found or you do not have permission to edit.');
        exit();
    }
    
    // Fetch classes for the dropdown
    $class_stmt = $pdo->prepare("SELECT id, class_name FROM classes");
    $class_stmt->execute();
    $classes = $class_stmt->fetchAll();

} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

// --- Handle Form Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_student'])) {
    $full_name = trim($_POST['full_name'] ?? '');
    $index_number = trim($_POST['index_number'] ?? '');
    $parent_phone = trim($_POST['parent_phone'] ?? '');
    
    // Optional: Add more validation here
    
    try {
        // Only update these specific fields. Password is not changed here for security.
        $update_sql = "UPDATE students SET full_name = ?, index_number = ?, parent_phone = ? WHERE id = ?";
        $pdo->prepare($update_sql)->execute([$full_name, $index_number, $parent_phone, $student_id]);
        $success_message = "Student details updated successfully!";
        // Refetch the student data to display the changes
        $stmt->execute([$student_id, $teacher_id]);
        $student = $stmt->fetch();
    } catch (PDOException $e) {
        $errors[] = "Could not update student details.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Student - Teacher Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
     <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&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-8 px-4">
        <div class="mb-4">
            <a href="manage_students.php" class="flex items-center text-teal-600 hover:text-teal-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 My Students
            </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 Student: <?php echo e($student['full_name']); ?></h1>
            
            <?php if($success_message): ?><div class="p-4 mb-4 text-sm text-green-700 bg-green-100 rounded-lg"><?php echo $success_message; ?></div><?php endif; ?>
            <?php if(!empty($errors)): ?><div class="p-4 mb-4 text-sm text-red-700 bg-red-100 rounded-lg"><ul class="list-disc list-inside"><?php foreach($errors as $e) echo "<li>$e</li>"; ?></ul></div><?php endif; ?>

            <form action="edit_student.php?id=<?php echo $student_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" value="<?php echo e($student['full_name']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                </div>
                 <div>
                    <label for="index_number" class="block text-sm font-medium text-gray-700">Index Number</label>
                    <input type="text" name="index_number" value="<?php echo e($student['index_number']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                </div>
                 <div>
                    <label for="parent_phone" class="block text-sm font-medium text-gray-700">Parent's Phone</label>
                    <input type="tel" name="parent_phone" value="<?php echo e($student['parent_phone']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                </div>
                 <div class="flex justify-end pt-4 border-t">
                    <a href="manage_students.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_student" class="px-6 py-2 bg-teal-600 text-white font-semibold rounded-lg shadow hover:bg-teal-700">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>
