<?php
session_start();

// Check if admin is logged in
if (!isset($_SESSION['student_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    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 check the server logs.";
}

// Fetch admin's student details (if student_id matches)
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);
} catch(PDOException $e) {
    error_log("Admin student fetch error: " . $e->getMessage());
    $error = "Error fetching admin's student data.";
}

// Fetch all timetable entries
try {
    $timetable_stmt = $conn->query("SELECT id, class, day, period, subject, teacher FROM timetables ORDER BY class, FIELD(day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'), period");
    $timetables = $timetable_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    error_log("Timetables fetch error: " . $e->getMessage());
    $error = "Error fetching timetables.";
}

// Handle add/edit timetable
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    $action = $_POST['action'];
    $class = filter_input(INPUT_POST, 'class', FILTER_SANITIZE_STRING);
    $day = filter_input(INPUT_POST, 'day', FILTER_SANITIZE_STRING);
    $period = filter_input(INPUT_POST, 'period', FILTER_SANITIZE_STRING);
    $subject = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_STRING);
    $teacher = filter_input(INPUT_POST, 'teacher', FILTER_SANITIZE_STRING);
    $timetable_id = filter_input(INPUT_POST, 'timetable_id', FILTER_VALIDATE_INT);

    if ($action === 'add' || $action === 'edit') {
        if (empty($class) || empty($day) || empty($period) || empty($subject) || empty($teacher)) {
            $error = "All fields are required.";
        } else {
            try {
                if ($action === 'add') {
                    $stmt = $conn->prepare("INSERT INTO timetables (class, day, period, subject, teacher) VALUES (:class, :day, :period, :subject, :teacher)");
                    $stmt->execute([':class' => $class, ':day' => $day, ':period' => $period, ':subject' => $subject, ':teacher' => $teacher]);
                    $success = "Timetable entry added successfully.";
                } elseif ($action === 'edit' && $timetable_id) {
                    $stmt = $conn->prepare("UPDATE timetables SET class = :class, day = :day, period = :period, subject = :subject, teacher = :teacher WHERE id = :id");
                    $stmt->execute([':class' => $class, ':day' => $day, ':period' => $period, ':subject' => $subject, ':teacher' => $teacher, ':id' => $timetable_id]);
                    $success = "Timetable entry updated successfully.";
                }
            } catch(PDOException $e) {
                error_log("Timetable {$action} error: " . $e->getMessage());
                $error = "Error {$action}ing timetable entry.";
            }
        }
    } elseif ($action === 'delete' && $timetable_id) {
        try {
            $stmt = $conn->prepare("DELETE FROM timetables WHERE id = :id");
            $stmt->execute([':id' => $timetable_id]);
            $success = "Timetable entry deleted successfully.";
        } catch(PDOException $e) {
            error_log("Timetable delete error: " . $e->getMessage());
            $error = "Error deleting timetable entry.";
        }
    }
    // Refresh timetable list
    $timetable_stmt = $conn->query("SELECT id, class, day, period, subject, teacher FROM timetables ORDER BY class, FIELD(day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'), period");
    $timetables = $timetable_stmt->fetchAll(PDO::FETCH_ASSOC);
}

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

<!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="Manage class timetables for Gakero E.L.C.K High School.">
    <meta name="keywords" content="Gakero E.L.C.K High School, admin, timetable management">
    <meta name="author" content="Gakero E.L.C.K High School">
    <title>Manage Timetables - 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 rel="stylesheet" href="css/styles.css">
</head>
<body>
    <div class="d-flex">
        <!-- Sticky Sidebar -->
        <nav class="sidebar bg-primary text-white" id="sidebar">
            <div class="sidebar-header text-center p-3">
                <h4 class="mb-0">Gakero E.L.C.K</h4>
            </div>
            <div class="profile-card p-3">
                <div class="text-center">
                    <div class="avatar bg-light text-primary rounded-circle mx-auto mb-2">
                        <i class="bi bi-person-circle fs-2"></i>
                    </div>
                    <h6 class="mb-1">Admin</h6>
                    <small class="text-white-50">ID: <?php echo htmlspecialchars($_SESSION['student_id'] ?? 'N/A'); ?></small><br>
                    <?php if ($admin_student): ?>
                        <small class="text-white-50">Name: <?php echo htmlspecialchars($admin_student['name'] ?? 'N/A'); ?></small><br>
                        <small class="text-white-50">Grade: <?php echo htmlspecialchars($admin_student['grade'] ?? 'N/A'); ?></small><br>
                        <small class="text-white-50">Contact: <?php echo htmlspecialchars($admin_student['contact'] ?? 'N/A'); ?></small>
                    <?php else: ?>
                        <small class="text-white-50">No student profile found.</small>
                    <?php endif; ?>
                </div>
            </div>
            <ul class="nav flex-column p-3">
                <li class="nav-item">
                    <a class="nav-link text-white" href="manage_news.php"><i class="bi bi-newspaper me-2"></i>Manage News</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="manage_students.php"><i class="bi bi-people me-2"></i>Manage Students</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white active" href="manage_timetables.php"><i class="bi bi-calendar me-2"></i>Manage Timetables</a>
                </li>
                <li class="nav-item">
                    <form method="POST" action="admin_page.php">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <button type="submit" name="logout" class="nav-link text-white bg-transparent border-0"><i class="bi bi-box-arrow-right me-2"></i>Logout</button>
                    </form>
                </li>
            </ul>
        </nav>

        <!-- Main Content -->
        <main class="flex-grow-1 p-4">
            <button class="btn btn-primary d-lg-none mb-3" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebarOffcanvas" aria-controls="sidebarOffcanvas">
                <i class="bi bi-list"></i> Menu
            </button>
            <div class="offcanvas offcanvas-start bg-primary text-white" tabindex="-1" id="sidebarOffcanvas" aria-labelledby="sidebarOffcanvasLabel">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="sidebarOffcanvasLabel">Gakero E.L.C.K</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <div class="profile-card p-3">
                        <div class="text-center">
                            <div class="avatar bg-light text-primary rounded-circle mx-auto mb-2">
                                <i class="bi bi-person-circle fs-2"></i>
                            </div>
                            <h6 class="mb-1">Admin</h6>
                            <small class="text-white-50">ID: <?php echo htmlspecialchars($_SESSION['student_id'] ?? 'N/A'); ?></small><br>
                            <?php if ($admin_student): ?>
                                <small class="text-white-50">Name: <?php echo htmlspecialchars($admin_student['name'] ?? 'N/A'); ?></small><br>
                                <small class="text-white-50">Grade: <?php echo htmlspecialchars($admin_student['grade'] ?? 'N/A'); ?></small><br>
                                <small class="text-white-50">Contact: <?php echo htmlspecialchars($admin_student['contact'] ?? 'N/A'); ?></small>
                            <?php else: ?>
                                <small class="text-white-50">No student profile found.</small>
                            <?php endif; ?>
                        </div>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="manage_news.php"><i class="bi bi-newspaper me-2"></i>Manage News</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="manage_students.php"><i class="bi bi-people me-2"></i>Manage Students</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white active" href="manage_timetables.php"><i class="bi bi-calendar me-2"></i>Manage Timetables</a>
                        </li>
                        <li class="nav-item">
                            <form method="POST" action="admin_page.php">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                <button type="submit" name="logout" class="nav-link text-white bg-transparent border-0"><i class="bi bi-box-arrow-right me-2"></i>Logout</button>
                            </form>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- Main Content -->
            <div class="container">
                <h2 class="section-title">Manage Timetables</h2>
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($error); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($success); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Add Timetable Form -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">Add Timetable Entry</h5>
                        <form method="POST">
                            <input type="hidden" name="action" value="add">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                            <div class="mb-3">
                                <label for="class" class="form-label">Class</label>
                                <input type="text" id="class" name="class" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label for="day" class="form-label">Day</label>
                                <select id="day" name="day" class="form-select" required>
                                    <option value="Monday">Monday</option>
                                    <option value="Tuesday">Tuesday</option>
                                    <option value="Wednesday">Wednesday</option>
                                    <option value="Thursday">Thursday</option>
                                    <option value="Friday">Friday</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label for="period" class="form-label">Period</label>
                                <input type="text" id="period" name="period" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label for="subject" class="form-label">Subject</label>
                                <input type="text" id="subject" name="subject" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label for="teacher" class="form-label">Teacher</label>
                                <input type="text" id="teacher" name="teacher" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-primary">Add Timetable Entry</button>
                        </form>
                    </div>
                </div>

                <!-- Timetable Table -->
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th scope="col">ID</th>
                                <th scope="col">Class</th>
                                <th scope="col">Day</th>
                                <th scope="col">Period</th>
                                <th scope="col">Subject</th>
                                <th scope="col">Teacher</th>
                                <th scope="col">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($timetables)): ?>
                                <?php foreach ($timetables as $timetable): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($timetable['id']); ?></td>
                                        <td><?php echo htmlspecialchars($timetable['class']); ?></td>
                                        <td><?php echo htmlspecialchars($timetable['day']); ?></td>
                                        <td><?php echo htmlspecialchars($timetable['period']); ?></td>
                                        <td><?php echo htmlspecialchars($timetable['subject']); ?></td>
                                        <td><?php echo htmlspecialchars($timetable['teacher']); ?></td>
                                        <td>
                                            <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editTimetableModal<?php echo $timetable['id']; ?>">Edit</button>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="timetable_id" value="<?php echo $timetable['id']; ?>">
                                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                <button type="submit" class="btn btn-outline-danger btn-sm" onclick="return confirm('Are you sure you want to delete this timetable entry?');">Delete</button>
                                            </form>
                                        </td>
                                    </tr>
                                    <!-- Edit Timetable Modal -->
                                    <div class="modal fade" id="editTimetableModal<?php echo $timetable['id']; ?>" tabindex="-1" aria-labelledby="editTimetableModalLabel<?php echo $timetable['id']; ?>" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="editTimetableModalLabel<?php echo $timetable['id']; ?>">Edit Timetable Entry</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <form method="POST">
                                                        <input type="hidden" name="action" value="edit">
                                                        <input type="hidden" name="timetable_id" value="<?php echo $timetable['id']; ?>">
                                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                        <div class="mb-3">
                                                            <label for="class<?php echo $timetable['id']; ?>" class="form-label">Class</label>
                                                            <input type="text" id="class<?php echo $timetable['id']; ?>" name="class" class="form-control" value="<?php echo htmlspecialchars($timetable['class']); ?>" required>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="day<?php echo $timetable['id']; ?>" class="form-label">Day</label>
                                                            <select id="day<?php echo $timetable['id']; ?>" name="day" class="form-select" required>
                                                                <option value="Monday" <?php echo $timetable['day'] === 'Monday' ? 'selected' : ''; ?>>Monday</option>
                                                                <option value="Tuesday" <?php echo $timetable['day'] === 'Tuesday' ? 'selected' : ''; ?>>Tuesday</option>
                                                                <option value="Wednesday" <?php echo $timetable['day'] === 'Wednesday' ? 'selected' : ''; ?>>Wednesday</option>
                                                                <option value="Thursday" <?php echo $timetable['day'] === 'Thursday' ? 'selected' : ''; ?>>Thursday</option>
                                                                <option value="Friday" <?php echo $timetable['day'] === 'Friday' ? 'selected' : ''; ?>>Friday</option>
                                                            </select>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="period<?php echo $timetable['id']; ?>" class="form-label">Period</label>
                                                            <input type="text" id="period<?php echo $timetable['id']; ?>" name="period" class="form-control" value="<?php echo htmlspecialchars($timetable['period']); ?>" required>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="subject<?php echo $timetable['id']; ?>" class="form-label">Subject</label>
                                                            <input type="text" id="subject<?php echo $timetable['id']; ?>" name="subject" class="form-control" value="<?php echo htmlspecialchars($timetable['subject']); ?>" required>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="teacher<?php echo $timetable['id']; ?>" class="form-label">Teacher</label>
                                                            <input type="text" id="teacher<?php echo $timetable['id']; ?>" name="teacher" class="form-control" value="<?php echo htmlspecialchars($timetable['teacher']); ?>" required>
                                                        </div>
                                                        <button type="submit" class="btn btn-primary">Save Changes</button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="7" class="text-center">No timetable entries found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>

    <!-- Footer -->
    <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-cunty,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>
</body>
</html>