<?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';

// Create meetings table if it doesn't exist
$createTableQuery = "CREATE TABLE IF NOT EXISTS meetings (
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    meeting_id VARCHAR(50) UNIQUE NOT NULL,
    course_code VARCHAR(50) NOT NULL,
    course_name VARCHAR(100) NOT NULL,
    program VARCHAR(100) NOT NULL,
    intake VARCHAR(50) NOT NULL,
    year VARCHAR(20) NOT NULL,
    staff_id VARCHAR(100) NOT NULL,
    staff_name VARCHAR(100) NOT NULL,
    meeting_title VARCHAR(200) NOT NULL,
    meeting_description TEXT,
    scheduled_time DATETIME,
    meeting_password VARCHAR(50),
    max_participants INT DEFAULT 50,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_staff (staff_id),
    INDEX idx_course (course_code),
    INDEX idx_program_intake (program, intake)
)";

mysqli_query($conn, $createTableQuery);

// Handle meeting creation
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['create_meeting'])) {
        $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']);
        $year = mysqli_real_escape_string($conn, $_POST['year']);
        $meeting_title = mysqli_real_escape_string($conn, $_POST['meeting_title']);
        $meeting_description = mysqli_real_escape_string($conn, $_POST['meeting_description']);
        $scheduled_time = mysqli_real_escape_string($conn, $_POST['scheduled_time']);
        $meeting_password = mysqli_real_escape_string($conn, $_POST['meeting_password']);
        $max_participants = intval($_POST['max_participants']);
        
        // Generate unique meeting ID
        $meeting_id = 'MEET-' . strtoupper(substr($course_code, 0, 3)) . '-' . 
                     date('Ymd') . '-' . bin2hex(random_bytes(3));
        
        $insertQuery = "INSERT INTO meetings 
                       (meeting_id, course_code, course_name, program, intake, year, 
                        staff_id, staff_name, meeting_title, meeting_description, 
                        scheduled_time, meeting_password, max_participants) 
                       VALUES ('$meeting_id', '$course_code', '$course_name', '$program', 
                               '$intake', '$year', '$staff_email', '$staff_name', 
                               '$meeting_title', '$meeting_description', 
                               '$scheduled_time', '$meeting_password', $max_participants)";
        
        if (mysqli_query($conn, $insertQuery)) {
            $message = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                        <i class='fas fa-video me-2'></i>Meeting created successfully! 
                        Meeting ID: <strong>$meeting_id</strong>
                        <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 creating meeting: " . mysqli_error($conn) . "
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
        }
    }
    
    // Handle meeting actions
    if (isset($_POST['start_meeting'])) {
        $meeting_id = mysqli_real_escape_string($conn, $_POST['meeting_id']);
        $_SESSION['current_meeting'] = $meeting_id;
        header("Location: meeting_room.php?meeting_id=$meeting_id");
        exit();
    }
    
    if (isset($_POST['delete_meeting'])) {
        $meeting_id = mysqli_real_escape_string($conn, $_POST['meeting_id']);
        
        $deleteQuery = "DELETE FROM meetings WHERE meeting_id = '$meeting_id' AND staff_id = '$staff_email'";
        
        if (mysqli_query($conn, $deleteQuery)) {
            $message = "<div class='alert alert-success alert-dismissible fade show' role='alert'>
                        <i class='fas fa-trash me-2'></i>Meeting 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 meeting: " . mysqli_error($conn) . "
                        <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
                      </div>";
        }
    }
    
    if (isset($_POST['toggle_meeting'])) {
        $meeting_id = mysqli_real_escape_string($conn, $_POST['meeting_id']);
        $is_active = intval($_POST['is_active']);
        $new_status = $is_active ? 0 : 1;
        
        $toggleQuery = "UPDATE meetings SET is_active = $new_status 
                       WHERE meeting_id = '$meeting_id' AND staff_id = '$staff_email'";
        
        if (mysqli_query($conn, $toggleQuery)) {
            $status_text = $new_status ? 'activated' : 'deactivated';
            $message = "<div class='alert alert-info alert-dismissible fade show' role='alert'>
                        <i class='fas fa-toggle-on me-2'></i>Meeting $status_text successfully!
                        <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'] ?? '';
$filter_year = $_GET['year'] ?? '';

// Get available years
$years_query = "SELECT DISTINCT year FROM balances ORDER BY year DESC";
$years_result = mysqli_query($conn, $years_query);

// Get available courses for dropdown
$available_courses_query = "SELECT DISTINCT course_code, course_name FROM timetable ORDER BY course_name";
$available_courses_result = mysqli_query($conn, $available_courses_query);

// Get meetings for current staff
$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%'";
}
if (!empty($filter_year)) {
    $filter_conditions[] = "year = '$filter_year'";
}

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

$meetings_query = "SELECT * FROM meetings $filter_sql ORDER BY scheduled_time DESC, created_at DESC";
$meetings_result = mysqli_query($conn, $meetings_query);

// Get unique programs and intakes for filters
$programs_query = "SELECT DISTINCT program FROM meetings WHERE staff_id = '$staff_email' ORDER BY program";
$programs_result = mysqli_query($conn, $programs_query);

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Meetings - Teaching Platform</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;
            --success: #28a745;
            --info: #17a2b8;
            --warning: #ffc107;
            --danger: #dc3545;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            margin: 0;
            padding: 0;
        }
        
        .content {
            margin-left: 210px;
            padding: 20px;
            min-height: 100vh;
        }
        
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        
        .header-section {
            background: var(--primary);
            color: white;
            padding: 25px;
            border-radius: 15px;
            margin-bottom: 25px;
            position: relative;
            overflow: hidden;
        }
        
        .header-section::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="rgba(255,255,255,0.1)" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,112C672,96,768,96,864,112C960,128,1056,160,1152,160C1248,160,1344,128,1392,112L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>');
            background-size: cover;
            opacity: 0.3;
        }
        
        .btn-primary {
            background: var(--primary) !important;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(32, 35, 66, 0.3);
        }
        
        .btn-success {
            background: var(--success) !important;
            border: none;
        }
        
        .btn-info {
            background: var(--info) !important;
            border: none;
        }
        
        .btn-warning {
            background: var(--warning) !important;
            border: none;
            color: #000 !important;
        }
        
        .btn-danger {
            background: var(--danger) !important;
            border: none;
        }
        
        .meeting-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 5px solid;
            box-shadow: 0 3px 15px rgba(0,0,0,0.08);
            transition: all 0.3s;
        }
        
        .meeting-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .meeting-card.active {
            border-left-color: var(--success);
        }
        
        .meeting-card.inactive {
            border-left-color: #6c757d;
            opacity: 0.8;
        }
        
        .meeting-card.upcoming {
            border-left-color: var(--info);
        }
        
        .meeting-card.ongoing {
            border-left-color: var(--warning);
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.4); }
            70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); }
            100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
        }
        
        .meeting-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-right: 10px;
        }
        
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        
        .status-inactive {
            background: #f8f9fa;
            color: #6c757d;
        }
        
        .status-upcoming {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .status-ongoing {
            background: #fff3cd;
            color: #856404;
        }
        
        .meeting-id {
            font-family: 'Courier New', monospace;
            background: #f8f9fa;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 14px;
            color: var(--primary);
        }
        
        .meeting-time {
            font-size: 14px;
            color: #6c757d;
            margin-top: 5px;
        }
        
        .meeting-time i {
            margin-right: 5px;
        }
        
        .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;
        }
        
        .badge-course {
            background: #9b59b6;
            color: white;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }
        
        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.3;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(32, 35, 66, 0.25);
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.08);
        }
        
        .stats-number {
            font-size: 32px;
            font-weight: bold;
            color: var(--primary);
            margin: 10px 0;
        }
        
        .filter-section {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.08);
        }
        
        .form-section {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 3px 15px rgba(0,0,0,0.08);
        }
        
        @media (max-width: 768px) {
            .content {
                margin-left: 0;
                padding: 15px;
            }
            
            .header-section {
                padding: 20px 15px;
            }
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
    
    <div class="content">
        <div class="container-fluid">
            <!-- Header Section -->
            <div class="header-section">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h1 class="mb-2"><i class="fas fa-video me-2"></i>Online Teaching Meetings</h1>
                        <p class="mb-0">Create and manage virtual classrooms for your courses. Welcome, <?php echo htmlspecialchars($staff_name); ?></p>
                    </div>
                    <div class="col-md-4 text-end">
                        <a href="#createMeetingForm" class="btn btn-primary btn-lg">
                            <i class="fas fa-plus-circle me-2"></i>Create New Meeting
                        </a>
                    </div>
                </div>
            </div>
            
            <?php if (isset($message)) echo $message; ?>

            <!-- Statistics Section -->
            <div class="row mb-4">
                <?php
                // Get meeting statistics
                $meetings_count_query = "SELECT COUNT(*) as total FROM meetings WHERE staff_id = '$staff_email'";
                $meetings_count_result = mysqli_query($conn, $meetings_count_query);
                $total_meetings = mysqli_fetch_assoc($meetings_count_result)['total'] ?? 0;
                
                $active_meetings_query = "SELECT COUNT(*) as active FROM meetings WHERE staff_id = '$staff_email' AND is_active = 1";
                $active_meetings_result = mysqli_query($conn, $active_meetings_query);
                $active_meetings = mysqli_fetch_assoc($active_meetings_result)['active'] ?? 0;
                
                $current_date = date('Y-m-d');
                $upcoming_meetings_query = "SELECT COUNT(*) as upcoming FROM meetings WHERE staff_id = '$staff_email' AND DATE(scheduled_time) > '$current_date'";
                $upcoming_meetings_result = mysqli_query($conn, $upcoming_meetings_query);
                $upcoming_meetings = mysqli_fetch_assoc($upcoming_meetings_result)['upcoming'] ?? 0;
                
                $today_meetings_query = "SELECT COUNT(*) as today FROM meetings WHERE staff_id = '$staff_email' AND DATE(scheduled_time) = '$current_date'";
                $today_meetings_result = mysqli_query($conn, $today_meetings_query);
                $today_meetings = mysqli_fetch_assoc($today_meetings_result)['today'] ?? 0;
                ?>
                
                <div class="col-md-3">
                    <div class="stats-card">
                        <i class="fas fa-video fa-2x text-primary mb-2"></i>
                        <h5>Total Meetings</h5>
                        <div class="stats-number"><?php echo $total_meetings; ?></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <i class="fas fa-play-circle fa-2x text-success mb-2"></i>
                        <h5>Active Meetings</h5>
                        <div class="stats-number"><?php echo $active_meetings; ?></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <i class="fas fa-calendar-alt fa-2x text-info mb-2"></i>
                        <h5>Upcoming</h5>
                        <div class="stats-number"><?php echo $upcoming_meetings; ?></div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <i class="fas fa-calendar-day fa-2x text-warning mb-2"></i>
                        <h5>Today</h5>
                        <div class="stats-number"><?php echo $today_meetings; ?></div>
                    </div>
                </div>
            </div>

            <!-- Create Meeting Form -->
            <div class="form-section" id="createMeetingForm">
                <h4 class="mb-4"><i class="fas fa-plus-circle me-2"></i>Create New Meeting</h4>
                <form method="POST" action="">
                    <div class="row g-3">
                        <!-- Course Selection -->
                        <div class="col-md-6">
                            <label class="form-label">Course</label>
                            <select name="course_code" class="form-select" required>
                                <option value="">Select Course</option>
                                <?php
                                if ($available_courses_result && mysqli_num_rows($available_courses_result) > 0):
                                    mysqli_data_seek($available_courses_result, 0);
                                    while ($course = mysqli_fetch_assoc($available_courses_result)): 
                                        $course_code = htmlspecialchars($course['course_code']);
                                        $course_name = htmlspecialchars($course['course_name']);
                                ?>
                                    <option value="<?php echo $course_code; ?>" data-course-name="<?php echo $course_name; ?>">
                                        <?php echo $course_code . ' - ' . $course_name; ?>
                                    </option>
                                <?php 
                                    endwhile;
                                endif; 
                                ?>
                            </select>
                            <input type="hidden" name="course_name" id="courseNameField">
                        </div>
                        
                        <!-- Program -->
                        <div class="col-md-6">
                            <label class="form-label">Program</label>
                            <select name="program" class="form-select" required>
                                <option value="">Select Program</option>
                                <?php
                                $program_query = "SELECT DISTINCT program FROM students WHERE program IS NOT NULL AND program != '' ORDER BY program ASC";
                                $program_result = mysqli_query($conn, $program_query);
                                
                                if ($program_result && mysqli_num_rows($program_result) > 0) {
                                    while ($program = mysqli_fetch_assoc($program_result)) {
                                        echo '<option value="' . htmlspecialchars($program['program']) . '">' . htmlspecialchars($program['program']) . '</option>';
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        
                        <!-- Intake -->
                        <div class="col-md-6">
                            <label class="form-label">Intake</label>
                            <select name="intake" class="form-select" required>
                                <option value="">Select Intake</option>
                                <?php
                                $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>';
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        
                        <!-- Year -->
                        <div class="col-md-6">
                            <label class="form-label">Academic Year</label>
                            <select name="year" class="form-select" required>
                                <option value="">Select Year</option>
                                <?php
                                if ($years_result && mysqli_num_rows($years_result) > 0):
                                    mysqli_data_seek($years_result, 0);
                                    while ($year = mysqli_fetch_assoc($years_result)): 
                                ?>
                                    <option value="<?php echo htmlspecialchars($year['year']); ?>">
                                        <?php echo htmlspecialchars($year['year']); ?>
                                    </option>
                                <?php 
                                    endwhile;
                                endif; 
                                ?>
                            </select>
                        </div>
                        
                        <!-- Meeting Details -->
                        <div class="col-12">
                            <label class="form-label">Meeting Title</label>
                            <input type="text" name="meeting_title" class="form-control" placeholder="Enter meeting title" required>
                        </div>
                        
                        <div class="col-12">
                            <label class="form-label">Meeting Description</label>
                            <textarea name="meeting_description" class="form-control" rows="3" placeholder="Enter meeting description"></textarea>
                        </div>
                        
                        <!-- Schedule Time -->
                        <div class="col-md-6">
                            <label class="form-label">Scheduled Date & Time</label>
                            <?php
                            $default_time = date('Y-m-d\TH:i', strtotime('+5 minutes'));
                            ?>
                            <input type="datetime-local" name="scheduled_time" class="form-control" required value="<?php echo $default_time; ?>">
                        </div>
                        
                        <!-- Meeting Password (Optional) -->
                        <div class="col-md-6">
                            <label class="form-label">Meeting Password (Optional)</label>
                            <input type="text" name="meeting_password" class="form-control" placeholder="Leave empty for no password">
                        </div>
                        
                        <!-- Max Participants -->
                        <div class="col-md-6">
                            <label class="form-label">Maximum Participants</label>
                            <input type="number" name="max_participants" class="form-control" value="50" min="1" max="100">
                        </div>
                    </div>
                    
                    <div class="mt-4">
                        <button type="submit" name="create_meeting" class="btn btn-primary btn-lg">
                            <i class="fas fa-save me-2"></i>Create Meeting
                        </button>
                    </div>
                </form>
            </div>

            <!-- Filter Section -->
            <div class="filter-section">
                <h5 class="mb-3"><i class="fas fa-filter me-2"></i>Filter Meetings</h5>
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Program</label>
                        <select name="program" class="form-select">
                            <option value="">All Programs</option>
                            <?php 
                            if ($programs_result && mysqli_num_rows($programs_result) > 0):
                                while ($program = mysqli_fetch_assoc($programs_result)): 
                            ?>
                                <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-3">
                        <label class="form-label">Intake</label>
                        <select name="intake" class="form-select">
                            <option value="">All Intakes</option>
                            <?php 
                            if ($intakes_result && mysqli_num_rows($intakes_result) > 0):
                                while ($intake = mysqli_fetch_assoc($intakes_result)): 
                            ?>
                                <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-3">
                        <label class="form-label">Course</label>
                        <select name="course" class="form-select">
                            <option value="">All Courses</option>
                            <?php 
                            if ($available_courses_result && mysqli_num_rows($available_courses_result) > 0):
                                mysqli_data_seek($available_courses_result, 0);
                                while ($course = mysqli_fetch_assoc($available_courses_result)): 
                            ?>
                                <option value="<?php echo htmlspecialchars($course['course_code']); ?>" 
                                    <?php echo ($filter_course == $course['course_code']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($course['course_code']); ?>
                                </option>
                            <?php 
                                endwhile;
                            endif; 
                            ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Year</label>
                        <select name="year" class="form-select">
                            <option value="">All Years</option>
                            <?php 
                            if ($years_result && mysqli_num_rows($years_result) > 0):
                                mysqli_data_seek($years_result, 0);
                                while ($year = mysqli_fetch_assoc($years_result)): 
                            ?>
                                <option value="<?php echo htmlspecialchars($year['year']); ?>" 
                                    <?php echo ($filter_year == $year['year']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($year['year']); ?>
                                </option>
                            <?php 
                                endwhile;
                            endif; 
                            ?>
                        </select>
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search me-2"></i>Apply Filters
                        </button>
                        <a href="meetings.php" class="btn btn-secondary">
                            <i class="fas fa-times me-2"></i>Clear Filters
                        </a>
                    </div>
                </form>
            </div>

            <!-- Meetings List -->
            <div class="row">
                <div class="col-12">
                    <h4 class="mb-3"><i class="fas fa-list me-2"></i>My Meetings</h4>
                    
                    <?php if ($meetings_result && mysqli_num_rows($meetings_result) > 0): ?>
                        <div class="row">
                            <?php 
                            $current_time = date('Y-m-d H:i:s');
                            while ($meeting = mysqli_fetch_assoc($meetings_result)): 
                                $meeting_time = $meeting['scheduled_time'];
                                $current_time_stamp = time();
                                $meeting_time_stamp = strtotime($meeting_time);
                                $time_diff = $meeting_time_stamp - $current_time_stamp;
                                
                                // Determine meeting status
                                $status_class = '';
                                $status_text = '';
                                
                                if (!$meeting['is_active']) {
                                    $status_class = 'inactive';
                                    $status_text = '<span class="meeting-status status-inactive"><i class="fas fa-pause-circle"></i> Inactive</span>';
                                } elseif ($meeting_time_stamp <= $current_time_stamp && $time_diff > -3600) { // Started within last hour
                                    $status_class = 'ongoing';
                                    $status_text = '<span class="meeting-status status-ongoing"><i class="fas fa-play-circle"></i> Live Now</span>';
                                } elseif ($meeting_time_stamp > $current_time_stamp) {
                                    $status_class = 'upcoming';
                                    $status_text = '<span class="meeting-status status-upcoming"><i class="fas fa-clock"></i> Upcoming</span>';
                                } else {
                                    $status_class = 'active';
                                    $status_text = '<span class="meeting-status status-active"><i class="fas fa-check-circle"></i> Active</span>';
                                }
                            ?>
                            
                            <div class="col-md-6">
                                <div class="meeting-card <?php echo $status_class; ?>">
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                        <div>
                                            <h5 class="mb-1"><?php echo htmlspecialchars($meeting['meeting_title']); ?></h5>
                                            <?php echo $status_text; ?>
                                        </div>
                                        <div class="text-end">
                                            <span class="meeting-id"><?php echo $meeting['meeting_id']; ?></span>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <span class="badge badge-program mb-1"><?php echo htmlspecialchars($meeting['program']); ?></span>
                                        <span class="badge badge-intake mb-1"><?php echo htmlspecialchars($meeting['intake']); ?></span>
                                        <span class="badge badge-course mb-1"><?php echo htmlspecialchars($meeting['course_code']); ?></span>
                                        <span class="badge bg-secondary mb-1"><?php echo htmlspecialchars($meeting['year']); ?></span>
                                    </div>
                                    
                                    <p class="mb-3"><?php echo htmlspecialchars($meeting['meeting_description'] ?: 'No description provided'); ?></p>
                                    
                                    <div class="meeting-time">
                                        <i class="fas fa-calendar"></i>
                                        <?php echo date('F j, Y', strtotime($meeting['scheduled_time'])); ?> 
                                        at <?php echo date('h:i A', strtotime($meeting['scheduled_time'])); ?>
                                    </div>
                                    
                                    <?php if ($meeting['meeting_password']): ?>
                                        <div class="meeting-time">
                                            <i class="fas fa-key"></i> Password: <?php echo htmlspecialchars($meeting['meeting_password']); ?>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="d-flex justify-content-between align-items-center mt-3">
                                        <div>
                                            <small class="text-muted">
                                                <i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($meeting['staff_name']); ?>
                                            </small>
                                        </div>
                                        <div>
                                            <?php if ($meeting['is_active'] && $meeting_time_stamp <= $current_time_stamp + 3600): ?>
                                                <form method="POST" class="d-inline">
                                                    <input type="hidden" name="meeting_id" value="<?php echo $meeting['meeting_id']; ?>">
                                                    <button type="submit" name="start_meeting" class="btn btn-success btn-sm">
                                                        <i class="fas fa-play me-1"></i> Join Meeting
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                            
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="meeting_id" value="<?php echo $meeting['meeting_id']; ?>">
                                                <input type="hidden" name="is_active" value="<?php echo $meeting['is_active']; ?>">
                                                <button type="submit" name="toggle_meeting" class="btn btn-sm <?php echo $meeting['is_active'] ? 'btn-warning' : 'btn-info'; ?>">
                                                    <i class="fas fa-toggle-<?php echo $meeting['is_active'] ? 'on' : 'off'; ?> me-1"></i>
                                                    <?php echo $meeting['is_active'] ? 'Deactivate' : 'Activate'; ?>
                                                </button>
                                            </form>
                                            
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this meeting?');">
                                                <input type="hidden" name="meeting_id" value="<?php echo $meeting['meeting_id']; ?>">
                                                <button type="submit" name="delete_meeting" class="btn btn-danger btn-sm">
                                                    <i class="fas fa-trash me-1"></i> Delete
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <?php endwhile; ?>
                        </div>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-video-slash"></i>
                            <h4>No meetings found</h4>
                            <p>You haven't created any meetings yet. Create your first meeting using the form above.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Auto-fill course name when course is selected
        document.querySelector('select[name="course_code"]').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const courseName = selectedOption.getAttribute('data-course-name');
            document.getElementById('courseNameField').value = courseName || '';
            
            // Auto-generate meeting title if empty
            const meetingTitle = document.querySelector('input[name="meeting_title"]');
            if (meetingTitle && !meetingTitle.value && courseName) {
                meetingTitle.value = courseName + ' - Online Class';
            }
        });
    </script>
</body>
</html>