<?php
require '../conexao/conexao.php';
require '../conexao/acesso.php';
require '../configuacoes.php';

$pageTitle = "Detalhar Médico";

//Declarado as variáveis que serão usadas para edição.
$pessoa = array(
    'NOMEMED' => 'N/A',
    'CRM_CONCAT' => 'N/A',
    'PARAMETRO' => 'N/A',
    'VISITADOR' => 'N/A'
    // ... outros campos que você pode ter ...
);
$dataFormatada = 'N/A';

$idPessoa = $_GET['id_medico'];
$DataInicial = $_GET['dtinicial'] ?? null;
$DataFinal = $_GET['dtfinal'] ?? null;
$filial = $_GET['filial'] ?? null;
$Visitador = $_GET['visitador'] ?? null;
$tabela = $_GET['tabela'] ?? null;

// Ajustando a consulta para Firebird
if (!empty($idPessoa) && !empty($DataInicial) && !empty($DataFinal) && !empty($filial)) {

    $query = "SELECT
    ME.NOMEMEDICO AS NOMEMED,
    ESPEC.NOMEESPECIALIDADE AS PARAMETRO,
    CR.SIGLA || '-' || ME.CR_ESTADO || '-' || ME.CRM AS CRM,
    MIN(RP.NOMEFUNCIONARIO) AS VISITADOR,
    MIN(CAST(A1.CADASTRO_DT AS DATE)) AS DATA_CADASTRO
FROM ATENDIMENTO_A1 A1
INNER JOIN MEDICO ME ON ME.CODIGO = A1.CODIGO_MEDICO
LEFT JOIN MEDICO_CR CR ON ME.CODIGO_CONSELHO_REGIONAL = CR.CODIGO
LEFT JOIN MEDICO_ESPECIALIDADE ESPEC ON ESPEC.CODIGO = ME.CODIGO_MEDICO_ESPECIALIDADE
LEFT JOIN MEDICO_REPRESENTANTE MR ON ME.CODIGO = MR.CODIGO_MEDICO
LEFT JOIN FUNCIONARIO RP ON MR.CODIGO_FUNCIONARIO = RP.CODIGO
WHERE A1.TIPO_ATENDIMENTO = 1
AND CAST(A1.CADASTRO_DT AS DATE) BETWEEN '$DataInicial' AND '$DataFinal'";

if (isset($_GET['visitador']) && $_GET['visitador'] <> '') {
    $query .= " AND MR.CODIGO_FUNCIONARIO = '$Visitador'";
}

$query .= " AND (CR.SIGLA || '-' || ME.CR_ESTADO || '-' || ME.CRM) = '$idPessoa' ";

if (!empty($filial) && $filial <> 'Todos') {
    $query .= " AND A1.CADASTRO_LJ IN ('$filial')";
}

$query .= " GROUP BY
ME.NOMEMEDICO,
ESPEC.NOMEESPECIALIDADE,
CR.SIGLA,
ME.CR_ESTADO,
ME.CRM";

    // Preparando a consulta
    $stmt = ibase_prepare($connection, $query);

    // Executando a consulta
    $result = ibase_execute($stmt);

    // Verificando se a consulta foi executada corretamente
    if (!$result) {
        die('Erro na execução da consulta: ' . ibase_errmsg());
    }

    // Inicializando o array para armazenar os resultados
    $pessoa = [];

    // Buscando os dados e armazenando no array
    while ($row = ibase_fetch_assoc($result)) {
        $pessoa[] = $row;
    }

    //print_r($pessoa);exit;

    $dataFormatada = date('d/m/Y', strtotime($pessoa[0]['DATA_CADASTRO']));
}
?>

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

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">
                            <?php echo $pageTitle; ?>
                        </h4>
                    </div>
                    <div class="col-6 text-right">
                        <button onclick="goBack()" class="btn btn-light"><i class="mdi mdi-keyboard-backspace"></i> Voltar</button>
                    </div>
                    <div class="col-12">
                        <hr>
                    </div>
                    <div class="col-12">
                        <form method="post" action="" onsubmit="return validarFormulario();">
                            <div class="form-row mb-3">
                                <!-- Campos para pessoa física -->

                                <div class="form-group col-md-3 pessoa-fisica">
                                    <p><b>Nome:</b> <?php echo htmlspecialchars($pessoa[0]['NOMEMED'], ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>
                                <div class="form-group col-md-3 pessoa-fisica">
                                    <p><b>CRM:</b> <?php echo htmlspecialchars($pessoa[0]['CRM'], ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>
                                <div class="form-group col-md-3 pessoa-fisica">
                                    <p><b>ESPECIALIDADE:</b> <?php echo htmlspecialchars($pessoa[0]['PARAMETRO'], ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>
                                <div class="form-group col-md-3 pessoa-fisica">
                                    <p><b>VISITADOR:</b> <?php echo htmlspecialchars($pessoa[0]['VISITADOR'], ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>

                                <div class="form-group col-md-3 pessoa-fisica">
                                    <p><b>DATA DE CADASTRO:</b> <?php echo htmlspecialchars($dataFormatada, ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>

                                <div class="col-12">
                                    <h6>Tabela de Orçamentos por Médicos</h6>
                                    <nav>
                                        <ul class="nav nav-tabs" id="myTab" role="tablist">
                                            <li class="nav-item">
                                                <a class="nav-link <?php echo (!$tabela || $tabela == '1') ? 'active' : ''; ?>" id="aprovado-tab" data-toggle="tab" href="#aprovado" role="tab" aria-controls="aprovado" aria-selected="<?php echo (!$tabela || $tabela == '1') ? 'true' : 'false'; ?>" onclick="updateURL('1')">Aprovado</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link <?php echo ($tabela == '2') ? 'active' : ''; ?>" id="reprovado-tab" data-toggle="tab" href="#reprovado" role="tab" aria-controls="reprovado" aria-selected="<?php echo ($tabela == '2') ? 'true' : 'false'; ?>" onclick="updateURL('2')">Reprovado</a>
                                            </li>
                                        </ul>
                                    </nav>
                                    <div class="tab-content" id="myTabContent">
                                        <div class="tab-pane fade <?php echo (!$tabela || $tabela == '1') ? 'show active' : ''; ?>" id="aprovado" role="tabpanel" aria-labelledby="aprovado-tab">
                                            <?php
                                            $tabela = '1';
                                            include('table-aprovado-reprovado.php');
                                            ?>
                                        </div>
                                        <div class="tab-pane fade <?php echo ($tabela == '2') ? 'show active' : ''; ?>" id="reprovado" role="tabpanel" aria-labelledby="reprovado-tab">
                                            <?php
                                            $tabela = '2';
                                            include('table-aprovado-reprovado.php');
                                            ?>
                                        </div>
                                    </div>
                                </div>
                        </form>

                    </div>
                </div>
            </div>
        </div> <!-- end container -->
    </div>

    <!-- end wrapper -->

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

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

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

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- Outros scripts -->
    <script src="../../assets/js/funcoes.js"></script>
    <script src="../../assets/js/vendor.min.js"></script>
    <script src="../../assets/libs/jquery-knob/jquery.knob.min.js"></script>
    <script src="../../assets/js/app.min.js"></script>
    <script src="../geral/javascript.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">

</body>

</html>

<script>
    function goBack() {
        window.history.back();
    }
</script>

<script>
    $(document).ready(function() {

        $('#minhaTabela1').DataTable({
            "language": {
                "url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json"
            },
            "order": [
                [2, "desc"]
            ],
            "ordering": true,
            "lengthMenu": [
                [10, 25, 50, 100, -1],
                [10, 25, 50, 100, "Todos"]
            ],
            "buttons": [
                'excelHtml5'
            ],


            //   //"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>>',
        });

        $('#minhaTabela2').DataTable({
            "language": {
                "url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json"
            },
            "order": [
                [2, "desc"]
            ],
            "ordering": true,
            "lengthMenu": [
                [10, 25, 50, 100, -1],
                [10, 25, 50, 100, "Todos"]
            ],
            "buttons": [
                'excelHtml5'
            ],


            //   //"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>>',
        });
    });

    function updateURL(tabela) {
        let url = new URL(window.location.href);
        url.searchParams.set('tabela', tabela);
        window.history.pushState({}, '', url);
    }
</script>
<style>
    #minhaTabela1_length label,
    #minhaTabela1_info {
        margin: 0 !important;
        padding: 0 !important;
        align-items: center;
    }
    #minhaTabela2_length label,
    #minhaTabela2_info {
        margin: 0 !important;
        padding: 0 !important;
        align-items: center;
    }
</style>

<script>

</script>