<?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();
}

$staffEmail = $_SESSION['email'];

// Get staff details
$staffQuery = "SELECT * FROM staff WHERE email = '$staffEmail'";
$staffResult = mysqli_query($conn, $staffQuery);

if (!$staffResult) {
    die("Database query failed: " . mysqli_error($conn));
}

$staffData = mysqli_fetch_assoc($staffResult);

$staffName = $staffData['staffname'] ?? 'Staff Member';
$staffEmail = $staffData['email'] ?? '';

// Get current semester and year
$currentYear = date('Y');
$currentSemester = (date('n') <= 6) ? 1 : 2; // Semester 1: Jan-Jun, Semester 2: Jul-Dec

// Check if timetable table exists and has data
$tableCheckQuery = "SHOW TABLES LIKE 'timetable'";
$tableCheckResult = mysqli_query($conn, $tableCheckQuery);
$timetableTableExists = mysqli_num_rows($tableCheckResult) > 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Timetable</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" 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://fonts.googleapis.com/css2?family=Josefin+Sans:wght@400;600&family=Signika+Negative:wght@500&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: var(--primary);
            --secondary-color: #238665;
            --dark-color: #2c3e50;
            --light-color: #f8f9fa;
            --text-color: #333;
            --border-radius: 8px;
            --shadow: 0 4px 12px rgba(0,0,0,0.08);
            --transition: all 0.3s ease;
        }
        
        body {
            background: #fff;
            font-family: "Josefin Sans", sans-serif;
            color: var(--text-color);
            padding-top: 70px;
            transition: margin-left 0.4s;
        }
        
        /* Enhanced Navbar */
        .main-navbar {
            background: var(--primary-color);
            color: white;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 60px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 1000;
        }
        
        .nav-container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 15px;
            height: 100%;
        }
        
        .nav-brand {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: white;
        }
        
        /* Timetable Styles */
        .card {
            border-radius: 12px;
            box-shadow: var(--shadow);
            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;
        }
        
        .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;
        }
        
        .meeting-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;
        }
        
        .meeting-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);
        }
        
        .meeting-btn i {
            margin-right: 5px;
            font-size: 0.9rem;
        }
        
        .meeting-btn.active {
            background: linear-gradient(135deg, #f44336, #d32f2f);
        }
        
        .meeting-btn.active:hover {
            background: linear-gradient(135deg, #d32f2f, #b71c1c);
        }
        
        /* Color coding for different times of day */
        .morning-slot { background: #e8f5e8; }
        .afternoon-slot { background: #fff3cd; }
        .evening-slot { background: #e2e3e5; }
        
        @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;
            }
            
            .meeting-btn {
                padding: 5px 8px;
                font-size: 0.75rem;
            }
        }
        
        /* 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%;
        }
        
        .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-family: monospace;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>

<?php include "../include/nav.php";?>

    <!-- Main Content Area -->
    <div id="main-content" class="content">
      
        <!-- Timetable Card -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fa fa-calendar me-2"></i>Weekly Teaching Schedule</h5>
                <p class="mb-0 mt-1 small opacity-75">Your teaching schedule for the current semester</p>
            </div>
            
            <div class="card-body">
                <?php
                if (!$timetableTableExists) {
                    echo '<div class="text-center py-5">
                        <i class="fa fa-database fa-3x text-muted mb-3"></i>
                        <h5 class="text-muted">Timetable System Not Available</h5>
                        <p class="text-muted">The timetable database table has not been set up yet.</p>
                    </div>';
                } else {
                    // Get staff's timetable - search by staff_id (email) instead of staff_name
                    $timetableQuery = "SELECT * FROM timetable 
                                      WHERE staff_id = '$staffEmail'
                                      ORDER BY 
                                        FIELD(day_of_week, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'),
                                        start_time";
                    
                    $timetableResult = mysqli_query($conn, $timetableQuery);
                    
                    // Debug: Check if query returned any results
                    $debugQuery = "SELECT COUNT(*) as total FROM timetable WHERE staff_id = '$staffEmail'";
                    $debugResult = mysqli_query($conn, $debugQuery);
                    $debugData = mysqli_fetch_assoc($debugResult);
                    $totalClasses = $debugData['total'] ?? 0;
                    
                    if ($timetableResult && 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-x: auto;">
                            <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
                                                    $courseCode = $class['course_code'] ?? '';
                                                    $courseName = $class['course_name'] ?? '';
                                                    $program = $class['program'] ?? '';
                                                    $intake = $class['intake'] ?? '';
                                                    
                                                    // Create a clean meeting room name
                                                    $meetingRoom = str_replace(' ', '', $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-code"><?php echo htmlspecialchars($courseCode); ?></div>
                                                <div class="course-name"><?php echo htmlspecialchars($courseName); ?></div>
                                                <div class="class-time">
                                                    <i class="fa fa-clock-o me-1"></i>
                                                    <?php echo date('h:i A', strtotime($class['start_time'])); ?> - <?php echo date('h:i A', strtotime($class['end_time'])); ?>
                                                </div>
                                                <div class="small text-muted">
                                                    <i class="fa fa-users me-1"></i>
                                                    <?php echo htmlspecialchars($program); ?> - <?php echo htmlspecialchars($intake); ?>
                                                </div>
                                                <?php if (!empty($class['venue'])): ?>
                                                <div class="small text-muted">
                                                    <i class="fa fa-map-marker me-1"></i>
                                                    <?php echo htmlspecialchars($class['venue']); ?>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <!-- Start Meeting Button -->
                                                <a href="<?php echo $meetingUrl; ?>" 
                                                   target="_blank" 
                                                   class="meeting-btn" 
                                                   onclick="trackMeetingClick('<?php echo htmlspecialchars($courseCode); ?>', '<?php echo htmlspecialchars($courseName); ?>')">
                                                    <i class="fa fa-video-camera"></i> Start Meeting
                                                </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>Starting 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 Meeting
                                    </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="fa 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>
                        
                    
                        
                    <?php } else { ?>
                        <div class="text-center py-5">
                            <i class="fa fa-calendar-times fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No teaching schedule assigned yet</h5>
                            <p class="text-muted mb-3">No classes found for your account (<?php echo htmlspecialchars($staffEmail); ?>).</p>
                            <p class="text-muted small">Total classes found in database: <?php echo $totalClasses; ?></p>
                            <p class="text-muted">Your teaching timetable will be available once scheduled by the administration.</p>
                        </div>
                    <?php } 
                } ?>
            </div>
        </div>
        <br><br><br>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.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>