<?php
/**
 * ===================================================================================
 * Edit Class Page
 * ===================================================================================
 *
 * File: edit_class.php
 * Location: /homework_portal/admin/edit_class.php
 *
 * Purpose:
 * 1. Provides a form for Super Admins to edit an existing class.
 * 2. Fetches current class details to pre-fill the form.
 * 3. Handles form submission to update the class record.
 */

require_once '../config.php';

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

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

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

// --- Fetch existing class data ---
try {
    $stmt = $pdo->prepare("SELECT id, class_name, teacher_id FROM classes WHERE id = ?");
    $stmt->execute([$class_id]);
    $class = $stmt->fetch();
    if (!$class) {
        header('Location: manage_classes.php?error=Class not found.');
        exit();
    }
    // Fetch all teachers for the dropdown
    $teachers = $pdo->query("SELECT id, full_name FROM teachers ORDER BY full_name ASC")->fetchAll();
} catch (PDOException $e) {
    die("Database error fetching data.");
}

// --- Handle Form Submission to UPDATE class ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_class'])) {
    $class_name = trim($_POST['class_name'] ?? '');
    $teacher_id = !empty($_POST['teacher_id']) ? (int)$_POST['teacher_id'] : null;

    if (empty($class_name)) {
        $errors[] = "Class name is required.";
    } else {
        // Check if the new name is taken by ANOTHER class
        $check_stmt = $pdo->prepare("SELECT id FROM classes WHERE class_name = ? AND id != ?");
        $check_stmt->execute([$class_name, $class_id]);
        if ($check_stmt->fetch()) {
            $errors[] = "Another class with this name already exists.";
        }
    }

    if (empty($errors)) {
        $sql = "UPDATE classes SET class_name = ?, teacher_id = ? WHERE id = ?";
        try {
            $pdo->prepare($sql)->execute([$class_name, $teacher_id, $class_id]);
            $success_message = "Class details updated successfully!";
            // Re-fetch data to show updated info in the form
            $stmt->execute([$class_id]);
            $class = $stmt->fetch();
        } catch (PDOException $e) {
            $errors[] = "Database error: Could not update class.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Class - 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_classes.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 Classes
            </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 Class: <?php echo e($class['class_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_class.php?id=<?php echo $class_id; ?>" method="POST" class="space-y-6">
                <div>
                    <label for="class_name" class="block text-sm font-medium text-gray-700">Class Name</label>
                    <input type="text" name="class_name" id="class_name" value="<?php echo e($class['class_name']); ?>" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                </div>
                <div>
                    <label for="teacher_id" class="block text-sm font-medium text-gray-700">Assign Class Teacher (Optional)</label>
                    <select name="teacher_id" id="teacher_id" class="mt-1 block w-full p-2 border border-gray-300 rounded-md">
                        <option value="">-- No specific teacher --</option>
                        <?php foreach($teachers as $teacher): ?>
                            <option value="<?php echo e($teacher['id']); ?>" <?php if($teacher['id'] == $class['teacher_id']) echo 'selected'; ?>>
                                <?php echo e($teacher['full_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="flex justify-end pt-4 border-t">
                    <a href="manage_classes.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_class" 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>
