<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TV Indoor</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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

        .slideshow-container {
            width: 100vw;
            height: 100vh;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
        }

        .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: #004080;
            color: white;
            z-index: 1000;
            justify-content: center;
            align-items: center;
            text-align: center;
        }

        #patient-overlay.active {
            display: flex;
            background-color: red;
        }

        #patient-name {
            font-size: 10vw;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }
    </style>
</head>
<body>
    <div class="slideshow-container">
        <!-- Os slides serão inseridos aqui dinamicamente -->
    </div>

    <div id="patient-overlay">
        <div id="patient-display">
            <h1 id="patient-name">Aguardando Chamada</h1>
        </div>
    </div>

    <audio id="patient-alert">
        <source src="alert.mp3" type="audio/mpeg">
        Seu navegador não suporta reprodução de áudio.
    </audio>

    <?php
    function getImages() {
        $images = [];
        $valid_extensions = ['jpg', 'jpeg', 'png', 'gif'];
        
        if (!is_dir('img')) {
            mkdir('img', 0755, true);
        }
        
        $files = scandir('img');
        
        foreach ($files as $file) {
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            if (in_array($ext, $valid_extensions)) {
                $images[] = 'img/' . $file;
            }
        }
        
        return $images;
    }
    
    $images = getImages();
    ?>

    <script>
        const slides = <?php echo json_encode($images); ?>;
        let currentSlide = 0;
        const SLIDE_DURATION = 8000;
        let slideshowInterval;

        const patientOverlay = document.getElementById('patient-overlay');
        const patientNameElement = document.getElementById('patient-name');
        const audioElement = document.getElementById('patient-alert');

        function createSlides() {
            if (slides.length === 0) {
                const container = document.querySelector('.slideshow-container');
                container.innerHTML = '<div style="color: white; text-align: center; width: 100%; padding: 20px;">Nenhuma imagem encontrada na pasta img/</div>';
                return;
            }

            const container = document.querySelector('.slideshow-container');
            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);
            });
        }

        function nextSlide() {
            if (slides.length <= 1) return;
            
            const slideElements = document.querySelectorAll('.slide');
            slideElements[currentSlide].classList.remove('active');
            currentSlide = (currentSlide + 1) % slides.length;
            slideElements[currentSlide].classList.add('active');
        }

        function autoFullscreen() {
            const element = document.documentElement;
            if (element.requestFullscreen) {
                element.requestFullscreen();
            } else if (element.webkitRequestFullscreen) {
                element.webkitRequestFullscreen();
            } else if (element.msRequestFullscreen) {
                element.msRequestFullscreen();
            }
        }

        function fetchNextPatient() {
            fetch('get_next_patient.php')
                .then(response => response.json())
                .then(data => {
                    if (data.name) {
                        // Para todos os intervalos de slide
                        clearInterval(slideshowInterval);
                        
                        // Reproduzir áudio de alerta
                        audioElement.play();
                        
                        // Quando o áudio terminar, falar o nome do paciente
                        audioElement.onended = () => {
                            const synth = window.speechSynthesis;
                            const utterance = new SpeechSynthesisUtterance(data.name);
                            utterance.lang = "pt-BR";
                            synth.speak(utterance);
                        };
                        
                        // Mostrar nome do paciente em tela cheia
                        patientNameElement.textContent = data.name;
                        patientOverlay.classList.add('active');
                        
                        // Voltar ao slideshow após 10 segundos
                        setTimeout(() => {
                            patientNameElement.textContent = 'Aguardando Chamada';
                            patientOverlay.classList.remove('active');
                            
                            // Reinicia o slideshow
                            if (slides.length > 1) {
                                slideshowInterval = setInterval(nextSlide, SLIDE_DURATION);
                            }
                        }, 10000);
                    }
                })
                .catch(error => {
                    console.error('Erro ao buscar paciente:', error);
                });
        }

        window.onload = function() {
            createSlides();
            autoFullscreen();
            
            document.addEventListener('click', autoFullscreen);
            
            // Inicia a transição automática de slides
            if (slides.length > 1) {
                slideshowInterval = setInterval(nextSlide, SLIDE_DURATION);
            }

            // Buscar paciente a cada 3 segundos
            setInterval(fetchNextPatient, 3000);

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

        document.addEventListener('fullscreenchange', function() {
            if (!document.fullscreenElement) {
                autoFullscreen();
            }
        });

        document.addEventListener('contextmenu', event => event.preventDefault());
    </script>
</body>
</html>