<?php
require 'config_painel.php';
$CNES       = $_GET['CNES'] ?? $_GET['cnes'] ?? 0;
$idPainel   = $_GET['PAINEL'] ?? $_GET['painel'] ?? 0;

function pegarNomePainel($CNES)
{
    require 'banco/conexao.php';

    $sql = "SELECT  UPPER(t1.nome_painel) AS  titulo FROM reg_tb_painelchamada t1
        INNER JOIN tb_estabelecimento t2 ON t1.codigoestabelecimento_cnes = t2.codigoestabelecimento_cnes
     WHERE t2.cnes_estabelecimento = :cnes ";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':cnes', $CNES, PDO::PARAM_STR);
    $stmt->execute();

    $config = $stmt->fetch(PDO::FETCH_ASSOC);

    return $config;
}

$config = pegarNomePainel($CNES);

//if (!$config) {
//   header('Location: ./');
//   exit;
//}

$nome_painel = 'Policlínica de Candeias';

?>
<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="icon" type="image/x-icon" href="https://candeias.portalgsaude.app.br/app-assets/images/favicon.png" />
    <title><?php echo htmlspecialchars($nome_painel); ?></title>
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(to right, #e9edf1, #b3c9d7);
            margin: 0;
            padding: 0;
        }

        .container {
            max-width: 1920px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            background-color: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .header .logo img {
            height: 40px;
        }

        .header .location {
            font-size: 1.5rem;
            font-weight: bold;
            color: #0056b3;
        }

        .header .hora {
            font-size: 1.2rem;
            color: #0056b3;
        }

        .main {
            display: block;
            margin-top: 10px;
            grid-template-rows: min-content min-content;
        }

        .chamadas {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            height: auto;
        }

        .historico {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            height: auto;
            margin-top:10px
        }

        .esperando-chamar {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            padding: 20px;
            margin-top: -10px;
            border-radius: 15px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            height: auto;
        }

        .historico ul,
        .esperando-chamar ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }

        .historico li,
        .esperando-chamar li {
            background: linear-gradient(to right, #0e093f, #0b028b);
            padding: 14px;
            border-radius: 1px;
            margin-bottom: 10px;
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
            align-items: center;
            font-size: 1.1rem;
            transition: background 0.3s;
            border-radius: 8px;
        }

        .qrcode {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            padding: 10px;
            border-radius: 15px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
        }

        .qrcode ul {
            list-style-type: none;
            padding: 0;
            margin: 0;
        }

        .qrcode li {
            background: rgb(255, 255, 255);
            padding: 14px;
            border-radius: 9px;
            margin-bottom: 10px;
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
            align-items: center;
            font-size: 1.1rem;
            transition: background 0.3s;
        }

        .chamadas-info {
            /*background: linear-gradient(to right, #0e093f, #0b028b);*/
            background: #0F71B6;
            color: #ffffff;
            padding: 5px;
            border-radius: 12px;
            margin-bottom: 5px;
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            text-align: center;
        }

        .chamadas-info p {
            margin: 0;
            font-size: 1.5rem;
        }

        .chamadas-info .doutor {
            margin-top: 10px;
            font-size: 1rem;
            color: #c2d4f5;
            text-align: left;
            font-size: 14pt;
            font-weight: bold;
        }

        .chamadas-info .status {
            margin-top: 10px;
            font-size: 1rem;
            font-weight: bold;
        }

        .esperando-chamar li {
            background: linear-gradient(to right, #0e093f, #0b028b);
            padding: 14px;
            border-radius: 9px;
            margin-bottom: 10px;
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
            align-items: center;
            font-size: 1.1rem;
            transition: background 0.3s;

        }

        .historico li {
            /*background: linear-gradient(to right, #0e093f, #0b028b);*/
            background: #0F71B6;
            padding: 14px;
            border-radius: 1px;
            margin-bottom: 10px;
            display: grid;
            grid-template-columns: 1fr 2fr 1fr;
            align-items: center;
            font-size: 14pt;
            transition: background 0.3s;
            border-radius: 12px;
        }


        .sala {
            font-size: 0.9rem;
            color: #ffffff;
        }

        .esperando-chamar .doutor,
        .historico .doutor {
            font-size: 1rem;
            color: #ffffff;
        }

        .esperando-chamar .hora,
        .historico .hora {
            font-size: 1rem;
            color: #ffffff;
        }

        .video-yt {
            border: 2px dashed #ccc;
            border-radius: 10px;
            height: 400px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #ffffff;
            font-size: 1.5rem;
            background: linear-gradient(to right, #0e093f, #0b028b);
            opacity: 0.9;
            backdrop-filter: blur(5px);
            transition: opacity 0.3s;
            margin-top: -415px;
        }

        .video-yt:hover {
            opacity: 1;
        }


        .icon {
            display: inline-block;
            margin-right: 8px;
            font-size: 1.4rem;
        }

        .icon-person {
            color: #ffffff;
        }

        .icon-clock {
            color: #f39c12;
        }

        .icon-history {
            color: #27ae60;
            width: 50px !important;
        }

        .logo {
            display: flex;
            align-items: center;/
        }

        .logo img {
            height: 40px;
            margin-right: 10px;
        }

        .logo-text {
            font-size: 1.5rem;
            color: #0056b3;
            font-weight: bold;
        }

        .hora {
            display: flex;
            align-items: center;
            font-size: 1.2rem;
            color: #ffffff;
            margin-left: 20px;/
        }

        .icon-clock {
            margin-right: 5px;
            color: #0056b3;
        }

        #telefone {
            list-style-type: none;
            padding: 0;
        }

        #telefone li {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        @media screen and (max-width: 768px) {
            .container {
                padding: 10px;
            }


            .main {
                display: block;
                margin-top: 10px;
            }


            .historico,
            .qrcode {
                display: none;
            }


            .chamadas,
            .esperando-chamar {
                width: 100%;
                margin-bottom: 20px;
            }

            .header {
                flex-direction: column;
                align-items: flex-start;
            }

            .header .logo img {
                height: 30px;
            }

            .header .hora {
                margin-left: 0;
                margin-top: 10px;
            }

            .header .location {
                font-size: 1.2rem;
            }


            .chamadas-info {
                font-size: 1rem;
            }

            .chamadas-info p {
                font-size: 1.2rem;
            }
        }
    </style>

</head>

<body>
    <div class="container">
        <div class="header" style='line-height: 50px'>
            <div class="logo">
                <img src="logopref.png" alt="Logo">
                <!-- <img src="../assets/img/pdf/logo.png" alt="Logo"> -->
            </div>
            <div class="location">
            </div>
            <div class="hora">
               <img src="logopoli.png" width='150'>
            </div>
        </div>
        <div class="main">
            <div class="chamadas">
                <h2>Chamadas</h2>
                <div id="chamandoAtualmente"></div>
            </div>
            <div class="historico" id="historico">
                <h2>Histórico</h2>
                <ul id="historicoChamadas">

                </ul>
            </div>
        </div>
    </div>
</body>
<script src="assets/vendor/swiper/swiper-bundle.min.js"></script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/vendor/glightbox/js/glightbox.min.js"></script>
<script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>

<script src="https://code.responsivevoice.org/responsivevoice.js?key=bXmFnRNP"></script>
<script src="https://www.youtube.com/iframe_api"></script>

<script>
    var linkdoPainel = window.location.href;
    var qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + encodeURIComponent(linkdoPainel);
    document.getElementById("qrcode").src = qrCodeUrl;
    isFullScreen = false;
    var elem = document.documentElement;

    function AtivarDesativarFS() {
        if (document.exitFullscreen) {
            document.exitFullscreen();
            isFullScreen = false;
        } else if (document.mozCancelFullScreen) {
            /* Firefox */
            document.mozCancelFullScreen();
            isFullScreen = false;
        } else if (document.webkitExitFullscreen) {
            /* Chrome, Safari & Opera */
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            /* IE/Edge */
            document.msExitFullscreen();
            isFullScreen = false;
        }
        if (elem.requestFullscreen) {
            elem.requestFullscreen();
            isFullScreen = true;
        } else if (elem.mozRequestFullScreen) {
            /* Firefox */
            elem.mozRequestFullScreen();
            isFullScreen = true;
        } else if (elem.webkitRequestFullscreen) {
            /* Chrome, Safari & Opera */
            elem.webkitRequestFullscreen();
            isFullScreen = true;
        } else if (elem.msRequestFullscreen) {
            /* IE/Edge */
            elem.msRequestFullscreen();
            isFullScreen = true;
        }

    }
    document.addEventListener('DOMContentLoaded', (event) => {
        document.body.addEventListener('click', AtivarDesativarFS);
    });
</script>

<script>
    function myFunction() {
        var x = document.getElementById("navDemo");
        if (x.className.indexOf("w3-show") == -1) {
            x.className += " w3-show";
        } else {
            x.className = x.className.replace(" w3-show", "");
        }
    }
</script>
<script>
    document.addEventListener('DOMContentLoaded', (event) => {
        document.body.addEventListener('click', enableAudio);
    });

    document.addEventListener('DOMContentLoaded', (event) => {
        document.body.addEventListener('click', () => {
            const bip = new Audio('assets/bip.mp3');
            bip.play().then(() => {

                document.body.removeEventListener('click', enableAudio);
            }).catch(error => {
                console.log('Erro ao reproduzir áudio:', error);
            });
        });
    });

    function enableAudio() {

    }


    function updateDataHora() {
        var now = new Date();
        var data = now.toLocaleDateString('pt-BR', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric'
        });
        var hora = now.toLocaleTimeString('pt-BR', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });
        //document.getElementById('dataHora').innerHTML = `${hora}`;
    }

    setInterval(updateDataHora, 1000);
    updateDataHora();
    let player;

    function onYouTubeIframeAPIReady() {
        player = new YT.Player('ytplayer', {
            events: {
                'onReady': onPlayerReady
            }
        });
    }

    function onPlayerReady(event) {
        event.target.mute();
    }
    let filaDeChamadas = [];
    let pacientesChamados = [];
    let pacienteAtual = null;

    const urlParams = new URLSearchParams(window.location.search);
    const CNES = urlParams.get('CNES')?.toUpperCase();
    const idPainel = urlParams.get('PAINEL')?.toUpperCase();



    if (!CNES) {

    }

    const socket = new WebSocket('<?php echo $ws_url; ?>');

    socket.onopen = function() {
        socket.send(JSON.stringify({ CNES, idPainel }));


    };

    socket.onmessage = function(event) {
        console.log('Mensagem recebida (JSON):', event.data);
        const data = JSON.parse(event.data);
        console.log('Objeto parseado:', data);
        atualizarPainel(data);

    };

    socket.onerror = function(error) {

    };

    function falar(mensagem) {
        if (speechSynthesis.speaking) {
            return;
        }


        const bip = new Audio('assets/bip.mp3');
        bip.play().then(() => {

            responsiveVoice.speak(mensagem, "Brazilian Portuguese Male", {
                rate: 1.0,
                onend: () => {
                    processarFilaDeChamadas();
                }
            });
        }).catch(error => {
            console.error('Erro ao tocar o bip', error);
        });
    }




    function exibirPacientesEmAtendimento(pacientes) {
        const chamandoAtualmente = document.getElementById('chamandoAtualmente');
        chamandoAtualmente.innerHTML = '';

        pacientes.slice(0, 4).forEach(paciente => {
            const nomePaciente = paciente.nome_paciente;
            const nomeProf = paciente.profissional;
            const sala = paciente.sala.replace("AO","");

            chamandoAtualmente.innerHTML += `
        <div class="chamadas-info">
            <div id="${nomePaciente}" class="paciente-chamado">
                <p style='font-size:35pt !important'>${nomePaciente}</p>
                <div class="status" style='font-size:22pt !important'>&bull; ${sala} &bull;</div>
            </div>
             </div>
        `;
        });
    }

    let contadorChamadas = {};

    function processarFilaDeChamadas() {
        if (filaDeChamadas.length > 0 && !speechSynthesis.speaking) {
            const paciente = filaDeChamadas[0];
            const chave = paciente.dt_ultima_alteracao_status;

            const chamadas = contadorChamadas[chave] || 0;

            if (chamadas < 2) {
                falar(`Paciente ${paciente.nomePaciente}, favor se dirigir ${paciente.sala}.`);
                contadorChamadas[chave] = chamadas + 1;
            }

            if (contadorChamadas[chave] >= 2) {
                filaDeChamadas.shift();
                pacientesChamados.push(paciente);
            }
        }
    }



    function atualizarPainel(data) {
        //const listaAguardando = document.getElementById('listaAguardando');
        const historicoChamadas = document.getElementById('historicoChamadas');
        const historico = document.getElementById('historico');
        const chamandoAtualmente = document.getElementById('chamandoAtualmente');

        chamandoAtualmente.innerHTML = '';
        //listaAguardando.innerHTML = '';
        historicoChamadas.innerHTML = '';


        if (data.em_atendimento.length > 0) {



            data.em_atendimento.forEach(paciente => {
                const nomePaciente = paciente.nome_paciente;
                const nomeProf = paciente.profissional;
                const sala = paciente.sala;
                const dt_ultima_alteracao_status = paciente.dt_ultima_alteracao_status;
                filaDeChamadas.push({
                    nomePaciente,
                    nomeProf,
                    sala,
                    dt_ultima_alteracao_status
                });
            });


            exibirPacientesEmAtendimento(data.em_atendimento);
        }

        /*data.aguardando_atendimento.slice(0, 5).forEach(paciente => {
            listaAguardando.innerHTML += `
            <li>
                <div class="icon icon-person"><i class="fas fa-user"></i></div>
                <div class="doutor">${paciente.nome_paciente}</div>
            </li>
        `;
        });*/


        data.atendido.slice(0, 3).forEach(paciente => {

            const nome_setoratendimento = paciente.nome_setoratendimento;
            historicoChamadas.innerHTML += `
            <li>
                <div class="doutor" style='color:#fff; width:400px !important'>
                  <i class="fas fa-history" style='color:#fff; font-size:14pt'></i>&nbsp;&nbsp;<font  style='font-size:14pt'>&bull; ${paciente.nome_paciente}</font>
                </div>
                <div class="sala" style='color:#fff; font-size:14pt'>&bull; ${nome_setoratendimento}</div>               
            </li>
        `;
        });
        let pacientesAguardando = data.aguardando_atendimento.length;
        let marginTopValue;

        if (pacientesAguardando >= 5) {
            marginTopValue = "-230px";
        } else if (pacientesAguardando = 0) {
            marginTopValue = "-150px";
        } else {

            marginTopValue = `${-150 - (pacientesAguardando - 1) * 30}px`;
        }
        //historico.style.marginTop = marginTopValue;

        processarFilaDeChamadas();
    }
</script>

</body>

</html>