<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
include "../include/config.php";
$userlogin = $_SESSION['studentid'];
$intake = $_SESSION['intake'];
$program = $_SESSION['program'];

// Function to calculate current year and semester based on intake
function calculateCurrentYearSemester($intake) {
    $intakeDate = DateTime::createFromFormat('F Y', $intake);
    if (!$intakeDate) {
        return ['year' => 1, 'semester' => 1];
    }
    
    $currentDate = new DateTime();
    $interval = $currentDate->diff($intakeDate);
    $monthsDifference = ($interval->y * 12) + $interval->m;
    $currentSemester = floor($monthsDifference / 6) + 1;
    $currentYear = ceil($currentSemester / 2);
    $semesterInYear = ($currentSemester % 2 == 0) ? 2 : 1;
    
    return [
        'year' => max(1, $currentYear),
        'semester' => $semesterInYear,
        'total_semesters' => $currentSemester
    ];
}

if (isset($_SESSION['studentid'])) {
    $currentInfo = calculateCurrentYearSemester($intake);
    $currentYear = $currentInfo['year'];
    $currentSemester = $currentInfo['semester'];
?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
      <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
   <link rel="icon" href="favicon.png" type="image/png">
   <!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <meta name="theme-color" content="var(--primary)">
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="res/bootstrap@5.2.0.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rowdies:wght@300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:ital,wght@0,100..700;1,100..700&display=swap" rel="stylesheet">
    
    <!-- Google Fonts -->
    
    <style>
        :root {
            --primary-color: #049836;
            --secondary-color: #2c3e50;
            --accent-color: #ff8a65;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
        }
        
        body {
            font-family: "Josefin Sans", sans-serif;
            background-color: #f5f7fa;
            color: #333;
            padding: 0;
            margin: 0;
            font-size: 14px;
        }
        
        .navbar-custom {
            background-color: var(--secondary-color);
        }
        
        .content {
            margin-left: 210px;
            padding: 10px;
        }
        
        @media (max-width: 992px) {
            .content {
                margin-left: 0;
            }
        }
        
        .card {
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: none;
            margin-bottom: 20px;
        }
        
        .card-header {
            background: var(--primary-color);
            color: white;
            border-radius: 12px 12px 0 0 !important;
            padding: 15px 20px;
        }
        
        .table-container {
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 30px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .timetable-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 0;
        }
        
        .timetable-table th {
            background-color: #e9ecef;
            color: var(--secondary-color);
            font-weight: 600;
            padding: 12px 15px;
            text-align: center;
            border-bottom: 2px solid #dee2e6;
        }
        
        .timetable-table td {
            padding: 15px 10px;
            border: 1px solid #eaeaea;
            vertical-align: top;
            text-align: center;
        }
        
        .time-slot {
            background: #f8f9fa;
            padding: 8px 5px;
            border-bottom: 1px solid #dee2e6;
            font-weight: 600;
            font-size: 0.85rem;
        }
        
        .day-header {
            background: var(--secondary-color);
            color: white;
            font-weight: 600;
            text-align: center;
        }
        
        .class-card {
            background: white;
            border-radius: 6px;
            padding: 12px;
            margin: 5px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            border-left: 4px solid var(--primary-color);
            text-align: left;
        }
        
        .class-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            transition: all 0.3s ease;
        }
        
        .course-code {
            font-weight: bold;
            color: var(--secondary-color);
            font-size: 0.9rem;
            margin-bottom: 5px;
        }
        
        .course-name {
            color: #666;
            font-size: 0.8rem;
            margin: 3px 0;
        }
        
        .class-time {
            color: var(--primary-color);
            font-weight: 600;
            font-size: 0.8rem;
            margin: 5px 0;
        }
        
        .current-class {
            background: linear-gradient(135deg, #e3f2fd, #bbdefb);
            border-left-color: #2196f3;
        }
        
        .no-class {
            color: #999;
            font-style: italic;
            padding: 20px;
        }
        
        .timetable-header {
            background: gray;
            color: white;
            padding: 15px;
            font-size: 1.1rem;
            font-weight: 600;
        }
        
        .stats-box {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid var(--primary-color);
        }
        
        .stats-box h6 {
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 5px;
        }
        
        .stats-box h3 {
            margin: 0;
            font-weight: 700;
        }
        
        /* Join Class Button */
        .join-class-btn {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-top: 8px;
            transition: all 0.3s ease;
            width: 100%;
            text-align: center;
        }
        
        .join-class-btn:hover {
            background: linear-gradient(135deg, #45a049, #3d8b40);
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
            box-shadow: 0 3px 6px rgba(0,0,0,0.15);
        }
        
        .join-class-btn i {
            margin-right: 5px;
            font-size: 0.9rem;
        }
        
        .join-class-btn.active {
            background: linear-gradient(135deg, #2196F3, #1976D2);
        }
        
        .join-class-btn.active:hover {
            background: linear-gradient(135deg, #1976D2, #1565C0);
        }
        
        /* Meeting Modal */
        .meeting-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 2000;
            display: none;
        }
        
        .meeting-modal-content {
            background: white;
            border-radius: 12px;
            padding: 25px;
            max-width: 500px;
            width: 90%;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        }
        
        .meeting-link {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 6px;
            padding: 10px 15px;
            margin: 15px 0;
            word-break: break-all;
            font-size: 0.9rem;
        }
        
        @media (max-width: 768px) {
            .content {
                padding: 15px;
            }
            
            .timetable-table {
                font-size: 0.8rem;
            }
            
            .timetable-table th, 
            .timetable-table td {
                padding: 8px 5px;
            }
            
            .class-card {
                padding: 8px;
            }
            
            .course-code {
                font-size: 0.8rem;
            }
            
            .course-name {
                font-size: 0.7rem;
            }
            
            .join-class-btn {
                padding: 5px 8px;
                font-size: 0.75rem;
            }
        }

        /* Color coding for different times of day */
        .morning-slot { background: #e8f5e8; }
        .afternoon-slot { background: #fff3cd; }
        .evening-slot { background: #e2e3e5; }
        
        /* Current time indicator */
        .current-time-indicator {
            position: absolute;
            left: 0;
            right: 0;
            height: 2px;
            background: #f44336;
            z-index: 10;
        }
        
        .current-time-indicator::before {
            content: '';
            position: absolute;
            left: -5px;
            top: -4px;
            width: 10px;
            height: 10px;
            background: #f44336;
            border-radius: 50%;
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>

    <div class="content">
 
            <div class="card">
                <div class="card-header" style="background:white; color:black;">
                    <h5 class="mb-0"><i class="fas fa-calendar-alt me-2"></i>Weekly Class Timetable</h5>
                    <p class="mb-0 mt-1 small opacity-75">Your scheduled classes for the current semester</p>
                </div>
                
                <div class="card-body">
                    <?php
                    // Get student's registered courses for current semester
                    $registeredQuery = "SELECT course_name FROM registered_course 
                                      WHERE student_id = '$userlogin' 
                                      ";
                    $registeredResult = mysqli_query($conn, $registeredQuery);
                    
                    $registeredCourses = [];
                    while ($row = mysqli_fetch_assoc($registeredResult)) {
                        $registeredCourses[] = $row['course_name'];
                    }
                    
                    if (!empty($registeredCourses)) {
                        // Get timetable for registered courses
                        $courseList = "'" . implode("','", $registeredCourses) . "'";
                        $timetableQuery = "SELECT * FROM timetable 
                                          WHERE course_name IN ($courseList)
                                          AND program = '$program'
                                          AND intake = '$intake'
                                          ORDER BY 
                                            FIELD(day_of_week, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'),
                                            start_time";
                        
                        $timetableResult = mysqli_query($conn, $timetableQuery);
                        
                        if (mysqli_num_rows($timetableResult) > 0) {
                            // Group classes by day and time
                            $schedule = [
                                'Monday' => [], 'Tuesday' => [], 'Wednesday' => [], 
                                'Thursday' => [], 'Friday' => [], 'Saturday' => [], 'Sunday' => []
                            ];
                            
                            $allTimes = [];
                            
                            while ($class = mysqli_fetch_assoc($timetableResult)) {
                                $day = $class['day_of_week'];
                                $startTime = $class['start_time'];
                                $endTime = $class['end_time'];
                                
                                $schedule[$day][] = $class;
                                
                                // Collect all unique time slots
                                $timeSlot = $startTime . '-' . $endTime;
                                if (!in_array($timeSlot, $allTimes)) {
                                    $allTimes[] = $timeSlot;
                                }
                            }
                            
                            // Sort time slots
                            usort($allTimes, function($a, $b) {
                                $aStart = explode('-', $a)[0];
                                $bStart = explode('-', $b)[0];
                                return strcmp($aStart, $bStart);
                            });
                            
                            // Get current day for highlighting
                            $currentDay = date('l');
                            ?>
                            
                            <div class="table-container" style="overflow:scroll">
                                <table class="timetable-table">
                                    <thead>
                                        <tr>
                                            <th width="12%">Time</th>
                                            <th width="12.5%">Monday</th>
                                            <th width="12.5%">Tuesday</th>
                                            <th width="12.5%">Wednesday</th>
                                            <th width="12.5%">Thursday</th>
                                            <th width="12.5%">Friday</th>
                                          
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($allTimes as $timeSlot): 
                                            list($startTime, $endTime) = explode('-', $timeSlot);
                                            $timeDisplay = date('h:i A', strtotime($startTime)) . ' - ' . date('h:i A', strtotime($endTime));
                                            
                                            // Determine time of day for color coding
                                            $hour = date('H', strtotime($startTime));
                                            $timeClass = '';
                                            if ($hour < 12) $timeClass = 'morning-slot';
                                            elseif ($hour < 17) $timeClass = 'afternoon-slot';
                                            else $timeClass = 'evening-slot';
                                            
                                            // Check if this is the current time slot
                                            $currentTime = date('H:i:s');
                                            $isCurrentSlot = ($currentTime >= $startTime && $currentTime <= $endTime);
                                        ?>
                                        <tr>
                                            <td class="time-slot <?php echo $timeClass; ?>">
                                                <?php echo $timeDisplay; ?>
                                                <?php if ($isCurrentSlot): ?>
                                                <div class="current-time-indicator"></div>
                                                <?php endif; ?>
                                            </td>
                                            <?php foreach (['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] as $day): 
                                                $dayClasses = array_filter($schedule[$day], function($class) use ($startTime, $endTime) {
                                                    return $class['start_time'] == $startTime && $class['end_time'] == $endTime;
                                                });
                                            ?>
                                            <td class="<?php echo ($day == $currentDay) ? 'current-day' : ''; ?>">
                                                <?php if (!empty($dayClasses)): 
                                                    foreach ($dayClasses as $class): 
                                                        // Create meeting URL - same as staff side for consistency
                                                        $courseName = $class['course_name'] ?? '';
                                                        $program = $class['program'] ?? '';
                                                        $intake = $class['intake'] ?? '';
                                                        
                                                        // Create a clean meeting room name
                                                        $courseCode = str_replace(' ', '', substr($courseName, 0, 10));
                                                        $meetingRoom = $courseCode . '_' . 
                                                                      str_replace(' ', '', $program) . '_' . 
                                                                      str_replace(' ', '', $intake) . '_' . 
                                                                      date('Ymd');
                                                        $meetingRoom = preg_replace('/[^A-Za-z0-9_]/', '', $meetingRoom);
                                                        $meetingUrl = "https://meet.jit.si/" . $meetingRoom;
                                                ?>
                                                <div class="class-card <?php echo ($day == $currentDay) ? 'current-class' : ''; ?>">
                                                  
                                                    <div class="course-name"><?php echo htmlspecialchars($courseName); ?></div>
                                                    <div class="class-time">
                                                        <i class="far fa-clock me-1"></i>
                                                        <?php echo date('h:i A', strtotime($class['start_time'])); ?>
                                                    </div>
                                                    <?php if (!empty($class['staff_name'])): ?>
                                                    <div class="staff-name small text-muted">
                                                        <i class="fa fa-graduation-cap"></i>
                                                        <?php echo htmlspecialchars($class['staff_name']); ?>
                                                    </div>
                                                    <?php endif; ?>
                                                    
                                                    <!-- Join Class Button -->
                                                    <a href="<?php echo $meetingUrl; ?>" 
                                                       target="_blank" 
                                                       class="join-class-btn" 
                                                       onclick="trackClassJoin('<?php echo htmlspecialchars($courseName); ?>')">
                                                        <i class="fa fa-video-camera"></i> Join Virtual Class
                                                    </a>
                                                </div>
                                                <?php endforeach; ?>
                                                <?php else: ?>
                                                <div class="no-class">-</div>
                                                <?php endif; ?>
                                            </td>
                                            <?php endforeach; ?>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Meeting Instructions Modal -->
                            <div class="meeting-modal" id="meetingModal">
                                <div class="meeting-modal-content">
                                    <h5><i class="fa fa-video-camera me-2"></i>Joining Virtual Class</h5>
                                    <div hidden class="meeting-link" id="meetingLink"></div>
                                    <div class="d-flex justify-content-between mt-3">
                                        <button class="btn btn-secondary" onclick="closeMeetingModal()">Cancel</button>
                                        <a href="#" class="btn btn-success" id="joinMeetingBtn" target="_blank">
                                            <i class="fa fa-external-link"></i> Join Class Now
                                        </a>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Legend -->
                            <div class="row mt-4">
                                <div class="col-md-6">
                                    <div class="d-flex align-items-center">
                                        <div class="class-card current-class me-3" style="min-width: 200px;">
                                            <small><i class="fas fa-info-circle me-1"></i>Blue border indicates today's classes</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="d-flex justify-content-end">
                                        <div class="d-flex align-items-center me-3">
                                            <div class="morning-slot me-2" style="width: 20px; height: 20px; border-radius: 4px;"></div>
                                            <small>Morning</small>
                                        </div>
                                        <div class="d-flex align-items-center me-3">
                                            <div class="afternoon-slot me-2" style="width: 20px; height: 20px; border-radius: 4px;"></div>
                                            <small>Afternoon</small>
                                        </div>
                                        <div class="d-flex align-items-center">
                                            <div class="evening-slot me-2" style="width: 20px; height: 20px; border-radius: 4px;"></div>
                                            <small>Evening</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Virtual Class Instructions -->
                           
                            
                        <?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 scheduled yet</h5>
                                <p class="text-muted">Your class schedule will be available once the timetable is published.</p>
                            </div>
                        <?php } ?>
                    <?php } else { ?>
                        <div class="text-center py-5">
                            <i class="fas fa-book fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No courses registered for this semester</h5>
                            <p class="text-muted">Please register your courses to view the timetable.</p>
                            
                        </div>
                    <?php } ?>
                </div>
            </div>
        </div>
        <br><br><br>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Configuration for meeting URLs
    const MEETING_URLS = {
        'CSC101': 'https://meet.jit.si/University-CSC101-Class',
        'MTH201': 'https://meet.jit.si/University-MTH201-Lecture',
        'ENG151': 'https://meet.jit.si/University-ENG151-Seminar',
        'PHY103': 'https://meet.jit.si/University-PHY103-Lab',
        'ART110': 'https://meet.jit.si/University-ART110-Studio'
    };

    // Function to generate meeting link based on course code
    function generateMeetingLink(courseCode, courseName) {
        // Use existing link if available in configuration
        if (MEETING_URLS[courseCode]) {
            return MEETING_URLS[courseCode];
        }
        
        // Generate a standard meeting link based on course code
        const sanitizedCourseCode = courseCode.replace(/\s+/g, '-');
        const sanitizedCourseName = courseName.replace(/\s+/g, '-').substring(0, 30);
        return `https://meet.jit.si/${sanitizedCourseName}`;
    }

    // Function to track meeting/class clicks
    function trackClassAction(courseCode, courseName, actionType = 'meeting') {
        console.log(`${actionType === 'meeting' ? 'Starting meeting' : 'Joining class'} for: ${courseName} (${courseCode})`);
        
        // Generate consistent meeting link
        const meetingUrl = generateMeetingLink(courseCode, courseName);
        
        // Show meeting modal
        const modal = document.getElementById('meetingModal');
        const meetingLink = document.getElementById('meetingLink');
        const joinBtn = document.getElementById('joinMeetingBtn');
        
        meetingLink.textContent = meetingUrl;
        joinBtn.href = meetingUrl;
        modal.style.display = 'flex';
        
        // Prevent default to show modal instead of navigating directly
        if (event) {
            event.preventDefault();
        }
        
        // You could embed Jitsi Meet in an iframe here instead of opening new tab
        // For now, we'll just show the modal with the link
        
        return meetingUrl;
    }
    
    // Function to close meeting modal
    function closeMeetingModal() {
        document.getElementById('meetingModal').style.display = 'none';
    }
    
    // Close modal when clicking outside
    document.getElementById('meetingModal')?.addEventListener('click', function(e) {
        if (e.target === this) {
            closeMeetingModal();
        }
    });
    
    // Function to copy meeting link to clipboard
    function copyMeetingLink() {
        const meetingLink = document.getElementById('meetingLink').textContent;
        navigator.clipboard.writeText(meetingLink).then(() => {
            alert('Meeting link copied to clipboard!');
        }).catch(err => {
            console.error('Failed to copy: ', err);
        });
    }
    
    // Highlight current time slot
    function highlightCurrentTime() {
        const currentTime = new Date();
        const currentHour = currentTime.getHours();
        const currentMinute = currentTime.getMinutes();
        const currentTotalMinutes = currentHour * 60 + currentMinute;
        
        document.querySelectorAll('.time-slot').forEach(slot => {
            const timeText = slot.textContent.trim();
            const times = timeText.split(' - ');
            
            if (times.length === 2) {
                const startTime = parseTime(times[0]);
                const endTime = parseTime(times[1]);
                
                if (currentTotalMinutes >= startTime && currentTotalMinutes <= endTime) {
                    slot.style.backgroundColor = '#ffebee';
                    slot.style.borderLeft = '4px solid #f44336';
                } else {
                    // Reset styles if not current time
                    slot.style.backgroundColor = '';
                    slot.style.borderLeft = '';
                }
            }
        });
    }
    
    // Helper function to parse time string
    function parseTime(timeStr) {
        const time = timeStr.trim();
        const isPM = time.includes('PM');
        const cleanTime = time.replace(/[APM]/gi, '').trim();
        const [hour, minute] = cleanTime.split(':').map(num => parseInt(num) || 0);
        
        let totalMinutes = hour * 60 + minute;
        if (isPM && hour !== 12) totalMinutes += 12 * 60;
        if (!isPM && hour === 12) totalMinutes -= 12 * 60;
        
        return totalMinutes;
    }
    
    // Initialize when page loads
    document.addEventListener('DOMContentLoaded', function() {
        highlightCurrentTime();
        
        // Update time highlighting every minute
        setInterval(highlightCurrentTime, 60000);
        
        // Add click handlers to meeting buttons
        document.querySelectorAll('.meeting-btn, .join-class-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                const classCard = this.closest('.class-card');
                if (!classCard) return;
                
                const courseCode = classCard.querySelector('.course-code')?.textContent || 
                                  classCard.querySelector('h3')?.textContent || 
                                  'Unknown';
                const courseName = classCard.querySelector('.course-name')?.textContent || 
                                  classCard.querySelector('h4')?.textContent || 
                                  'Class';
                
                trackClassAction(courseCode, courseName, 
                    this.classList.contains('meeting-btn') ? 'meeting' : 'class');
            });
        });
        
        // Add smooth animations for class cards
        const classCards = document.querySelectorAll('.class-card');
        classCards.forEach(card => {
            card.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px)';
                this.style.transition = 'all 0.3s ease';
            });
            
            card.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
            });
        });
        
        // Highlight current day
        const currentDayCells = document.querySelectorAll('td.current-day');
        currentDayCells.forEach(cell => {
            cell.style.backgroundColor = '#f8f9fa';
        });
    });
    
    // Keyboard shortcuts
    document.addEventListener('keydown', function(e) {
        // Escape key closes modal
        if (e.key === 'Escape') {
            closeMeetingModal();
        }
        
        // Ctrl/Cmd + M opens first available meeting (meeting-btn)
        if ((e.ctrlKey || e.metaKey) && e.key === 'm') {
            const firstMeetingBtn = document.querySelector('.meeting-btn');
            if (firstMeetingBtn) {
                firstMeetingBtn.click();
                e.preventDefault();
            }
        }
        
        // Ctrl/Cmd + J opens first available class (join-class-btn)
        if ((e.ctrlKey || e.metaKey) && e.key === 'j') {
            const firstClassBtn = document.querySelector('.join-class-btn');
            if (firstClassBtn) {
                firstClassBtn.click();
                e.preventDefault();
            }
        }
    });
    
    // Export functions for global access if needed
    window.MeetingUtils = {
        generateMeetingLink,
        trackClassAction,
        closeMeetingModal,
        copyMeetingLink,
        highlightCurrentTime
    };
</script>
</body>
</html>
<?php
} else {
    header("location:../index.php");
    exit();
}