<?php
require '../conexao/conexao.php';
require '../conexao/acesso.php';
require '../configuacoes.php';
require '../configuracao/consulta_banco_dados.php';
require_once '../querys/query-logs.php';
require '../configuracao/filtros.php';

$filtrosSistema = new Filtros();
$queryLogs = new QueryLogs($connectionmysql);

$modulos = $queryLogs->getModulos();

$DataInicial = $_GET['DataInicial'] ?? null;
$DataFinal = $_GET['DataFinal'] ?? null;
$modulo = $_GET['modulo'] ?? null;
$nome_usuario = $_GET['nome_usuario'] ?? null;
$modulo = $_GET['modulos'] ?? null;

$modulo = $modulo ? implode(',', array_map(function ($item) {
    return "'" . addslashes(trim($item)) . "'";
}, explode(',', $modulo))) : 'NULL';

$filtros = [
    'data_inicial' => isset($_GET['data_inicial']) ? $_GET['data_inicial'] : date('Y-m-d', strtotime('-30 days')),
    'data_final' => isset($_GET['data_final']) ? $_GET['data_final'] : date('Y-m-d'),
    'modulo' => $modulo,
];

$query_params = [
    'data_inicial' => $_GET['data_inicial'] ?? '',
    'data_final'   => $_GET['data_final'] ?? '',
    'modulo'       => $_GET['modulo'] ?? '',
];
$query_string = http_build_query($query_params);

$logs = $queryLogs->LogsAcessados($query_params);

?>

<style>
    .dataTables_length,
    .dataTables_filter {
        margin-bottom: 0 !important;
    }

    .dataTables_info {
        padding-top: 10px;
    }

    .dataTables_paginate {
        padding-top: 10px;
    }
</style>

<style>
    div.dataTables_wrapper div.dataTables_length {
        padding-top: 10px;
    }
</style>

<style>
    /* Garante alinhamento bonito e espaçamento */
    div.dataTables_wrapper div.dataTables_length,
    div.dataTables_wrapper div.dataTables_info,
    div.dataTables_wrapper div.dataTables_paginate {
        margin: 0 !important;
        padding: 0 !important;
    }

    div.dataTables_wrapper .text-center {
        margin-left: 447px !important;
    }

    div.dataTables_wrapper .text-end {
        text-align: right !important;
    }
</style>

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

<?php
$pageTitle = "Ranking de Acesso";
include('../geral/header.php');
?>

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

    <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">Ranking de Acessos</h4>
                    </div>
                    <div class="col-6 text-right">
                        <a href="index.php" class="btn btn-light">
                            <i class="mdi mdi-keyboard-backspace"></i> Voltar
                        </a>
                    </div>
                    <div class="col-12">
                        <form method="get" action="geral_acessados.php" id="geralForm" onsubmit="return validarFormulario()">
                            <div class="form-row mb-3">
                                <div class="form-group col-md-3">
                                    <label>Data Inicial</label>
                                    <input type="date" name="data_inicial" class="form-control"
                                        value="<?= $filtros['data_inicial'] ?>">
                                </div>
                                <div class="form-group col-md-3">
                                    <label>Data Final</label>
                                    <input type="date" name="data_final" class="form-control"
                                        value="<?= $filtros['data_final'] ?>">
                                </div>
                                <?php
                                echo $filtrosSistema->filtroCheckBox('modulos', $modulos);
                                ?>
                            </div>

                            <input type="hidden" name="pesquisar" value="1" />
                            <div class="col-12 text-right" style="margin-top: -70px;">
                                <a href="geral_acessados.php" class="btn btn-warning mr-2"><i class="mdi mdi-plus"></i> Limpar</a>
                                <button type="submit" class="btn btn-primary"><i class="mdi mdi-magnify"></i> Pesquisar</button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="col-12">
                    <h6>Lista de Acessos</h6>
                    <?php if (isset($_GET['pesquisar']) && $_GET['pesquisar'] == '1') { ?>
                        <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap">
                            <thead>
                                <tr class="text-center">
                                    <th>Módulos</th>
                                    <th>Total de Acessos</th>
                                    <th>Data dos Acessos</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($logs)) { ?>
                                    <?php foreach ($logs as $log) { ?>
                                        <tr class="linha-modulo" style="cursor: pointer;" data-modulo-id="<?= $log['modulo'] ?>">
                                            <td class="text-center"><?= htmlspecialchars($log['modulo'] . ' - ' . $log['descricao_modulo']); ?></td>
                                            <td class="text-center"><?= $log['total_acessos']; ?></td>
                                            <td class="text-center"><?= date('d/m/Y', strtotime($log['ultima_data_acesso'])); ?></td>
                                        </tr>
                                    <?php } ?>
                                <?php } else { ?>
                                    <tr>
                                        <td colspan="5">Nenhum dado encontrado.</td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal de Detalhes -->
    <div class="modal fade" id="modalDetalhes" tabindex="-1" aria-labelledby="modalDetalhesLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalDetalhesLabel">Acessos por Usuários</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Usuários</th>
                                <th>Total de Acessos</th>
                            </tr>
                        </thead>
                        <tbody id="tabelaUsuarios">
                            <!-- Dados serão carregados aqui via AJAX -->
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 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>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- third party js -->
    <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>
        $(document).ready(function() {
            initDropdownFilter('modulos', false);
            var table = $('#datatable-buttons').DataTable({
                language: {
                    url: "https://cdn.datatables.net/plug-ins/1.13.6/i18n/pt-BR.json"
                },
                lengthMenu: [
                    [10, 25, 50, 100, -1],
                    [10, 25, 50, 100, "Todos"]
                ],
                buttons: [
                    'excelHtml5',
                    'csvHtml5'
                ],
                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>>',
                order: [
                    [0, 'asc']
                ],
                columnDefs: [{
                    targets: 0,
                    orderable: true
                }],
            });
        });
    </script>
    <style>
        .drop {
            margin-top: -8px;
            /* ou o valor que preferir */
        }
    </style>

    <script>
        $(document).ready(function() {
            $('.linha-modulo').on('click', function() {
                const moduloId = $(this).data('modulo-id');
                const dataInicial = $('input[name="data_inicial"]').val();
                const dataFinal = $('input[name="data_final"]').val();

                $.get('acessos_usuario.php', {
                    modulo: moduloId,
                    data_inicial: dataInicial,
                    data_final: dataFinal
                }, function(dados) {
                    let html = '';
                    if (dados && Array.isArray(dados) && dados.length > 0) {
                        dados.forEach(row => {
                            html += `<tr><td>${row.nome_usuario}</td><td>${row.total_acessos}</td></tr>`;
                        });
                    } else {
                        html = '<tr><td colspan="2">Nenhum acesso encontrado</td></tr>';
                    }

                    $('#tabelaUsuarios').html(html);
                    const modal = new bootstrap.Modal(document.getElementById('modalDetalhes'));
                    modal.show();
                }, 'json');
            });
        });
    </script>

</body>

</html>