<?php
require_once 'db/config.php';
// Use 'en' as base for structure, but we display both languages.
$lang = 'en';

// Fetch initial data to render skeletal HTML
try {
    $db = db();
    // Use raw query instead of fetching all to handle potential empty tables gracefully if needed, 
    // though here we just get all departments.
    $departments = $db->query("SELECT * FROM departments WHERE show_in_queue = 1")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // If DB fails, we can't show much, but let's not crash the whole page if possible.
    // die("Database error"); 
    $departments = [];
}
?>
<!DOCTYPE html>
<?php require_once __DIR__ . "/helpers.php"; ?><html lang="<?php echo get_lang_code(); ?>" dir="<?php echo get_dir(); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Queue Display / شاشة الانتظار</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        html, body {
            height: 100%;
            margin: 0;
            overflow: hidden; /* Hide scrollbars for TV feel */
        }
        body {
            background-color: #f0f2f5;
            font-family: 'Tajawal', sans-serif;
            display: flex;
            flex-direction: column;
        }
        .header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            flex-shrink: 0;
            height: 80px;
        }
        .header h1 {
            margin: 0;
            font-size: 1.8rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .main-content {
            flex-grow: 1;
            padding: 20px;
            overflow: hidden; /* Container handles overflow */
            display: flex;
            flex-direction: column;
        }
        #departmentsContainer {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            height: 100%;
            justify-content: center;
            align-content: center; /* Center content vertically if space permits */
            overflow-y: auto;
        }
        .dept-wrapper {
            flex: 1 1 300px; /* Grow, shrink, base width */
            max-width: 450px;
            min-width: 250px;
            display: flex;
            flex-direction: column;
        }
        .dept-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
            height: 100%;
            transition: transform 0.3s;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        .dept-header {
            background: #f8f9fa;
            padding: 15px;
            font-size: 1.3rem; 
            font-weight: bold;
            text-align: center;
            border-bottom: 2px solid #e9ecef;
            color: #333;
            line-height: 1.3;
        }
        .serving-section {
            padding: 10px;
            text-align: center;
            flex-grow: 1;
            background: #e3f2fd;
            display: flex;
            flex-direction: column;
            justify-content: center; 
        }
        .serving-label {
            font-size: 1.0rem;
            color: #1976d2;
            margin-bottom: 5px;
            text-transform: uppercase;
            font-weight: 600;
        }
        .serving-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
            width: 100%;
            align-items: center; 
            justify-content: center;
        }
        .serving-item {
            background: rgba(255, 255, 255, 0.6);
            border-radius: 10px;
            padding: 5px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100%;
        }
        .serving-number {
            font-size: 3rem; 
            font-weight: 800;
            color: #0d47a1;
            line-height: 1;
            animation: pulse 2s infinite;
        }
        .waiting-section {
            padding: 10px;
            background: #fff;
            border-top: 1px dashed #dee2e6;
            min-height: 60px;
        }
        .waiting-label {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 5px;
            font-weight: bold;
            text-align: center;
        }
        .waiting-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            justify-content: center;
        }
        .waiting-item {
            background: #f1f3f5;
            color: #495057;
            padding: 5px 10px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 1.1rem;
        }
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        .clock-container {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .clock {
            font-size: 1.5rem;
            font-weight: bold;
            color: white;
        }
        /* Marquee Footer Styles */
        .footer-marquee {
            width: 100%;
            background: #002D62;
            color: white;
            padding: 10px 0;
            font-size: 1.5rem;
            white-space: nowrap;
            overflow: hidden;
            z-index: 1000;
            box-shadow: 0 -2px 5px rgba(0,0,0,0.2);
            border-top: 3px solid #fbbc04; /* Accent color */
            flex-shrink: 0;
            height: 60px;
        }
        .marquee-content {
            display: inline-block;
            padding-left: 100%;
            animation: marquee 25s linear infinite;
        }
        @keyframes marquee {
            0% { transform: translate(0, 0); }
            100% { transform: translate(-100%, 0); }
        }
    </style>
</head>
<body onclick="enableAudioContext()">

<div class="header">
    <h1 class="m-0"><i class="bi bi-hospital"></i> Hospital Queue Status / حالة انتظار المستشفى</h1>
    <div class="clock-container">
        <button id="fullscreenToggle" class="btn btn-outline-light btn-sm" onclick="toggleFullScreen()">
            <i class="bi bi-arrows-fullscreen"></i> Full Screen
        </button>
        <button id="soundToggle" class="btn btn-outline-light btn-sm" onclick="toggleSound(event)">
            <i class="bi bi-volume-up-fill" id="soundIcon"></i> Sound: ON
        </button>
        <div class="clock" id="clock">00:00:00</div>
    </div>
</div>

<div class="main-content">
    <div id="departmentsContainer">
        <!-- Javascript will inject cards here -->
    </div>
</div>

<!-- Footer Marquee -->
<div class="footer-marquee">
    <div class="marquee-content" id="marqueeContent">
        <span class="mx-3">Welcome to our hospital / أهلاً بكم في مستشفانا</span>
    </div>
</div>

<script>
    let audioEnabled = true;
    const announcedIds = new Set();
    let isFirstRun = true;
    let audioContextResumed = false;
    
    function updateClock() {
        const now = new Date();
        document.getElementById('clock').innerText = now.toLocaleTimeString();
    }
    setInterval(updateClock, 1000);
    updateClock();

    function enableAudioContext() {
        if (!audioContextResumed) {
            // Some browsers require a user interaction to allow speech synthesis
            if (window.speechSynthesis) {
                window.speechSynthesis.resume();
            }
            audioContextResumed = true;
        }
    }

    function toggleFullScreen() {
        if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen().catch(err => {
                console.log(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`);
            });
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            }
        }
    }

    function toggleSound(e) {
        if (e) e.stopPropagation(); // Prevent body onclick
        audioEnabled = !audioEnabled;
        const icon = document.getElementById('soundIcon');
        const btn = document.getElementById('soundToggle');
        if (audioEnabled) {
            icon.className = 'bi bi-volume-up-fill';
            btn.innerHTML = '<i class="bi bi-volume-up-fill" id="soundIcon"></i> Sound: ON';
            btn.classList.remove('btn-outline-danger');
            btn.classList.add('btn-outline-light');
            enableAudioContext();
            
            // Test speak
            if (window.speechSynthesis) {
                const u = new SpeechSynthesisUtterance("Sound enabled");
                window.speechSynthesis.speak(u);
            }
        } else {
            icon.className = 'bi bi-volume-mute-fill';
            btn.innerHTML = '<i class="bi bi-volume-mute-fill" id="soundIcon"></i> Sound: OFF';
            btn.classList.remove('btn-outline-light');
            btn.classList.add('btn-outline-danger');
            if (window.speechSynthesis) {
                window.speechSynthesis.cancel();
            }
        }
    }

    function fetchQueueStatus() {
        fetch('api/queue.php?action=list')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    checkForNewCalls(data.data);
                    renderDepartments(data.data);
                }
            })
            .catch(err => console.error('Fetch error:', err));
    }

    function checkForNewCalls(items) {
        // Filter for serving items
        const serving = items.filter(i => i.status === 'serving');

        if (isFirstRun) {
            // On first load, just mark current serving as announced so we don't spam
            serving.forEach(i => announcedIds.add(i.id));
            isFirstRun = false;
            return;
        }

        serving.forEach(item => {
            if (!announcedIds.has(item.id)) {
                announcedIds.add(item.id);
                if (audioEnabled) {
                    speakToken(item);
                }
            }
        });
    }

    function speakToken(item) {
        if (!window.speechSynthesis) return;

        // Cancel any pending speech to announce current immediately
        window.speechSynthesis.cancel();

        // English
        const textEn = `Token number ${item.token_number}, Room ${item.room_number ? item.room_number : ''}`;
        const uEn = new SpeechSynthesisUtterance(textEn);
        uEn.lang = 'en-US';
        uEn.rate = 0.9;

        // Arabic
        const textAr = `رقم ${item.token_number}, غرفة ${item.room_number ? item.room_number : ''}`;
        const uAr = new SpeechSynthesisUtterance(textAr);
        uAr.lang = 'ar-SA';
        uAr.rate = 0.8;

        window.speechSynthesis.speak(uEn);
        window.speechSynthesis.speak(uAr);
    }

    function renderDepartments(queueItems) {
        // Group by department
        const depts = {};
        
        // Initialize with server-side departments to ensure empty ones show up
        <?php foreach ($departments as $d): ?>
        depts[<?php echo $d['id']; ?>] = {
            id: <?php echo $d['id']; ?>,
            name_en: "<?php echo $d['name_en']; ?>",
            name_ar: "<?php echo $d['name_ar']; ?>",
            serving: [],
            waiting: []
        };
        <?php endforeach; ?>

        // Populate from queue
        queueItems.forEach(item => {
            if (!depts[item.department_id]) return;
            
            // Augment item with doctor names from API if available
            item.doctor_name_en = item.doctor_name_en || item.doctor_name; // Fallback
            
            if (item.status === 'serving') {
                depts[item.department_id].serving.push(item);
            } else if (item.status === 'waiting') {
                depts[item.department_id].waiting.push(item);
            }
        });

        const container = document.getElementById('departmentsContainer');
        container.innerHTML = '';

        Object.values(depts).forEach(dept => {
            
            let servingHtml = '<div class="text-muted small text-center w-100">No active patient<br>لا يوجد مريض</div>';
            
            if (dept.serving.length > 0) {
                servingHtml = dept.serving.map(s => {
                    let docName = '';
                    // Doctor Name: Prefix with Dr. and show only English name
                    if (s.doctor_name_en) {
                        docName = `Dr. ${s.doctor_name_en}`;
                    } else if (s.doctor_name) {
                        docName = `Dr. ${s.doctor_name}`;
                    }

                    // Wrap doctor name in a colored badge (e.g., bg-info)
                    let docInfo = '';
                    if (docName) {
                        docInfo = `<div class="mb-1 fw-bold badge bg-info text-white" style="font-size:0.9rem;">${docName}</div>`;
                    }

                    let roomInfo = '';
                    if (s.room_number) {
                        roomInfo = `<div class="fw-bold badge bg-warning text-dark" style="font-size:0.9rem;">Room/غرفة: ${s.room_number}</div>`;
                    }
                    
                    return `
                    <div class="serving-item">
                        <div class="serving-number">${s.token_number}</div>
                        <div class="small text-center mt-2 d-flex flex-column align-items-center">
                            ${docInfo}
                            ${roomInfo}
                        </div>
                    </div>`;
                }).join('');
            }

            let waitingHtml = '<span class="text-muted small">-</span>';
            if (dept.waiting.length > 0) {
                waitingHtml = dept.waiting.map(w => `<span class="waiting-item">${w.token_number}</span>`).join('');
            }

            const card = `
                <div class="dept-wrapper">
                    <div class="dept-card">
                        <div class="dept-header">
                            ${dept.name_en}
                            <div class="text-muted small mt-1" style="font-size: 1.1rem; font-weight: 500;">${dept.name_ar}</div>
                        </div>
                        <div class="serving-section">
                            <div class="serving-label">
                                Now Serving<br>
                                <span style="font-size: 0.9em;">جاري الخدمة</span>
                            </div>
                            <div class="serving-list">
                                ${servingHtml}
                            </div>
                        </div>
                        <div class="waiting-section">
                            <div class="waiting-label">Waiting / الانتظار</div>
                            <div class="waiting-list">
                                ${waitingHtml}
                            </div>
                        </div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', card);
        });
    }

    function fetchAds() {
        fetch('api/queue.php?action=get_ads')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data && data.data.length > 0) {
                    const adsContent = data.data.map(ad => 
                        `<span class="mx-5">${ad.text_en} - ${ad.text_ar}</span>`
                    ).join('<i class="bi bi-star-fill mx-3 text-warning"></i>');
                    
                    document.getElementById('marqueeContent').innerHTML = adsContent;
                } else {
                     // Fallback if no ads
                     document.getElementById('marqueeContent').innerHTML = '<span class="mx-3">Welcome to our hospital / أهلاً بكم في مستشفانا</span>';
                }
            })
            .catch(err => console.error('Ads fetch error:', err));
    }

    // Initial load
    fetchQueueStatus();
    fetchAds();
    
    // Poll every 5 seconds for queue
    setInterval(fetchQueueStatus, 5000);
    // Poll every 60 seconds for ads
    setInterval(fetchAds, 60000);

</script>

</body>
</html>