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

require_once '../config.php';

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

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

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

// --- Fetch existing subject data ---
try {
    $stmt = $pdo->prepare("SELECT id, subject_name FROM subjects WHERE id = ?");
    $stmt->execute([$subject_id]);
    $subject = $stmt->fetch();
    if (!$subject) {
        header('Location: manage_subjects.php?error=Subject not found.');
        exit();
    }
} catch (PDOException $e) {
    die("Database error fetching subject data.");
}

// --- Handle Form Submission to UPDATE subject ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_subject'])) {
    $subject_name = trim($_POST['subject_name'] ?? '');

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

    if (empty($errors)) {
        $sql = "UPDATE subjects SET subject_name = ? WHERE id = ?";
        try {
            $pdo->prepare($sql)->execute([$subject_name, $subject_id]);
            $success_message = "Subject updated successfully!";
            // Re-fetch data to show updated info in the form
            $stmt->execute([$subject_id]);
            $subject = $stmt->fetch();
        } catch (PDOException $e) {
            $errors[] = "Database error: Could not update subject.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Subject - 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_subjects.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 Subjects
            </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 Subject: <?php echo e($subject['subject_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_subject.php?id=<?php echo $subject_id; ?>" method="POST" class="space-y-6">
                <div>
                    <label for="subject_name" class="block text-sm font-medium text-gray-700">Subject Name</label>
                    <input type="text" name="subject_name" id="subject_name" value="<?php echo e($subject['subject_name']); ?>" 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_subjects.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_subject" 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>
