<?php
session_start();
session_regenerate_id(true);

// Enforce HTTPS
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit();
}

// Disable debug in production
if ($_SERVER['SERVER_NAME'] !== 'localhost') {
    ini_set('display_errors', 0);
    error_reporting(E_ALL & ~E_NOTICE);
}

// Check if admin is logged in
if (!isset($_SESSION['student_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php?error=" . urlencode("Please log in as an admin."));
    exit();
}

// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school_db";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    error_log("Connection failed: " . $e->getMessage());
    $error = "Connection failed. Please contact support.";
    header("Location: login.php?error=" . urlencode($error));
    exit();
}

// CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

// Fetch admin's student details
try {
    $stmt = $conn->prepare("SELECT name, grade, contact FROM students WHERE id = :student_id");
    $stmt->execute([':student_id' => $_SESSION['student_id']]);
    $admin_student = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$admin_student) {
        error_log("No admin student data found for student_id: " . $_SESSION['student_id']);
        $error = "Admin data not found.";
    }
} catch(PDOException $e) {
    error_log("Admin student fetch error: " . $e->getMessage());
    $error = "Error fetching admin's student data.";
}

// Fetch application details
$application = null;
if (isset($_GET['id']) && filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
    try {
        $stmt = $conn->prepare("SELECT e.*, s.name AS student_name FROM special_exams_applications e LEFT JOIN students s ON e.student_id = s.id WHERE e.id = :id");
        $stmt->execute([':id' => $_GET['id']]);
        $application = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$application) {
            error_log("No application found for id: " . $_GET['id']);
            $error = "Application not found.";
            header("Location: manage_special_exams.php?error=" . urlencode($error));
            exit();
        }
    } catch(PDOException $e) {
        error_log("Fetch application error: " . $e->getMessage());
        $error = "Error fetching application details.";
        header("Location: manage_special_exams.php?error=" . urlencode($error));
        exit();
    }
} else {
    $error = "Invalid application ID.";
    header("Location: manage_special_exams.php?error=" . urlencode($error));
    exit();
}

// Fetch students for dropdown
$students = [];
try {
    $stmt = $conn->query("SELECT id, name FROM students ORDER BY name");
    $students = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch(PDOException $e) {
    error_log("Students fetch error: " . $e->getMessage());
    $error = "Error fetching students.";
}

// Handle edit submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_application' && $_POST['csrf_token'] === $csrf_token) {
    error_log("POST data received: " . print_r($_POST, true));
    $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
    $student_id = filter_input(INPUT_POST, 'student_id', FILTER_VALIDATE_INT);
    $exam_code = trim(filter_input(INPUT_POST, 'exam_code', FILTER_SANITIZE_STRING));
    $reason = trim(filter_input(INPUT_POST, 'reason', FILTER_SANITIZE_STRING));
    $status = filter_input(INPUT_POST, 'status', FILTER_SANITIZE_STRING);

    if ($id && $student_id && $exam_code && $reason && in_array($status, ['pending', 'approved', 'rejected'])) {
        try {
            $stmt = $conn->prepare("SELECT id FROM students WHERE id = :student_id");
            $stmt->execute([':student_id' => $student_id]);
            if (!$stmt->fetch()) {
                throw new PDOException("Student ID does not exist.");
            }
            $stmt = $conn->prepare("SELECT id FROM special_exams_applications WHERE id = :id");
            $stmt->execute([':id' => $id]);
            if (!$stmt->fetch()) {
                throw new PDOException("Application ID does not exist.");
            }
            $stmt = $conn->prepare("UPDATE special_exams_applications SET student_id = :student_id, exam_code = :exam_code, reason = :reason, status = :status WHERE id = :id");
            $stmt->execute([
                ':student_id' => $student_id,
                ':exam_code' => $exam_code,
                ':reason' => $reason,
                ':status' => $status,
                ':id' => $id
            ]);
            $success = "Special exam application updated successfully.";
            header("Location: manage_special_exams.php?success=" . urlencode($success));
            exit();
        } catch(PDOException $e) {
            error_log("Edit special exam application error: " . $e->getMessage());
            $error = "Error updating special exam application: " . $e->getMessage();
        }
    } else {
        $error = "Invalid application details or status.";
    }
}

// Handle logout
if (isset($_POST['logout']) && $_POST['csrf_token'] === $csrf_token) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit();
}

// Handle redirect messages
$message = '';
$alert_type = '';
if (isset($_GET['error'])) {
    $message = htmlspecialchars($_GET['error']);
    $alert_type = 'alert-danger';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Edit special exam application for Gakero E.L.C.K High School.">
    <meta name="keywords" content="Gakero E.L.C.K High School, admin, special exams, edit">
    <meta name="author" content="Gakero E.L.C.K High School">
    <title>Edit Special Exam Application - Gakero E.L.C.K High School</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Poppins', sans-serif; background-color: #f5f6f5; color: #333; margin: 0; overflow-x: hidden; }
        .navbar { background-color: #003087; padding: 8px 0; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); z-index: 1001; position: sticky; top: 0; }
        .navbar-brand { font-size: 1.25rem; font-weight: 600; color: #fff !important; }
        .nav-link { font-size: 0.9rem; color: #fff !important; padding: 6px 12px; transition: color 0.3s ease, background-color 0.3s ease; }
        .nav-link:hover { color: #a9d6e5 !important; background-color: rgba(255, 255, 255, 0.1); border-radius: 4px; }
        .navbar-toggler { border-color: rgba(255, 255, 255, 0.5); }
        main { padding: 15px; min-height: calc(100vh - 48px); background-color: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); width: 100%; }
        footer { background-color: #003087; color: #fff; padding: 20px 0; margin-top: 20px; z-index: 999; width: 100%; }
        footer a { color: #a9d6e5; text-decoration: none; transition: color 0.3s ease; }
        footer a:hover { color: #fff; }
        .hero-section { background: linear-gradient(135deg, #003087, #005f73); border-radius: 8px; padding: 20px; margin-bottom: 2rem; }
        .hero-section h1 { font-size: 1.75rem; font-weight: 600; }
        .hero-section p { font-size: 1rem; }
        .section-title { font-size: 1.75rem; color: #003087; margin-bottom: 1rem; position: relative; }
        .section-title::after { content: ''; display: block; width: 50px; height: 3px; background: #003087; margin-top: 0.5rem; }
        .card { border: none; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: transform 0.3s ease, box-shadow 0.3s ease; }
        .card:hover { transform: translateY(-5px); box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2); }
        .card-body { padding: 1.5rem; }
        .btn-primary { background-color: #003087; border: none; padding: 0.75rem 1.5rem; border-radius: 8px; transition: background-color 0.3s ease; }
        .btn-primary:hover { background-color: #00205b; }
        .btn-secondary { background-color: #6c757d; border: none; padding: 0.75rem 1.5rem; border-radius: 8px; transition: background-color 0.3s ease; }
        .btn-secondary:hover { background-color: #5a6268; }
        .form-control { border-radius: 8px; border: 1px solid #ced4da; transition: border-color 0.3s ease, box-shadow 0.3s ease; cursor: text; }
        .form-control:focus { border-color: #003087; box-shadow: 0 0 5px rgba(0, 48, 135, 0.5); outline: 2px solid #003087; outline-offset: 2px; }
        .form-select:focus { border-color: #003087; box-shadow: 0 0 5px rgba(0, 48, 135, 0.5); outline: 2px solid #003087; outline-offset: 2px; }
        .form-label { color: #003087; }
        .alert { border-radius: 8px; font-size: 0.9rem; }
        @media (max-width: 991px) {
            .navbar-brand { font-size: 1.1rem; }
            .nav-link { font-size: 0.85rem; }
            .hero-section { padding: 2rem 0; }
            .hero-section h1 { font-size: 1.5rem; }
            .section-title { font-size: 1.5rem; }
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg bg-primary text-white">
        <div class="container-fluid">
            <a class="navbar-brand" href="index.php">Gakero E.L.C.K High School</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="index.php">Home</a></li>
                    <li class="nav-item"><a class="nav-link" href="about.php">About</a></li>
                    <li class="nav-item"><a class="nav-link" href="contact.php">Contact</a></li>
                    <li class="nav-item"><a class="nav-link" href="news.php">News</a></li>
                    <li class="nav-item">
                        <form method="POST" action="edit_special_exam.php?id=<?php echo htmlspecialchars($_GET['id']); ?>" style="display:inline;">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                            <button type="submit" name="logout" class="nav-link btn btn-link text-white">Logout</button>
                        </form>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <main class="p-4">
        <header class="hero-section text-white text-center py-4 rounded mb-4">
            <h1 class="display-5">Edit Special Exam Application</h1>
            <p class="lead">Modify the details of the special exam application for <?php echo htmlspecialchars($application['student_name'] ?? 'Unknown'); ?></p>
        </header>

        <?php if ($message): ?>
            <div class="alert <?php echo $alert_type; ?> alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <section class="mb-5">
            <h2 class="section-title">Edit Application</h2>
            <div class="card">
                <div class="card-body">
                    <form method="POST" id="editApplicationForm" onsubmit="return validateEditForm()">
                        <input type="hidden" name="action" value="edit_application">
                        <input type="hidden" name="id" value="<?php echo htmlspecialchars($application['id']); ?>">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <div class="mb-3">
                            <label for="edit_student_id" class="form-label">Student</label>
                            <select id="edit_student_id" name="student_id" class="form-control" required aria-describedby="edit_student_id_help">
                                <option value="">Select a student</option>
                                <?php foreach ($students as $student): ?>
                                    <option value="<?php echo htmlspecialchars($student['id']); ?>" <?php echo $student['id'] == $application['student_id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($student['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small id="edit_student_id_help" class="form-text text-muted">Choose the student applying for the special exam.</small>
                        </div>
                        <div class="mb-3">
                            <label for="edit_exam_code" class="form-label">Exam Code</label>
                            <input type="text" id="edit_exam_code" name="exam_code" class="form-control" value="<?php echo htmlspecialchars($application['exam_code']); ?>" required aria-describedby="edit_exam_code_help">
                            <small id="edit_exam_code_help" class="form-text text-muted">Enter the exam code (e.g., MATH2023).</small>
                        </div>
                        <div class="mb-3">
                            <label for="edit_reason" class="form-label">Reason</label>
                            <textarea id="edit_reason" name="reason" class="form-control" rows="4" required aria-describedby="edit_reason_help"><?php echo htmlspecialchars($application['reason']); ?></textarea>
                            <small id="edit_reason_help" class="form-text text-muted">Provide the reason for the special exam.</small>
                        </div>
                        <div class="mb-3">
                            <label for="edit_status" class="form-label">Status</label>
                            <select id="edit_status" name="status" class="form-control" required aria-describedby="edit_status_help">
                                <option value="pending" <?php echo $application['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="approved" <?php echo $application['status'] === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                <option value="rejected" <?php echo $application['status'] === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                            <small id="edit_status_help" class="form-text text-muted">Select the status of the application.</small>
                        </div>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                            <a href="manage_special_exams.php" class="btn btn-secondary">Back to Dashboard</a>
                        </div>
                    </form>
                </div>
            </div>
        </section>
    </main>

    <footer class="bg-dark text-white text-center py-4">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> Gakero E.L.C.K High School. All rights reserved.</p>
            <p>Kisii County, Gucha Sub-county, Misesi Location</p>
            <p>Email: <a href="mailto:info@gakeroelckhigh.edu" class="text-white">info@gakeroelckhigh.edu</a> | Phone: <a href="tel:+1234567890" class="text-white">(123) 456-7890</a></p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Client-side validation for edit form
        function validateEditForm() {
            const studentId = document.getElementById('edit_student_id').value;
            const examCode = document.getElementById('edit_exam_code').value.trim();
            const reason = document.getElementById('edit_reason').value.trim();
            const status = document.getElementById('edit_status').value;

            if (!studentId || !examCode || !reason || !['pending', 'approved', 'rejected'].includes(status)) {
                alert('Please fill in all fields correctly.');
                return false;
            }
            return true;
        }

        // Focus on first input
        document.addEventListener('DOMContentLoaded', function () {
            const firstInput = document.querySelector('select, input, textarea');
            if (firstInput) {
                firstInput.focus();
            }
        });
    </script>
</body>
</html>