<?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>
<html lang="en">
<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>
        body {
            background-color: #f0f2f5;
            font-family: 'Tajawal', sans-serif;
            overflow: hidden; /* Hide scrollbars for TV feel */
            padding-bottom: 60px; /* Space for marquee */
        }
        .header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 20px;
            text-align: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .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; /* Slightly smaller to fit two lines */
            font-weight: bold;
            text-align: center;
            border-bottom: 2px solid #e9ecef;
            color: #333;
            line-height: 1.3;
        }
        .serving-section {
            padding: 15px;
            text-align: center;
            flex-grow: 1;
            background: #e3f2fd;
            display: flex;
            flex-direction: column;
            justify-content: center; /* Center vertically */
        }
        .serving-label {
            font-size: 1.1rem;
            color: #1976d2;
            margin-bottom: 10px;
            text-transform: uppercase;
            font-weight: 600;
        }
        .serving-list {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            width: 100%;
            align-items: center; /* Center items vertically in grid */
        }
        .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;
            min-height: 100px;
        }
        .serving-number {
            font-size: 3.5rem; /* Adjusted for grid */
            font-weight: 800;
            color: #0d47a1;
            line-height: 1;
            animation: pulse 2s infinite;
        }
        .waiting-section {
            padding: 15px;
            background: #fff;
            border-top: 1px dashed #dee2e6;
        }
        .waiting-label {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .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 {
            position: absolute;
            top: 20px;
            right: 20px;
            font-size: 1.5rem;
            font-weight: bold;
            color: white;
        }
        /* Marquee Footer Styles */
        .footer-marquee {
            position: fixed;
            bottom: 0;
            left: 0;
            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 */
        }
        .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>

<div class="header">
    <h1 class="m-0"><i class="bi bi-hospital"></i> Hospital Queue Status / حالة انتظار المستشفى</h1>
    <div class="clock" id="clock">00:00:00</div>
</div>

<div class="container-fluid p-4">
    <div class="row g-4" 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>
    
    function updateClock() {
        const now = new Date();
        document.getElementById('clock').innerText = now.toLocaleTimeString();
    }
    setInterval(updateClock, 1000);
    updateClock();

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

    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
            item.doctor_name_ar = item.doctor_name_ar || 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" style="grid-column: span 2;">No active patient<br>لا يوجد مريض</div>';
            
            if (dept.serving.length > 0) {
                servingHtml = dept.serving.map(s => {
                    let docName = '';
                    if (s.doctor_name_en && s.doctor_name_ar) {
                        docName = `${s.doctor_name_en}<br>${s.doctor_name_ar}`;
                    } else {
                        docName = s.doctor_name || '';
                    }
                    
                    return `
                    <div class="serving-item">
                        <div class="serving-number">${s.token_number}</div>
                        <div class="small text-muted text-center" style="line-height:1.2; font-size:0.85rem;">${docName}</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="col-md-4 col-lg-3">
                    <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>