<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['patient_id'])) {
    header("Location: ../login.php");
    exit();
}
include '../../include/config.php';

$user_id = $_SESSION['patient_id'];
$user_name = $_SESSION['patient_name'];

// Generate a unique room name if not provided
$room_id = isset($_GET['room']) ? $_GET['room'] : 'UHD_Patient_' . $user_id . '_' . time();

$meeting_link = "https://meet.jit.si/" . $room_id;

$page_title = 'Video Consultation | UHD';
include '../../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>UHD Video Consultation</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            font-family: 'Segoe UI', sans-serif;
        }
        #jitsi-container {
            height: 100vh;
            width: 100%;
        }
        .loading {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            z-index: 1000;
            background: white;
            padding: 30px;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #d4a017;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .exit-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1001;
            background: #dc3545;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 25px;
            cursor: pointer;
            font-weight: bold;
            transition: 0.2s;
        }
        .exit-btn:hover {
            background: #c82333;
            transform: scale(1.02);
        }
        .info-bar {
            position: fixed;
            top: 20px;
            left: 20px;
            background: rgba(0,0,0,0.6);
            backdrop-filter: blur(10px);
            padding: 8px 16px;
            border-radius: 20px;
            color: white;
            z-index: 1001;
            font-size: 12px;
        }
        .copy-link-btn {
            position: fixed;
            bottom: 20px;
            left: 20px;
            z-index: 1001;
            background: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 25px;
            cursor: pointer;
            font-weight: bold;
            transition: 0.2s;
        }
        .copy-link-btn:hover {
            background: #218838;
        }
    </style>
</head>
<body>
    <div class="loading" id="loading">
        <div class="spinner"></div>
        <h3>Connecting to consultation...</h3>
        <p>Please wait while we connect you to your doctor</p>
    </div>
    
    <div class="info-bar">
        <i class="fas fa-video"></i> UHD Telemedicine | Room: <?= substr($room_id, -8) ?>
    </div>
    
    <button class="copy-link-btn" onclick="copyLink()">
        <i class="fas fa-copy"></i> Copy Meeting Link
    </button>
    
    <button class="exit-btn" onclick="endCall()">
        <i class="fas fa-phone-slash"></i> End Call
    </button>
    
    <div id="jitsi-container"></div>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <script src="https://meet.jit.si/external_api.js"></script>
    <script>
        const domain = 'meet.jit.si';
        const roomName = '<?php echo $room_id; ?>';
        const meetingLink = '<?php echo $meeting_link; ?>';
        
        const options = {
            roomName: roomName,
            width: '100%',
            height: '100%',
            parentNode: document.querySelector('#jitsi-container'),
            userInfo: {
                displayName: '<?php echo addslashes($user_name); ?> (Patient)'
            },
            configOverwrite: {
                startWithAudioMuted: false,
                startWithVideoMuted: false,
                prejoinPageEnabled: false,
                enableWelcomePage: false,
                disableDeepLinking: true,
                toolbarButtons: [
                    'microphone', 'camera', 'chat', 'tileview', 
                    'fullscreen', 'hangup', 'raise-hand', 'share-screen'
                ]
            },
            interfaceConfigOverwrite: {
                SHOW_JITSI_WATERMARK: false,
                SHOW_BRAND_WATERMARK: false,
                MOBILE_APP_PROMO: false,
                TOOLBAR_BUTTONS: [
                    'microphone', 'camera', 'chat', 'tileview', 
                    'fullscreen', 'hangup', 'raise-hand', 'share-screen'
                ]
            }
        };
        
        const api = new JitsiMeetExternalAPI(domain, options);
        
        api.addEventListener('videoConferenceJoined', () => {
            document.getElementById('loading').style.display = 'none';
        });
        
        function copyLink() {
            navigator.clipboard.writeText(meetingLink);
            alert('Meeting link copied to clipboard!\n\nShare this link with your doctor to join the consultation.');
        }
        
        function endCall() {
            if (confirm('Are you sure you want to end this consultation?')) {
                api.executeCommand('hangup');
                setTimeout(() => {
                    window.location.href = 'consultations.php';
                }, 1000);
            }
        }
        
        api.addEventListener('readyToClose', () => {
            window.location.href = 'consultations.php';
        });
    </script>
</body>
</html>

<?php include '../../include/footer.php'; ?>