<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";

// Check if staff is logged in
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$staff_email = $_SESSION['email'];
$staff_name = $_SESSION['staffname'] ?? 'Staff';

// Function to generate course code from course name
function generateCourseCode($course_name) {
    // Remove special characters and extra spaces
    $clean_name = preg_replace('/[^a-zA-Z0-9\s]/', '', $course_name);
    $clean_name = trim($clean_name);
    
    // Get first 5 characters from the course name
    $code = substr($clean_name, 0, 5);
    
    // Convert to uppercase
    $code = strtoupper($code);
    
    // If course name is less than 5 characters, pad with X
    if (strlen($code) < 5) {
        $code = str_pad($code, 5, 'X', STR_PAD_RIGHT);
    }
    
    // Add 3-digit random number
    $random_num = rand(100, 999);
    
    return $code . $random_num;
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_timetable'])) {
        // Add new timetable entry
        $course_code = mysqli_real_escape_string($conn, $_POST['course_code']);
        $course_name = mysqli_real_escape_string($conn, $_POST['course_name']);
        $program = mysqli_real_escape_string($conn, $_POST['program']);
        $intake = mysqli_real_escape_string($conn, $_POST['intake']);
        $day_of_week = mysqli_real_escape_string($conn, $_POST['day_of_week']);
        $start_time = mysqli_real_escape_string($conn, $_POST['start_time']);
        $end_time = mysqli_real_escape_string($conn, $_POST['end_time']);
        $selected_staff_name = mysqli_real_escape_string($conn, $_POST['staff_name']);
        $selected_staff_id = mysqli_real_escape_string($conn, $_POST['staff_id']);

        // Check for time conflicts (only for the selected staff)
        $conflict_check = "SELECT * FROM timetable 
                          WHERE staff_id = '$selected_staff_id' 
                          AND day_of_week = '$day_of_week'
                          AND (
                            ('$start_time' >= start_time AND '$start_time' < end_time) OR
                            ('$end_time' > start_time AND '$end_time' <= end_time) OR
                            ('$start_time' <= start_time AND '$end_time' >= end_time)
                          )";
        
        $conflict_result = mysqli_query($conn, $conflict_check);
        
        if (!$conflict_result) {
            $message = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                        <i class='fas fa-times-circle me-2'></i>Error checking time conflicts: " . mysqli_error($conn) . "
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
        } elseif (mysqli_num_rows($conflict_result) > 0) {
            $message = "<div class='alert alert-warning alert-dismissible fade show' role='alert'>
                        <i class='fas fa-exclamation-triangle me-2'></i>Time conflict detected! The selected staff already has a class scheduled during this time.
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
        } else {
            $insert_query = "INSERT INTO timetable 
                            (course_code, course_name, program, intake, staff_id, staff_name, 
                             day_of_week, start_time, end_time) 
                            VALUES ('$course_code', '$course_name', '$program', '$intake', 
                                    '$selected_staff_id', '$selected_staff_name', '$day_of_week', '$start_time', 
                                    '$end_time')";
            
            if (mysqli_query($conn, $insert_query)) {
                $message = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                            <i class='fas fa-check-circle me-2'></i>Timetable entry added successfully!
                            <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                          </div>";
            } else {
                $message = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                            <i class='fas fa-times-circle me-2'></i>Error adding timetable entry: " . mysqli_error($conn) . "
                            <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                          </div>";
            }
        }
        
    } elseif (isset($_POST['update_timetable'])) {
        // Update timetable entry
        $id = mysqli_real_escape_string($conn, $_POST['id']);
        $course_code = mysqli_real_escape_string($conn, $_POST['course_code']);
        $course_name = mysqli_real_escape_string($conn, $_POST['course_name']);
        $program = mysqli_real_escape_string($conn, $_POST['program']);
        $intake = mysqli_real_escape_string($conn, $_POST['intake']);
        $day_of_week = mysqli_real_escape_string($conn, $_POST['day_of_week']);
        $start_time = mysqli_real_escape_string($conn, $_POST['start_time']);
        $end_time = mysqli_real_escape_string($conn, $_POST['end_time']);

        // Check for time conflicts (excluding current entry)
        $conflict_check = "SELECT * FROM timetable 
                          WHERE staff_id = '$staff_email' 
                          AND day_of_week = '$day_of_week'
                          AND id != '$id'
                          AND (
                            ('$start_time' >= start_time AND '$start_time' < end_time) OR
                            ('$end_time' > start_time AND '$end_time' <= end_time) OR
                            ('$start_time' <= start_time AND '$end_time' >= end_time)
                          )";
        
        $conflict_result = mysqli_query($conn, $conflict_check);
        
        if (!$conflict_result) {
            $message = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                        <i class='fas fa-times-circle me-2'></i>Error checking time conflicts: " . mysqli_error($conn) . "
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
        } elseif (mysqli_num_rows($conflict_result) > 0) {
            $message = "<div class='alert alert-warning alert-dismissible fade show' role='alert'>
                        <i class='fas fa-exclamation-triangle me-2'></i>Time conflict detected! You already have a class scheduled during this time.
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
        } else {
            $update_query = "UPDATE timetable SET 
                            course_code = '$course_code',
                            course_name = '$course_name',
                            program = '$program',
                            intake = '$intake',
                            day_of_week = '$day_of_week',
                            start_time = '$start_time',
                            end_time = '$end_time'
                            WHERE id = '$id' AND staff_id = '$staff_email'";
            
            if (mysqli_query($conn, $update_query)) {
                $message = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                            <i class='fas fa-check-circle me-2'></i>Timetable entry updated successfully!
                            <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                          </div>";
            } else {
                $message = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                            <i class='fas fa-times-circle me-2'></i>Error updating timetable entry: " . mysqli_error($conn) . "
                            <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                          </div>";
            }
        }
        
    } elseif (isset($_POST['delete_timetable'])) {
        // Delete timetable entry
        $id = mysqli_real_escape_string($conn, $_POST['id']);
        
        $delete_query = "DELETE FROM timetable WHERE id = '$id' AND staff_id = '$staff_email'";
        
        if (mysqli_query($conn, $delete_query)) {
            $message = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                        <i class='fas fa-check-circle me-2'></i>Timetable entry deleted successfully!
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
        } else {
            $message = "<div class='alert alert-danger alert-dismissible fade show' role='alert'>
                        <i class='fas fa-times-circle me-2'></i>Error deleting timetable entry: " . mysqli_error($conn) . "
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
        }
    }
}

// Get filter values
$filter_program = $_GET['program'] ?? '';
$filter_intake = $_GET['intake'] ?? '';
$filter_course = $_GET['course'] ?? '';

// Build filter conditions - staff can only see their own entries unless they're admin
$filter_conditions = ["staff_id = '$staff_email'"];
if (!empty($filter_program)) {
    $filter_conditions[] = "program = '$filter_program'";
}
if (!empty($filter_intake)) {
    $filter_conditions[] = "intake = '$filter_intake'";
}
if (!empty($filter_course)) {
    $filter_conditions[] = "course_code LIKE '%$filter_course%'";
}

$filter_sql = '';
if (!empty($filter_conditions)) {
    $filter_sql = "WHERE " . implode(' AND ', $filter_conditions);
}

// Get unique values for filters (only for current staff)
$programs_query = "SELECT DISTINCT program FROM timetable WHERE staff_id = '$staff_email' ORDER BY program";
$programs_result = mysqli_query($conn, $programs_query);

$intakes_query = "SELECT DISTINCT intake FROM timetable WHERE staff_id = '$staff_email' ORDER BY intake DESC";
$intakes_result = mysqli_query($conn, $intakes_query);

$courses_query = "SELECT DISTINCT course_code, course_name FROM timetable WHERE staff_id = '$staff_email' ORDER BY course_name";
$courses_result = mysqli_query($conn, $courses_query);

// Get available courses from course table for dropdown
$available_courses_query = "SELECT DISTINCT course, program FROM course ORDER BY course";
$available_courses_result = mysqli_query($conn, $available_courses_query);

// Reset result pointers for reuse
$programs_result_copy = $programs_result;
$intakes_result_copy = $intakes_result;
$courses_result_copy = $courses_result;

// Get timetable data
$timetable_query = "SELECT * FROM timetable $filter_sql ORDER BY 
                    FIELD(day_of_week, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'), 
                    start_time";
$timetable_result = mysqli_query($conn, $timetable_query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timetable Management</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #202342;
            --secondary: #2c3e50;
        }
        
        body {
            font-family: Arial, sans-serif;
            background-color: #f8f9fa;
            margin: 0;
            padding: 0;
        }
        
        .content {
            margin-left: 210px;
            padding: 20px;
            min-height: 100vh;
        }
        
        .btn {
            background: var(--primary) !important;
            color: white !important;
            border: none;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
        
        .btn-warning {
            background: #ffc107 !important;
            color: #000 !important;
        }
        
        .btn-danger {
            background: #dc3545 !important;
            color: white !important;
        }
        
        .table-container {
            overflow: hidden;
            margin-bottom: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .table-header {
            background: var(--secondary) !important;
            color: white;
            padding: 15px 20px;
            border-radius: 10px 10px 0 0;
        }
        
        .timetable-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .timetable-table th {
            background-color: #34495e;
            color: white;
            padding: 12px 15px;
            text-align: left;
            font-weight: 600;
            border-bottom: 2px solid #2c3e50;
        }
        
        .timetable-table td {
            padding: 12px 15px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .timetable-table tr:hover {
            background-color: #f8f9fa;
        }
        
        .time-slot {
            background: #ecf0f1;
            padding: 4px 8px;
            border-radius: 4px;
            font-weight: 600;
            font-size: 0.9em;
            color: #2c3e50;
        }
        
        .badge {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-program {
            background: #3498db;
            color: white;
        }
        
        .badge-intake {
            background: #e74c3c;
            color: white;
        }
        
        .filter-section {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .btn-add {
            background: var(--primary) !important;
            color: white !important;
            font-weight: 600;
            padding: 10px 20px;
        }
        
        .modal-header {
            border-radius: 10px 10px 0 0;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(32, 35, 66, 0.25);
        }
        
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 10px;
            }
            
            .table-responsive {
                overflow-x: auto;
            }
            
            .timetable-table {
                min-width: 800px;
            }
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
    
    <div class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <?php if (isset($message)) echo $message; ?>

                    <!-- Header Section -->
                    <div class="table-container">
                        <div class="table-header d-flex justify-content-between align-items-center">
                            <div>
                                <h4 class="mb-1"><i class="fas fa-calendar-alt me-2"></i>Timetable Management</h4>
                                <p class="mb-0">Welcome, <?php echo htmlspecialchars($staff_name); ?> (<?php echo htmlspecialchars($staff_email); ?>)</p>
                            </div>
                            <button type="button" class="btn btn-add" data-bs-toggle="modal" data-bs-target="#addTimetableModal">
                                <i class="fas fa-plus-circle me-2"></i>Add Timetable Entry
                            </button>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="filter-section">
                        <h5><i class="fas fa-filter me-2"></i>Filter Timetable</h5>
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Program</label>
                                <select name="program" class="form-select">
                                    <option value="">All Programs</option>
                                    <?php 
                                    if ($programs_result_copy && mysqli_num_rows($programs_result_copy) > 0):
                                        while ($program = mysqli_fetch_assoc($programs_result_copy)): 
                                    ?>
                                        <option value="<?php echo htmlspecialchars($program['program']); ?>" 
                                            <?php echo ($filter_program == $program['program']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($program['program']); ?>
                                        </option>
                                    <?php 
                                        endwhile;
                                    endif; 
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Intake</label>
                                <select name="intake" class="form-select">
                                    <option value="">All Intakes</option>
                                    <?php 
                                    if ($intakes_result_copy && mysqli_num_rows($intakes_result_copy) > 0):
                                        while ($intake = mysqli_fetch_assoc($intakes_result_copy)): 
                                    ?>
                                        <option value="<?php echo htmlspecialchars($intake['intake']); ?>" 
                                            <?php echo ($filter_intake == $intake['intake']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($intake['intake']); ?>
                                        </option>
                                    <?php 
                                        endwhile;
                                    endif; 
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Course</label>
                                <select name="course" class="form-select">
                                    <option value="">All Courses</option>
                                    <?php 
                                    if ($courses_result_copy && mysqli_num_rows($courses_result_copy) > 0):
                                        while ($course = mysqli_fetch_assoc($courses_result_copy)): 
                                    ?>
                                        <option value="<?php echo htmlspecialchars($course['course_code']); ?>" 
                                            <?php echo ($filter_course == $course['course_code']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($course['course_code'] . ' - ' . $course['course_name']); ?>
                                        </option>
                                    <?php 
                                        endwhile;
                                    endif; 
                                    ?>
                                </select>
                            </div>
                            <div class="col-12">
                                <button type="submit" class="btn btn-sm">
                                    <i class="fas fa-search me-2"></i>Apply Filters
                                </button>
                                <a href="timetable.php" class="btn btn-sm btn-secondary">
                                    <i class="fas fa-times me-2"></i>Clear Filters
                                </a>
                            </div>
                        </form>
                    </div>

                    <!-- Timetable Table -->
                    <div class="table-container">
                        <div class="table-header">
                            <h5 class="mb-0"><i class="fas fa-table me-2"></i>Timetable Entries</h5>
                        </div>
                        <div class="table-responsive">
                            <?php if ($timetable_result && mysqli_num_rows($timetable_result) > 0): ?>
                                <table class="timetable-table">
                                    <thead>
                                        <tr>
                                            <th>Course</th>
                                            <th>Program</th>
                                            <th>Intake</th>
                                            <th>Day</th>
                                            <th>Time</th>
                                            <th>Staff</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($entry = mysqli_fetch_assoc($timetable_result)): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($entry['course_code']); ?></strong><br>
                                                    <small class="text-muted"><?php echo htmlspecialchars($entry['course_name']); ?></small>
                                                </td>
                                                <td>
                                                    <span class="badge badge-program"><?php echo htmlspecialchars($entry['program']); ?></span>
                                                </td>
                                                <td>
                                                    <span class="badge badge-intake"><?php echo htmlspecialchars($entry['intake']); ?></span>
                                                </td>
                                                <td><?php echo htmlspecialchars($entry['day_of_week']); ?></td>
                                                <td>
                                                    <span class="time-slot">
                                                        <?php echo date('h:i A', strtotime($entry['start_time'])); ?> - 
                                                        <?php echo date('h:i A', strtotime($entry['end_time'])); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <small><?php echo htmlspecialchars($entry['staff_name']); ?></small><br>
                                                    <small class="text-muted"><?php echo htmlspecialchars($entry['staff_id']); ?></small>
                                                </td>
                                                <td>
                                                    <?php if ($entry['staff_id'] == $staff_email): ?>
                                                        <button type="button" class="btn btn-sm btn-warning" 
                                                                data-bs-toggle="modal" 
                                                                data-bs-target="#editTimetableModal"
                                                                data-id="<?php echo $entry['id']; ?>"
                                                                data-course-code="<?php echo htmlspecialchars($entry['course_code']); ?>"
                                                                data-course-name="<?php echo htmlspecialchars($entry['course_name']); ?>"
                                                                data-program="<?php echo htmlspecialchars($entry['program']); ?>"
                                                                data-intake="<?php echo htmlspecialchars($entry['intake']); ?>"
                                                                data-day="<?php echo htmlspecialchars($entry['day_of_week']); ?>"
                                                                data-start-time="<?php echo date('H:i', strtotime($entry['start_time'])); ?>"
                                                                data-end-time="<?php echo date('H:i', strtotime($entry['end_time'])); ?>">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                        <form method="POST" class="d-inline">
                                                            <input type="hidden" name="id" value="<?php echo $entry['id']; ?>">
                                                            <button type="submit" name="delete_timetable" class="btn btn-sm btn-danger" 
                                                                    onclick="return confirm('Are you sure you want to delete this timetable entry?')">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </form>
                                                    <?php else: ?>
                                                        <span class="text-muted">Read only</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                                    <h5 class="text-muted">No timetable entries found</h5>
                                    <p class="text-muted">Click "Add Timetable Entry" to create your first schedule.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Add Timetable Modal -->
        <div class="modal fade" id="addTimetableModal" tabindex="-1" aria-labelledby="addTimetableModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <form method="POST" action="">
                        <div class="modal-header" style="background: var(--primary); color: white;">
                            <h5 class="modal-title" id="addTimetableModalLabel">
                                <i class="fas fa-plus-circle me-2"></i>Add Timetable Entry
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row g-3">
                                <!-- Course Selection from Database -->
                                <div class="col-md-6">
                                    <label class="form-label">Select Course</label>
                                    <select name="course_name" class="form-select" id="courseSelect" required>
                                        <option value="">Select a course</option>
                                        <?php
                                        if ($available_courses_result && mysqli_num_rows($available_courses_result) > 0):
                                            while ($course = mysqli_fetch_assoc($available_courses_result)):
                                                $course_name = htmlspecialchars($course['course']);
                                                $course_program = htmlspecialchars($course['program'] ?? '');
                                                $display_text = $course_name . ($course_program ? " ($course_program)" : "");
                                        ?>
                                            <option value="<?php echo $course_name; ?>" data-program="<?php echo $course_program; ?>">
                                                <?php echo $display_text; ?>
                                            </option>
                                        <?php 
                                            endwhile;
                                        else:
                                            // If no courses in database, provide some sample options
                                        ?>
                                            <option value="Anatomy and Physiology">Anatomy and Physiology</option>
                                            <option value="Medical Biochemistry">Medical Biochemistry</option>
                                            <option value="Clinical Medicine">Clinical Medicine</option>
                                            <option value="Nursing Fundamentals">Nursing Fundamentals</option>
                                            <option value="Pharmacology">Pharmacology</option>
                                            <option value="Pathology">Pathology</option>
                                            <option value="Microbiology">Microbiology</option>
                                            <option value="Community Health">Community Health</option>
                                        <?php endif; ?>
                                    </select>
                                    <small class="form-text text-muted">Select a course from the list</small>
                                </div>
                                
                                <!-- Course Code (Auto-generated) -->
                                <div class="col-md-6">
                                    <label class="form-label">Course Code</label>
                                    <input type="text" name="course_code" class="form-control" id="courseCode" readonly required>
                                    <small class="form-text text-muted">Auto-generated from course name</small>
                                </div>
                                
                                <!-- Program (Auto-filled from course selection) -->
                                <div class="col-md-6">
                                    <label class="form-label">Program</label>
                                    <input type="text" name="program" class="form-control" id="programField" required>
                                    <small class="form-text text-muted">Auto-filled from course selection</small>
                                </div>
                                
                                <!-- Intake Dropdown -->
                                <div class="col-md-6">
                                    <label class="form-label">Intake</label>
                                    <select name="intake" class="form-select" required>
                                        <option value="">Select Intake</option>
                                        <?php
                                        // Fetch intakes from students table
                                        $intake_query = "SELECT DISTINCT intake FROM students WHERE intake IS NOT NULL AND intake != '' ORDER BY intake DESC";
                                        $intake_result = mysqli_query($conn, $intake_query);
                                        
                                        if ($intake_result && mysqli_num_rows($intake_result) > 0) {
                                            while ($intake = mysqli_fetch_assoc($intake_result)) {
                                                echo '<option value="' . htmlspecialchars($intake['intake']) . '">' . htmlspecialchars($intake['intake']) . '</option>';
                                            }
                                        } else {
                                            // Generate intake options
                                            $current_year = date('Y');
                                            for ($i = 0; $i < 3; $i++) {
                                                $year = $current_year - $i;
                                                echo '<option value="January ' . $year . '">January ' . $year . '</option>';
                                                echo '<option value="May ' . $year . '">May ' . $year . '</option>';
                                                echo '<option value="September ' . $year . '">September ' . $year . '</option>';
                                            }
                                        }
                                        ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-4">
                                    <label class="form-label">Day of Week</label>
                                    <select name="day_of_week" class="form-select" required>
                                        <option value="">Select Day</option>
                                        <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>
                                        <option value="Saturday">Saturday</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Start Time</label>
                                    <input type="time" name="start_time" class="form-control" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">End Time</label>
                                    <input type="time" name="end_time" class="form-control" required>
                                </div>
                                
                                <!-- Staff Selection -->
                                <div class="col-md-6">
                                    <label class="form-label">Staff Name</label>
                                    <select name="staff_name" class="form-select" id="staffNameSelect" required>
                                        <option value="">Select Staff</option>
                                        <?php
                                        $staff_query = mysqli_query($conn, "SELECT staffname, email FROM staff ORDER BY staffname");
                                        while($staff = mysqli_fetch_array($staff_query)){
                                            $selected = ($staff['email'] == $staff_email) ? 'selected' : '';
                                            echo '<option value="' . htmlspecialchars($staff['staffname']) . '" data-email="' . htmlspecialchars($staff['email']) . '" ' . $selected . '>' . htmlspecialchars($staff['staffname']) . '</option>';
                                        }
                                        ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-6">
                                    <label class="form-label">Staff Email</label>
                                    <input type="text" name="staff_id" class="form-control" id="staffEmail" readonly required>
                                    <small class="form-text text-muted">Staff email will auto-populate when you select staff name</small>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-2"></i>Cancel
                            </button>
                            <button type="submit" name="add_timetable" class="btn">
                                <i class="fas fa-save me-2"></i>Save Entry
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Edit Timetable Modal -->
        <div class="modal fade" id="editTimetableModal" tabindex="-1" aria-labelledby="editTimetableModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <form method="POST" action="">
                        <div class="modal-header bg-warning text-dark">
                            <h5 class="modal-title" id="editTimetableModalLabel">
                                <i class="fas fa-edit me-2"></i>Edit Timetable Entry
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <input type="hidden" name="id" id="edit_id">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Course Code</label>
                                    <input type="text" name="course_code" id="edit_course_code" class="form-control" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Course Name</label>
                                    <input type="text" name="course_name" id="edit_course_name" class="form-control" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Program</label>
                                    <input type="text" name="program" id="edit_program" class="form-control" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Intake</label>
                                    <input type="text" name="intake" id="edit_intake" class="form-control" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Day of Week</label>
                                    <select name="day_of_week" id="edit_day_of_week" 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>
                                        <option value="Saturday">Saturday</option>
                                        <option value="Sunday">Sunday</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Start Time</label>
                                    <input type="time" name="start_time" id="edit_start_time" class="form-control" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">End Time</label>
                                    <input type="time" name="end_time" id="edit_end_time" class="form-control" required>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                <i class="fas fa-times me-2"></i>Cancel
                            </button>
                            <button type="submit" name="update_timetable" class="btn btn-warning">
                                <i class="fas fa-save me-2"></i>Update Entry
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
        <script>
            // Function to generate course code from course name (5 letters + 3 random numbers)
            function generateCourseCode(courseName) {
                // Remove special characters and extra spaces
                let cleanName = courseName.replace(/[^a-zA-Z0-9\s]/g, '');
                cleanName = cleanName.trim();
                
                // Get first 5 characters
                let code = cleanName.substring(0, 5).toUpperCase();
                
                // Pad with X if less than 5 characters
                if (code.length < 5) {
                    code = code.padEnd(5, 'X');
                }
                
                // Add 3 random digits
                const randomNum = Math.floor(100 + Math.random() * 900);
                
                return code + randomNum;
            }

            // Auto-fill course code and program when course is selected
            document.getElementById('courseSelect').addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                const courseName = this.value;
                const courseProgram = selectedOption.getAttribute('data-program');
                const courseCodeInput = document.getElementById('courseCode');
                const programField = document.getElementById('programField');
                
                if (courseName) {
                    // Generate course code
                    courseCodeInput.value = generateCourseCode(courseName);
                    
                    // Fill program field
                    if (courseProgram) {
                        programField.value = courseProgram;
                    } else {
                        // Try to extract program from course name
                        const lowerName = courseName.toLowerCase();
                        if (lowerName.includes('nursing') || lowerName.includes('nurse')) {
                            programField.value = 'Diploma in Registered Nursing';
                        } else if (lowerName.includes('clinical') || lowerName.includes('medicine')) {
                            programField.value = 'Diploma in Clinical Officer General';
                        } else if (lowerName.includes('health') || lowerName.includes('care') || lowerName.includes('assistant')) {
                            programField.value = 'Certificate in Advanced Health Care Assistant';
                        } else {
                            programField.value = 'General Program';
                        }
                    }
                } else {
                    courseCodeInput.value = '';
                    programField.value = '';
                }
            });

            // Auto-fill staff email when staff name is selected
            document.getElementById('staffNameSelect').addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                const staffEmail = selectedOption.getAttribute('data-email');
                const staffEmailInput = document.getElementById('staffEmail');
                
                if (staffEmail) {
                    staffEmailInput.value = staffEmail;
                } else {
                    staffEmailInput.value = '';
                }
            });

            // Edit modal functionality
            const editTimetableModal = document.getElementById('editTimetableModal');
            if (editTimetableModal) {
                editTimetableModal.addEventListener('show.bs.modal', function (event) {
                    const button = event.relatedTarget;
                    const id = button.getAttribute('data-id');
                    const courseCode = button.getAttribute('data-course-code');
                    const courseName = button.getAttribute('data-course-name');
                    const program = button.getAttribute('data-program');
                    const intake = button.getAttribute('data-intake');
                    const day = button.getAttribute('data-day');
                    const startTime = button.getAttribute('data-start-time');
                    const endTime = button.getAttribute('data-end-time');

                    document.getElementById('edit_id').value = id;
                    document.getElementById('edit_course_code').value = courseCode;
                    document.getElementById('edit_course_name').value = courseName;
                    document.getElementById('edit_program').value = program;
                    document.getElementById('edit_intake').value = intake;
                    document.getElementById('edit_day_of_week').value = day;
                    document.getElementById('edit_start_time').value = startTime;
                    document.getElementById('edit_end_time').value = endTime;
                });
            }

            // Validate time inputs
            document.addEventListener('DOMContentLoaded', function() {
                const startTimeInputs = document.querySelectorAll('input[name="start_time"]');
                const endTimeInputs = document.querySelectorAll('input[name="end_time"]');
                
                startTimeInputs.forEach(input => {
                    input.addEventListener('change', function() {
                        const endTime = this.closest('.row').querySelector('input[name="end_time"]');
                        if (endTime.value && this.value >= endTime.value) {
                            alert('End time must be after start time');
                            this.value = '';
                        }
                    });
                });
                
                endTimeInputs.forEach(input => {
                    input.addEventListener('change', function() {
                        const startTime = this.closest('.row').querySelector('input[name="start_time"]');
                        if (startTime.value && this.value <= startTime.value) {
                            alert('End time must be after start time');
                            this.value = '';
                        }
                    });
                });
                
                // Auto-select current staff by default
                const staffSelect = document.getElementById('staffNameSelect');
                const staffEmailInput = document.getElementById('staffEmail');
                if (staffSelect && staffEmailInput) {
                    const currentStaffOption = staffSelect.querySelector('option[selected]');
                    if (currentStaffOption) {
                        const staffEmail = currentStaffOption.getAttribute('data-email');
                        if (staffEmail) {
                            staffEmailInput.value = staffEmail;
                        }
                    }
                }
            });
        </script>
    </div>
</body>
</html>