<?php
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';
$meeting_id = $_GET['meeting_id'] ?? '';

// Get meeting details
$meeting = null;
if ($meeting_id) {
    $meetingQuery = "SELECT * FROM meetings WHERE meeting_id = '$meeting_id' AND staff_id = '$staff_email'";
    $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; // This creates "BIO202512187c2afe"
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meeting 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: #f0f2f5;
            height: 100vh;
            overflow: hidden;
        }
        
        .meeting-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        
        /* Header */
        .meeting-header {
            background: #202342;
            color: white;
            padding: 15px 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
            position: relative;
        }
        
        .meeting-info h2 {
            font-size: 20px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .meeting-info h2 i {
            color: #4CAF50;
        }
        
        .meeting-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: center;
        }
        
        .badge {
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-light {
            background: rgba(255,255,255,0.2);
            color: white;
        }
        
        .badge-green {
            background: #4CAF50;
            color: white;
        }
        
        .meeting-id-display {
            font-family: 'Courier New', monospace;
            background: rgba(255,255,255,0.1);
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 13px;
        }
        
        /* Controls */
        .controls {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            background: rgba(255,255,255,0.15);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
            text-decoration: none;
        }
        
        .btn:hover {
            background: rgba(255,255,255,0.25);
            transform: translateY(-1px);
        }
        
        .btn-green {
            background: #4CAF50;
        }
        
        .btn-green:hover {
            background: #45a049;
        }
        
        /* Main Content */
        .meeting-main {
            flex: 1;
            display: flex;
            position: relative;
            overflow: hidden;
        }
        
        /* Jitsi Iframe */
        .jitsi-iframe-container {
            flex: 1;
            width: 100%;
            height: 100%;
            position: relative;
            background: #000;
        }
        
        .jitsi-iframe {
            width: 100%;
            height: 100%;
            border: none;
            background: #000;
        }
        
        /* Loading Screen */
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.9);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            z-index: 100;
            color: white;
            text-align: center;
            padding: 20px;
        }
        
        .loading-spinner {
            border: 4px solid rgba(255,255,255,0.3);
            border-top: 4px solid #4CAF50;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Meeting Link Box */
        .link-box {
            background: rgba(255,255,255,0.1);
            padding: 15px;
            border-radius: 8px;
            margin-top: 25px;
            max-width: 600px;
            width: 90%;
        }
        
        .link-box h4 {
            margin-bottom: 10px;
            color: #4CAF50;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .link-display {
            background: rgba(0,0,0,0.3);
            padding: 10px;
            border-radius: 5px;
            font-family: 'Courier New', monospace;
            word-break: break-all;
            margin-bottom: 15px;
            border: 1px solid rgba(255,255,255,0.1);
        }
        
        /* Side Panel */
        .side-panel {
            position: absolute;
            top: 0;
            right: 0;
            width: 300px;
            height: 100%;
            background: rgba(32, 35, 66, 0.95);
            color: white;
            padding: 20px;
            transform: translateX(100%);
            transition: transform 0.3s ease;
            z-index: 100;
            overflow-y: auto;
        }
        
        .side-panel.active {
            transform: translateX(0);
        }
        
        .panel-toggle {
            position: absolute;
            top: 50%;
            right: 300px;
            transform: translateY(-50%);
            background: #202342;
            color: white;
            border: none;
            width: 40px;
            height: 60px;
            border-radius: 5px 0 0 5px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 101;
        }
        
        /* Meeting Details */
        .meeting-details {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid rgba(255,255,255,0.1);
        }
        
        .detail-item {
            margin-bottom: 15px;
        }
        
        .detail-item label {
            display: block;
            color: #aaa;
            font-size: 12px;
            margin-bottom: 5px;
        }
        
        .detail-item .value {
            font-size: 14px;
            color: white;
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            .meeting-header {
                padding: 12px 15px;
            }
            
            .meeting-info h2 {
                font-size: 16px;
            }
            
            .side-panel {
                width: 100%;
            }
            
            .panel-toggle {
                right: 100%;
            }
        }
    </style>
</head>
<body>
  

    <div class="meeting-container">
        <!-- Header -->
        <div class="meeting-header">
            <div class="meeting-info">
                <h2>
                    <i class="fas fa-video"></i>
                    <?php echo htmlspecialchars($meeting['meeting_title']); ?>
                </h2>
                <div class="meeting-meta">
                    <span class="badge badge-light"><?php echo htmlspecialchars($meeting['course_code']); ?></span>
                    <span class="badge badge-green"><?php echo htmlspecialchars($meeting['program']); ?></span>
                    <span class="meeting-id-display"><?php echo $meeting['meeting_id']; ?></span>
                </div>
            </div>
            
            <div class="controls">
                <button class="btn btn-green" onclick="copyMeetingLink()">
                    <i class="fas fa-link"></i> Copy Link
                </button>
                <button class="btn" onclick="toggleFullscreen()">
                    <i class="fas fa-expand"></i> Fullscreen
                </button>
                <button class="btn" onclick="window.location.href='meetings.php'">
                    <i class="fas fa-arrow-left"></i> Back
                </button>
            </div>
        </div>
        
        <!-- Main Meeting Area -->
        <div class="meeting-main">
            <!-- Jitsi Iframe -->
            <div class="jitsi-iframe-container" id="jitsiContainer">
                <iframe 
                    src="https://meet.jit.si/<?php echo $room_name; ?>"
                    class="jitsi-iframe"
                    allow="camera; microphone; display-capture; fullscreen"
                    allowfullscreen
                    title="Virtual Classroom"
                ></iframe>
            </div>
            
            <!-- Loading Overlay -->
            <div class="loading-overlay" id="loadingOverlay">
                <div class="loading-spinner"></div>
                <h3>Connecting to Virtual Classroom...</h3>
                <p>Please wait while we establish the connection.</p>
                
                <!-- Meeting Link Display -->
                <div class="link-box">
                    <h4><i class="fas fa-share-alt"></i> Share Meeting Link</h4>
                    <div class="link-display" id="meetingLink">
                        https://meet.jit.si/<?php echo $room_name; ?>
                    </div>
                    <button class="btn btn-green" onclick="copyMeetingLink()">
                        <i class="fas fa-copy"></i> Copy Link
                    </button>
                </div>
            </div>
            
            <!-- Panel Toggle Button -->
            <button class="panel-toggle" onclick="toggleSidePanel()">
                <i class="fas fa-info-circle"></i>
            </button>
            
            <!-- Side Panel -->
            <div class="side-panel" id="sidePanel">
                <h3><i class="fas fa-info-circle"></i> Meeting Details</h3>
                
                <div class="meeting-details">
                    <div class="detail-item">
                        <label>Meeting Title</label>
                        <div class="value"><?php echo htmlspecialchars($meeting['meeting_title']); ?></div>
                    </div>
                    
                    <div class="detail-item">
                        <label>Course</label>
                        <div class="value">
                            <?php echo htmlspecialchars($meeting['course_code']); ?> - 
                            <?php echo htmlspecialchars($meeting['course_name']); ?>
                        </div>
                    </div>
                    
                    <div class="detail-item">
                        <label>Program & Intake</label>
                        <div class="value">
                            <?php echo htmlspecialchars($meeting['program']); ?> - 
                            <?php echo htmlspecialchars($meeting['intake']); ?>
                        </div>
                    </div>
                    
                    <div class="detail-item">
                        <label>Academic Year</label>
                        <div class="value"><?php echo htmlspecialchars($meeting['year']); ?></div>
                    </div>
                    
                    <div class="detail-item">
                        <label>Scheduled Time</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="detail-item">
                        <label>Meeting Password</label>
                        <div class="value"><?php echo htmlspecialchars($meeting['meeting_password']); ?></div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="detail-item">
                        <label>Meeting ID</label>
                        <div class="value" style="font-family: 'Courier New', monospace;">
                            <?php echo $meeting['meeting_id']; ?>
                        </div>
                    </div>
                    
                    <div class="detail-item">
                        <label>Created By</label>
                        <div class="value"><?php echo htmlspecialchars($meeting['staff_name']); ?></div>
                    </div>
                </div>
                
                <!-- Quick Actions -->
                <div class="meeting-details">
                    <h4><i class="fas fa-bolt"></i> Quick Actions</h4>
                    <div style="display: flex; flex-direction: column; gap: 10px; margin-top: 15px;">
                        <button class="btn btn-green" onclick="reloadMeeting()">
                            <i class="fas fa-redo"></i> Reload Meeting
                        </button>
                        <button class="btn" onclick="openInNewTab()">
                            <i class="fas fa-external-link-alt"></i> Open in New Tab
                        </button>
                        <button class="btn" onclick="toggleAudio()">
                            <i class="fas fa-volume-mute"></i> Mute Audio
                        </button>
                        <button class="btn" onclick="toggleVideo()">
                            <i class="fas fa-video-slash"></i> Disable Video
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // Configuration
        const meetingLink = "https://meet.jit.si/<?php echo $room_name; ?>";
        const iframe = document.querySelector('.jitsi-iframe');
        const loadingOverlay = document.getElementById('loadingOverlay');
        const sidePanel = document.getElementById('sidePanel');
        
        console.log("Meeting URL:", meetingLink);
        
        // Function to hide loading overlay when meeting loads
        function hideLoadingOverlay() {
            setTimeout(() => {
                loadingOverlay.style.display = 'none';
                console.log("Meeting loaded successfully");
            }, 3000); // Hide after 3 seconds
        }
        
        // Function to copy meeting link
        function copyMeetingLink() {
            navigator.clipboard.writeText(meetingLink).then(() => {
                alert('✓ Meeting link copied to clipboard!\n\nShare this link with students:\n' + meetingLink);
            }).catch(err => {
                // Fallback for older browsers
                const textArea = document.createElement('textarea');
                textArea.value = meetingLink;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                alert('✓ Meeting link copied!\n\nShare with students:\n' + meetingLink);
            });
        }
        
        // Function to toggle fullscreen
        function toggleFullscreen() {
            const container = document.querySelector('.jitsi-iframe-container');
            
            if (!document.fullscreenElement) {
                if (container.requestFullscreen) {
                    container.requestFullscreen();
                } else if (container.webkitRequestFullscreen) {
                    container.webkitRequestFullscreen();
                } else if (container.msRequestFullscreen) {
                    container.msRequestFullscreen();
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                }
            }
        }
        
        // Function to toggle side panel
        function toggleSidePanel() {
            sidePanel.classList.toggle('active');
        }
        
        // Function to reload meeting
        function reloadMeeting() {
            if (confirm('Reload the meeting? This will refresh the video conference.')) {
                iframe.src = iframe.src;
                loadingOverlay.style.display = 'flex';
                hideLoadingOverlay();
            }
        }
        
        // Function to open meeting in new tab
        function openInNewTab() {
            window.open(meetingLink, '_blank');
        }
        
        // Functions to control audio/video (these would need Jitsi API)
        function toggleAudio() {
            alert('Note: To mute/unmute, use the microphone button in the Jitsi meeting.');
        }
        
        function toggleVideo() {
            alert('Note: To enable/disable video, use the camera button in the Jitsi meeting.');
        }
        
        // Hide loading overlay when iframe loads
        iframe.addEventListener('load', function() {
            console.log("Iframe loaded");
            hideLoadingOverlay();
            
            // Try to post message to iframe for better integration
            try {
                iframe.contentWindow.postMessage({
                    event: 'command',
                    func: 'toggleAudio'
                }, '*');
            } catch (e) {
                console.log("Could not send message to iframe:", e);
            }
        });
        
        // Handle iframe errors
        iframe.addEventListener('error', function() {
            console.error("Iframe failed to load");
            loadingOverlay.innerHTML = `
                <div style="text-align: center;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #ff9800; margin-bottom: 20px;"></i>
                    <h3>Unable to Load Meeting</h3>
                    <p style="margin-bottom: 20px;">There was an error loading the meeting.</p>
                    <div style="display: flex; flex-direction: column; gap: 10px; align-items: center;">
                        <button class="btn btn-green" onclick="reloadMeeting()">
                            <i class="fas fa-redo"></i> Try Again
                        </button>
                        <button class="btn" onclick="openInNewTab()">
                            <i class="fas fa-external-link-alt"></i> Open in New Tab
                        </button>
                    </div>
                </div>
            `;
        });
        
        // Auto-hide loading after 10 seconds max
        setTimeout(() => {
            if (loadingOverlay.style.display !== 'none') {
                loadingOverlay.style.display = 'none';
                console.log("Auto-hid loading overlay");
            }
        }, 10000);
        
        // Handle fullscreen change
        document.addEventListener('fullscreenchange', function() {
            const isFullscreen = !!document.fullscreenElement;
            console.log("Fullscreen:", isFullscreen);
        });
        
        // Initialize
        window.addEventListener('load', function() {
            console.log("Page loaded, starting meeting...");
            // Auto-hide loading after initial delay
            hideLoadingOverlay();
        });
        
        // Handle beforeunload
        window.addEventListener('beforeunload', function(e) {
            // Optional: Show confirmation
            // e.preventDefault();
            // e.returnValue = '';
        });
    </script>
</body>
</html>