<?php
require '../conexao/conexao.php';
//require '../sessao.php';
require '../conexao/acesso.php';
require '../configuacoes.php';
require '../configuracao/consulta_banco_dados.php';
require '../configuracao/filtros.php';
require '../configuracao/get_config.php';
require 'consulta_bd.php';
require '../logs/gera-log.php';

gerarLog(
    1, // tipo de log (acesso)
    $basePath, // módulo
    $_SESSION['CodUsuario'],
    $_SESSION['NomeUsuario']
);

$resultmeta = null;

// Instancia a classe de consulta_bb ao banco de dados
$consulta_bb = new ConsultaBancoDeDados();
$consulta_medico = new ConsultasMedicoAitorizacao();
$configuracao = new Configuracoes();
$filtros = new Filtros();
$medicos_index = $consulta_medico->get_medicos_index();
$medicos = $consulta_medico->get_medicos($medicos_index);
$medico = $_GET['medicos'] ?? null;


$url = http_build_query([
    'medicosbox' => $medico,
    'form_submitted' => isset($_GET['form_submitted']) ? $_GET['form_submitted'] : '',
]);

if (isset($_GET['form_submitted']) && $_GET['form_submitted'] == '1') {

    gerarLog(
        5, // tipo de log (acesso)
        $basePath, // módulo
        $_SESSION['CodUsuario'],
        $_SESSION['NomeUsuario']
    );

    if (!empty($medico) && $medico !== 'Todos') {
        $medicosautorizacoes = $consulta_medico->get_medicos($medico);
    } else {
        $medicosautorizacoes = $consulta_medico->get_medicos($medicos_index);
    }
}

?>

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

<head>
    <link rel="stylesheet" href="../configuracao/modalexcluir.css">
</head>
<?php
$pageTitle = "Médico Autorizações";
include('../geral/header.php');
?>

<body>

    <!-- Navigation Bar-->
    <?php
    include('../geral/menu.php');
    ?>
    <!-- End Navigation Bar-->

    <!-- ============================================================== -->
    <!-- Start Page Content here -->
    <!-- ============================================================== -->

    <div class="wrapper candidato">
        <div class="container-fluid">
            <div class="card-box mt-3">
                <div class="row">
                    <div class="col-6 text-left">
                        <h4 class="page-title">Médico Autorizações</h4>
                    </div>

                    <div class="col-6 text-right">
                        <a href="formulario_inclusao_autorizacoes.php?id=0&<?= $url ?>" class="btn btn-light" alt="Incluir Autorização" title="Incluir Autorização"><i class="mdi mdi-plus"></i> Adicionar </a>
                    </div>

                    <div class="col-12">
                        <hr>
                    </div>

                    <div class="col-12">
                        <form method="get" action="">
                            <div class="form-row mb-1">
                                <?php
                                echo $filtros->filtroCheckBox('medicos', $medicos, null, false, false, 'médicos'); ?>
                                <input type="hidden" name="form_submitted" value="1" />
                                <div class="col-6 col-md-8 col-lg-10 d-flex mt-0" style="align-items:center;justify-content: end;">
                                    <div>
                                        <a href="index.php" class="btn btn-warning mr-2"><i class="mdi mdi-plus"></i> Limpar</a>
                                    </div>
                                    <div>
                                        <button type="submit" class="btn btn-primary"><i class="mdi mdi-magnify"></i> Pesquisar</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>

                </div>

                <?php
                //VERIFICANDO SE O USUÁRIO CLICOU NO BOTÃO PESQUISAR
                if (isset($_GET['form_submitted']) && $_GET['form_submitted'] == '1') { ?>
                    <div class="col-12">
                        <div class="mb-2" style="display: flex; justify-content: space-between; align-items: center; ">
                            <h6>Lista de Médicos</h6>
                        </div>
                        <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap">
                            <thead>
                                <tr class="text-center">
                                    <th class="text-center">Nome Médico</th>
                                    <th class="text-center">CRM Médico</th>
                                    <th class="text-center">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $hasResults = false;  // Inicializa como false

                                if (!empty($medicosautorizacoes)) {
                                    foreach ($medicosautorizacoes as $row) {
                                        $hasResults = true; // Define como verdadeiro quando encontrar algum resultado
                                        $nome_medico = $row['NOME'];
                                        $crm = $row['ID'];
                                ?>
                                        <tr class="text-center">
                                            <td><?= htmlspecialchars($nome_medico) ?></td>
                                            <td><?= htmlspecialchars($crm) ?></td>
                                            <td>
                                                <a href="detalhar_autorizacoes.php?crm_medico=<?php echo $crm; ?> &nome_medico=<?php echo $nome_medico; ?>&<?php echo $url; ?>" class="table-actions link-view" title="Detalhar Autorizações"><i class="mdi mdi-account-details"></i></a>
                                                <a href="formulario_inclusao_autorizacoes.php?&medicos=<?php echo $crm; ?>&<?php echo $url; ?>" class="table-actions link-view" title="Detalhar Autorizações"><i class="mdi mdi-pencil"></i></a>
                                            </td>
                                        </tr>
                                <?php
                                    }
                                }
                                if (!$hasResults) {
                                    echo "<tr><td colspan='3' class='text-center'>Sem resultado para a consulta</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
            </div>
        <?php } //fechamento do IF que valida se o usuário clicou no botão pesquisar 
        ?>
        </div>
    </div>


    <!-- FINAL MODAL DE EXCLUIR -->

    <!-- end wrapper -->

    <!-- ============================================================== -->
    <!-- End Page content -->
    <!-- ============================================================== -->

    <!-- Footer Start -->
    <?php
    include('../geral/footer.php');
    ?>
    <!-- end Footer -->

    <?php
    include('../geral/mensagens_modais.php');
    ?>

    <!-- Vendor js -->
    <script src="../../assets/js/vendor.min.js"></script>

    <!-- knob plugin -->
    <script src="../../assets/libs/jquery-knob/jquery.knob.min.js"></script>
    <!-- App js-->
    <script src="../../assets/js/app.min.js"></script>
    <script src="../geral/javascript.js"></script>
    <script src="../../assets/js/funcoes.js"></script>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/dataTables.bootstrap5.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/dataTables.bootstrap5.min.css">

    <script src="https://cdn.datatables.net/buttons/2.0.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.0.1/js/buttons.html5.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.0.1/css/buttons.dataTables.min.css">
    <link rel="stylesheet" href="../../assets/css/resetedatatable.css">


    <script>
        initDropdownFilter('medicos', false);

        $(document).ready(function() {
            var table = $('#datatable-buttons').DataTable({
                "language": {
                    "url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json"
                },
                "lengthMenu": [
                    [10, 25, 50, 100, -1],
                    [10, 25, 50, 100, "Todos"]
                ],
                "buttons": [
                    //'copyHtml5',
                    'excelHtml5',
                    //'csvHtml5',
                    'pdfHtml5'
                ],


                //    //"dom": 'lBfrtip',
                dom: '<"d-flex justify-content-between align-items-center mb-2"Bf>t<"datatable-footer d-flex justify-content-between align-items-center mt-2 w-100"<"footer-left"l><"footer-center"i><"footer-right"p>>',
            });


        });

        document.addEventListener("DOMContentLoaded", function() {
            setTimeout(function() {
                $("#datatable-buttons_filter").children("label").css("font-size", "15px");
            }, 50);
            setTimeout(function() {
                $("#datatable-buttons_length").children("label").css("font-size", "15px");
            }, 50);
            // Remove status and message parameters from URL
            const url = new URL(window.location);
            url.searchParams.delete('status');
            url.searchParams.delete('message');
            window.history.replaceState({}, document.title, url);
        });
    </script>
    <style>
        #datatable-buttons_length label,
        #datatable-buttons_info {
            margin: 0 !important;
            padding: 0 !important;
            align-items: center;
        }
    </style>
</body>

</html>