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

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

$student_id = $_SESSION['studentid'];
$student_name = $_SESSION['studentname'] ?? 'Student';
$intake = $_SESSION['intake'] ?? '';
$program = $_SESSION['program'] ?? '';
$meeting_id = $_GET['meeting_id'] ?? '';

// Get meeting details
$meeting = null;
if ($meeting_id) {
    $meetingQuery = "SELECT * FROM meetings 
                    WHERE meeting_id = '$meeting_id' 
                    AND program = '$program' 
                    AND intake = '$intake' 
                    AND is_active = 1";
    $meetingResult = mysqli_query($conn, $meetingQuery);
    if (mysqli_num_rows($meetingResult) > 0) {
        $meeting = mysqli_fetch_assoc($meetingResult);
    }
}

if (!$meeting) {
    die("Meeting not found or access denied.");
}

// Generate clean room name from meeting ID
$clean_id = str_replace(['MEET-', '-'], ['', ''], $meeting['meeting_id']);
$room_name = $clean_id;

// Create the full Jitsi meeting URL with student name
$jitsi_url = "https://meet.jit.si/" . $room_name;
$display_name = urlencode($student_name . " (" . $student_id . ")");
$jitsi_url .= "#userInfo.displayName=" . $display_name;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Class Room - <?php echo htmlspecialchars($meeting['meeting_title']); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
            height: 100vh;
            overflow: hidden;
            color: white;
        }
        
        .redirect-container {
            max-width: 800px;
            margin: 0 auto;
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 20px;
            text-align: center;
        }
        
        .loading-spinner {
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-top: 4px solid #27ae60;
            border-radius: 50%;
            width: 80px;
            height: 80px;
            animation: spin 1.5s linear infinite;
            margin-bottom: 30px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        h1 {
            font-size: 28px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
        }
        
        h1 i {
            color: #27ae60;
        }
        
        .meeting-info {
            background: rgba(255, 255, 255, 0.1);
            padding: 25px;
            border-radius: 15px;
            margin: 25px 0;
            text-align: left;
            width: 100%;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .info-row {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .info-row:last-child {
            border-bottom: none;
            margin-bottom: 0;
            padding-bottom: 0;
        }
        
        .info-row label {
            display: block;
            color: rgba(255, 255, 255, 0.7);
            font-size: 14px;
            margin-bottom: 5px;
        }
        
        .info-row .value {
            font-size: 16px;
            color: white;
        }
        
        .btn {
            background: #27ae60;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s;
            text-decoration: none;
            margin-top: 20px;
        }
        
        .btn:hover {
            background: #219653;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
        }
        
        .btn-secondary {
            background: #7f8c8d;
        }
        
        .btn-secondary:hover {
            background: #6c7b7d;
        }
        
        .alert {
            background: rgba(243, 156, 18, 0.2);
            border-left: 4px solid #f39c12;
            padding: 15px;
            margin: 20px 0;
            text-align: left;
            border-radius: 0 5px 5px 0;
            width: 100%;
        }
        
        .alert i {
            color: #f39c12;
            margin-right: 10px;
        }
        
        .countdown {
            font-size: 48px;
            font-weight: bold;
            color: #f39c12;
            margin: 20px 0;
            font-family: 'Courier New', monospace;
        }
        
        .student-badge {
            background: rgba(52, 152, 219, 0.2);
            padding: 10px 20px;
            border-radius: 20px;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="redirect-container">
        <div class="student-badge">
            <i class="fas fa-user-graduate"></i>
            <?php echo htmlspecialchars($student_name); ?> (<?php echo htmlspecialchars($student_id); ?>)
        </div>
        
        <div class="loading-spinner"></div>
        
        <h1>
            <i class="fas fa-chalkboard-teacher"></i>
            Joining: <?php echo htmlspecialchars($meeting['meeting_title']); ?>
        </h1>
        
        <p>Redirecting you to the virtual classroom...</p>
        
        <div class="countdown" id="countdown">5</div>
        
        <div class="alert">
            <i class="fas fa-info-circle"></i>
            <strong>Note:</strong> The class will open in a new tab. Please allow pop-ups for this site.
        </div>
        
        <div class="meeting-info">
            <div class="info-row">
                <label>Course</label>
                <div class="value"><?php echo htmlspecialchars($meeting['course_code'] . ' - ' . $meeting['course_name']); ?></div>
            </div>
            
            <div class="info-row">
                <label>Instructor</label>
                <div class="value"><?php echo htmlspecialchars($meeting['staff_name']); ?></div>
            </div>
            
            <div class="info-row">
                <label>Schedule</label>
                <div class="value"><?php echo date('F j, Y \a\t h:i A', strtotime($meeting['scheduled_time'])); ?></div>
            </div>
            
            <?php if ($meeting['meeting_password']): ?>
            <div class="info-row">
                <label>Class Status</label>
                <div class="value">Password Protected</div>
            </div>
            <?php endif; ?>
        </div>
        
        <div style="display: flex; gap: 15px; margin-top: 20px;">
            <button class="btn" onclick="redirectToMeeting()">
                <i class="fas fa-external-link-alt"></i> Open Class Now
            </button>
            
            <button class="btn btn-secondary" onclick="window.location.href='online.php'">
                <i class="fas fa-arrow-left"></i> Back to Classes
            </button>
        </div>
        
        <p style="margin-top: 30px; color: rgba(255,255,255,0.7); font-size: 14px;">
            <i class="fas fa-headphones"></i>
            Please ensure you have a working microphone and camera for interactive sessions.
        </p>
    </div>
    
    <script>
        // Auto-redirect function
        function redirectToMeeting() {
            const meetingLink = "<?php echo $jitsi_url; ?>";
            console.log("Redirecting to class:", meetingLink);
            
            // Open in new tab
            window.open(meetingLink, '_blank', 'noopener,noreferrer');
            
            // Show success message
            document.querySelector('h1').innerHTML = '<i class="fas fa-check-circle"></i> Class Opened!';
            document.querySelector('p').textContent = 'The class has been opened in a new tab. You can close this window.';
            document.getElementById('countdown').style.display = 'none';
            
            // Close this window after 3 seconds
            setTimeout(() => {
                window.close();
            }, 3000);
        }
        
        // Countdown timer
        let countdownValue = 5;
        const countdownElement = document.getElementById('countdown');
        
        function updateCountdown() {
            countdownElement.textContent = countdownValue;
            if (countdownValue > 0) {
                countdownValue--;
                setTimeout(updateCountdown, 1000);
            } else {
                redirectToMeeting();
            }
        }
        
        // Start countdown on page load
        document.addEventListener('DOMContentLoaded', function() {
            updateCountdown();
            
            // Also try immediate redirect after short delay
            setTimeout(() => {
                redirectToMeeting();
            }, 500);
        });
        
        // Handle if popup is blocked
        let popupBlocked = false;
        
        function checkPopup() {
            if (!window.opener && window.name === '') {
                popupBlocked = true;
                document.querySelector('.alert').innerHTML = `
                    <i class="fas fa-exclamation-triangle"></i>
                    <strong>Pop-up Blocked!</strong> Please allow pop-ups for this site and click "Open Class Now" button.
                `;
            }
        }
        
        // Check after a short delay
        setTimeout(checkPopup, 2000);
    </script>
</body>
</html>