<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';

date_default_timezone_set('America/Sao_Paulo');

// Função para buscar imagens da pasta
function getImages() {
    $images = [];
    $valid_extensions = ['jpg', 'jpeg', 'png', 'gif'];
    
    // Verifica se o diretório existe
    if (!is_dir('assets/slides')) {
        mkdir('assets/slides', 0755, true);
    }
    
    // Lê todos os arquivos do diretório
    $files = scandir('assets/slides');
    
    foreach ($files as $file) {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (in_array($ext, $valid_extensions)) {
            $images[] = 'assets/slides/' . $file;
        }
    }
    
    return $images;
}

$images = getImages();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Painel de Chamadas</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            overflow: hidden;
            background: #000;
            color: white;
        }

        .slideshow-container {
            width: 100vw;
            height: 100vh;
            position: relative;
        }

        .slide {
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            transition: opacity 1.5s ease-in-out;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .slide.active {
            opacity: 1;
        }

        .slide img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        #patient-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background-color: rgba(0, 64, 128, 0.95);
            z-index: 1000;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            text-align: center;
        }

        #patient-overlay.patient-called {
            display: flex;
            animation: fadeIn 0.5s ease-in;
        }

        #patient-name {
            font-size: 8vw;
            margin-bottom: 2vh;
            animation: pulse 2s infinite;
        }

        #office-name {
            font-size: 4vw;
            color: #FFD700;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .waiting-info {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.8);
            padding: 20px;
            display: flex;
            justify-content: space-around;
            font-size: 1.5vw;
        }

        .waiting-count {
            text-align: center;
        }

        .waiting-count span {
            color: #FFD700;
            font-weight: bold;
        }

        .clock {
            position: fixed;
            top: 20px;
            right: 20px;
            font-size: 2vw;
            background: rgba(0, 0, 0, 0.8);
            padding: 10px 20px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="clock" id="clock"></div>
    
    <div class="slideshow-container">
        <!-- Slides serão inseridos aqui -->
    </div>

    <div id="patient-overlay">
        <div id="patient-display">
            <h1 id="patient-name"></h1>
            <h2 id="office-name"></h2>
        </div>
    </div>

    <div class="waiting-info" id="waiting-info">
        <!-- Informações de espera serão inseridas aqui -->
    </div>

    <audio id="patient-alert" preload="auto">
        <source src="assets/sound/call.mp3" type="audio/mpeg">
    </audio>

    <script>
        const slides = <?= json_encode($images) ?>;
        let currentSlide = 0;
        const SLIDE_DURATION = 8000;
        let lastPatientId = null;

        // Função para atualizar o relógio
        function updateClock() {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('pt-BR');
            document.getElementById('clock').textContent = timeStr;
        }

        // Função para buscar informações de pacientes
        async function fetchPatientInfo() {
            try {
                const response = await fetch('api/get_patient_info.php');
                const data = await response.json();
                
                if (data.next_patient && data.next_patient.id !== lastPatientId) {
                    lastPatientId = data.next_patient.id;
                    showPatientCall(data.next_patient);
                }
                
                updateWaitingInfo(data.waiting_counts);
            } catch (error) {
                console.error('Erro ao buscar informações:', error);
            }
        }

        // Função para mostrar chamada de paciente
        function showPatientCall(patient) {
            const overlay = document.getElementById('patient-overlay');
            document.getElementById('patient-name').textContent = patient.name;
            document.getElementById('office-name').textContent = patient.office_name;
            
            overlay.classList.add('patient-called');
            
            // Tocar som
            const audio = document.getElementById('patient-alert');
            audio.play();
            
            // Remover overlay após 10 segundos
            setTimeout(() => {
                overlay.classList.remove('patient-called');
            }, 10000);
        }

        // Função para atualizar informações de espera
        function updateWaitingInfo(counts) {
            const container = document.getElementById('waiting-info');
            container.innerHTML = counts.map(count => `
                <div class="waiting-count">
                    <div>${count.office_name}</div>
                    <div><span>${count.waiting}</span> aguardando</div>
                </div>
            `).join('');
        }

        // Inicialização
        window.onload = function() {
            // Criar slides
            const container = document.querySelector('.slideshow-container');
            if (slides.length === 0) {
                container.innerHTML = '<div style="text-align: center; padding: 20px;">Nenhuma imagem encontrada</div>';
            } else {
                slides.forEach((slide, index) => {
                    const slideDiv = document.createElement('div');
                    slideDiv.className = `slide ${index === 0 ? 'active' : ''}`;
                    slideDiv.innerHTML = `<img src="${slide}" alt="Slide ${index + 1}">`;
                    container.appendChild(slideDiv);
                });
            }

            // Iniciar atualizações
            updateClock();
            setInterval(updateClock, 1000);
            setInterval(() => {
                if (slides.length > 1) {
                    nextSlide();
                }
            }, SLIDE_DURATION);
            
            // Buscar informações de pacientes
            fetchPatientInfo();
            setInterval(fetchPatientInfo, 3000);

            // Recarregar página a cada 6 horas
            setTimeout(() => window.location.reload(), 6 * 60 * 60 * 1000);
        };

        // Função para próximo slide
        function nextSlide() {
            const slideElements = document.querySelectorAll('.slide');
            slideElements[currentSlide].classList.remove('active');
            currentSlide = (currentSlide + 1) % slides.length;
            slideElements[currentSlide].classList.add('active');
        }

        // Prevenir menu de contexto
        document.addEventListener('contextmenu', e => e.preventDefault());
    </script>
</body>
</html>