<?php
require '../../conexao/conexao.php';
//require '../sessao.php';
require '../../configuacoes.php';
require '../../conexao/acesso.php';
require './consulta_bd.php';
require '../../configuracao/filtros.php';
$resultmeta = null;

// Instancia a classe de consulta_bb ao banco de dados
$filtros = new Filtros();
$consulta_pcp = new ConsultaOperacao();

$id_configuracao = $consulta_pcp->get_configuracao();
$id_configuracao = $id_configuracao[0]['id_configuracoes'];
$operacoes_cadastradas = $consulta_pcp->get_operacoes_em_uso();
$valores = [];

foreach ($operacoes_cadastradas as $row) {
    $valores = array_merge($valores, explode(',', $row['valor']));
}

$operacoes_string = implode(',', array_map('trim', $valores));

$valores = array_merge($operacoes_cadastradas, explode(',', $row['valor']));

$operacoes_selecionado = $_GET['operacoes'] ?? null;
$tabela = $_GET['tabela'] ?? 'ativo';

$operacoes = $consulta_pcp->get_operacoes($operacoes_string, false);
$operacoes_filtro = $consulta_pcp->get_operacoes($operacoes_string, false);

//var_dump($operacoes, $operacoes_filtro);

if ($tabela == 'ativo') {
    $operacoes = $consulta_pcp->get_operacoes($operacoes_string);
    $operacoes_filtro = $consulta_pcp->get_operacoes($operacoes_string);
} elseif ($tabela == 'inativo') {
    $operacoes = $consulta_pcp->get_operacoes($operacoes_string, false);
    $operacoes_filtro = $consulta_pcp->get_operacoes($operacoes_string, false);
}
//var_dump($id_configuracao);

$query_string = http_build_query([
    'operacoes' => $operacoes_selecionado,
    'form_submitted' => '1'
]);

?>

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

<?php
$pageTitle = "Configuração Operações"; // Definir o título da página aqui
include('../header.php');
include('../menu.php');
?>

<head>
    <link rel="icon" href="\KPI\pages/configuracoes/logo-sm.png">
    <link rel="shortcut icon" href="\KPI\pages/configuracoes/logo-sm.png">
</head>

<body>


    <!-- ============================================================== -->
    <!-- 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"><?= $pageTitle; ?></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>
                    <?php if ($tabela == 'ativo') { ?>
                        <div class="col-6 text-left mt-4">
                            <p class="page-title"><b>Essas operações estão ativadas no sistema. Marque as operações que deseja desativar.</b></p>
                        </div>
                    <?php } elseif ($tabela == 'inativo') { ?>
                        <div class="col-6 text-left mt-4">
                            <p class="page-title"><b>Essas operações estão desativadas para consultas no sistema. Marque as operações que deseja ativar.</b></p>
                        </div>
                    <?php } ?>


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

                <form action="processa_operacao.php" method="post">
                    <div class="row col-12">
                        <?php echo $filtros->filtroCheckBox('operacoes', $operacoes_filtro, $operacoes_selecionado, false, false, 'operações'); ?>
                        <div class="col-6 col-md-8 col-lg-10 mt-0 d-flex " style="align-items:center;justify-content: end;">
                            <button type="submit" class="btn btn-primary"><i class="mdi mdi-magnify"></i> Salvar</button>
                        </div>
                    </div>
                    <input type="hidden" name="id_configuracao" value="<?= $id_configuracao ?>" />
                    <input type="hidden" name="URL" value="<?= $query_string ?>" />

                    <?php if ($tabela == 'ativo') { ?>
                        <input type="hidden" name="ativo" value="1" />
                    <?php  } elseif ($tabela == 'inativo') { ?>
                        <input type="hidden" name="inativo" value="1" />
                    <?php  } ?>
                </form>

                <div class="col-12">
                    <nav class="mb-2 mt-2">
                        <ul class="nav nav-tabs" id="myTab" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link <?php echo ($tabela == 'ativo') ? 'active' : ''; ?>" id="ativo-tab" data-toggle="tab" href="#ativo" role="tab" aria-controls="ativo" aria-selected="<?php echo ($tabela == 'ativo') ? 'true' : 'false'; ?>" onclick="updateURL('ativo')">Ativos</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo ($tabela == 'inativo') ? 'active' : ''; ?>" id="inativo-tab" data-toggle="tab" href="#inativo" role="tab" aria-controls="inativo" aria-selected="<?php echo ($tabela == 'inativo') ? 'true' : 'false'; ?>" onclick="updateURL('inativo')">Desativados</a>
                            </li>
                        </ul>
                    </nav>
                </div>



                <div class="tab-content" id="myTabContent">
                    <?php if ($tabela == 'ativo') { ?>
                        <div class="tab-pane fade show active" id="ativo" role="tabpanel" aria-labelledby="ativoativo-tab">
                            <div style="display: flex; justify-content: space-between; align-items: center; " class="mb-3">
                                <h6>Tabela de Operacões Ativas</h6>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="per-page-selector">
                                    <select id="per-page-select">
                                        <option value="10">10</option>
                                        <option value="25">25</option>
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                    </select>
                                    <span>registros por página</span>
                                </div>
                                <div>
                                    <input type="text" id="pesquisa" class="form-control" placeholder="Pesquisar" style="width: 200px;">
                                </div>
                            </div>
                            <br>
                            <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap">
                                <thead>
                                    <tr class="text-center">
                                        <th>Cod</th>
                                        <th>Nome</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $hasResults = false;
                                    if ($operacoes) {
                                        foreach ($operacoes as $row) {
                                            $hasResults = true;   ?>
                                            <tr class="text-center">
                                                <td class="col-3"><?php echo htmlspecialchars($row['ID']); ?></td>
                                                <td class="col-3"><?php echo htmlspecialchars($row['NOME']); ?></td>
                                            </tr>
                                    <?php
                                        }
                                    }

                                    if (!$hasResults) {
                                        echo "<tr><td colspan='3' class='text-center'>Sem resultado para a consulta</td></tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    <?php } elseif ($tabela == 'inativo') { ?>
                        <div class="tab-pane fade show active" id="inativo" role="tabpanel" aria-labelledby="inativo-tab">
                            <div style="display: flex; justify-content: space-between; align-items: center; " class="mb-3">
                                <h6>Tabela de Operacões Desativadas</h6>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="per-page-selector">
                                    <select id="per-page-select">
                                        <option value="10">10</option>
                                        <option value="25">25</option>
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                    </select>
                                    <span>registros por página</span>
                                </div>
                                <div>
                                    <input type="text" id="pesquisa" class="form-control" placeholder="Pesquisar" style="width: 200px;">
                                </div>
                            </div>
                            <br>
                            <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap">
                                <thead>
                                    <tr class="text-center">
                                        <th>Cod</th>
                                        <th>Nome</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $hasResults = false;
                                    if ($operacoes) {
                                        foreach ($operacoes as $row) {
                                            $hasResults = true;   ?>
                                            <tr class="text-center">
                                                <td class="col-3"><?php echo htmlspecialchars($row['ID']); ?></td>
                                                <td class="col-3"><?php echo htmlspecialchars($row['NOME']); ?></td>
                                            </tr>
                                    <?php }
                                    }
                                    if (!$hasResults) {
                                        echo "<tr><td colspan='3' class='text-center'>Sem resultado para a consulta</td></tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    <?php } ?>
                    <div class="pagination-container">
                        <div class="pagination-info">
                            <span id="pagination-info"></span>
                        </div>
                        <div class="pagination-controls">
                            <button id="prev-page" style="background: #fff; margin-right: 10px;" class="paginate_button page-item previous disabled">Anterior</button>
                            <span id="page-numbers"></span>
                            <button id="next-page" style="background: #fff; margin-left: 10px;" class="paginate_button page-item next">Próxima</button>
                        </div>
                    </div>


                    <style>
                        .pagination-container {
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                            margin-top: 20px;
                            padding: 10px;
                            background-color: #fff;
                            border-radius: 5px;
                        }

                        .pagination-controls {
                            display: flex;
                            gap: 5px;
                            align-items: center;
                        }

                        .pagination-controls button {
                            padding: 5px 10px;
                        }

                        .page-number {
                            padding: 5px 10px;
                            margin: 0 2px;
                            cursor: pointer;
                            border-radius: 3px;
                        }

                        .page-number.active {
                            background-color: #007bff;
                            color: white;
                        }

                        .per-page-selector {
                            display: flex;
                            align-items: center;
                            gap: 10px;
                        }

                        #per-page-select {
                            padding: 5px;
                            border-radius: 3px;
                        }
                    </style>
                </div>
            </div>
        </div>
    </div>


    <!-- FINAL MODAL DE EXCLUIR -->

    <!-- end wrapper -->

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

    <?php
    include('../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>

    <!-- Mask para cpf,cnpj -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.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>
        initDropdownFilter('operacoes', false, null, false);
        $(document).ready(function() {
            let currentPage = 1;
            let itemsPerPage = 10;
            const $table = $('.table');
            const $tbody = $table.find('tbody');
            const $rows = $tbody.find('tr');
            const totalItems = $rows.length;

            function updatePagination() {
                const totalPages = Math.ceil(totalItems / itemsPerPage);
                const start = (currentPage - 1) * itemsPerPage;
                const end = Math.min(start + itemsPerPage, totalItems);

                // Hide all rows
                $rows.hide();

                // Show only rows for current page
                $rows.slice(start, end).show();

                // Update pagination info
                $('#pagination-info').text(`Mostrando ${start + 1} a ${end} de ${totalItems} registros`);

                // Update page numbers
                let pageNumbers = '';
                const maxPages = 5;
                let startPage = Math.max(1, currentPage - Math.floor(maxPages / 2));
                let endPage = Math.min(totalPages, startPage + maxPages - 1);

                if (endPage - startPage + 1 < maxPages) {
                    startPage = Math.max(1, endPage - maxPages + 1);
                }

                for (let i = startPage; i <= endPage; i++) {
                    pageNumbers += `<span class="page-number ${i === currentPage ? 'active' : ''}" data-page="${i}">${i}</span>`;
                }

                $('#page-numbers').html(pageNumbers);

                // Update button states
                $('#first-page, #prev-page').prop('disabled', currentPage === 1);
                $('#last-page, #next-page').prop('disabled', currentPage === totalPages);
            }

            // Event handlers
            $('#per-page-select').change(function() {
                itemsPerPage = parseInt($(this).val());
                currentPage = 1;
                updatePagination();
            });

            $('#first-page').click(function() {
                if (currentPage !== 1) {
                    currentPage = 1;
                    updatePagination();
                }
            });

            $('#last-page').click(function() {
                const totalPages = Math.ceil(totalItems / itemsPerPage);
                if (currentPage !== totalPages) {
                    currentPage = totalPages;
                    updatePagination();
                }
            });

            $('#prev-page').click(function() {
                if (currentPage > 1) {
                    currentPage--;
                    updatePagination();
                }
            });

            $('#next-page').click(function() {
                const totalPages = Math.ceil(totalItems / itemsPerPage);
                if (currentPage < totalPages) {
                    currentPage++;
                    updatePagination();
                }
            });

            $(document).on('click', '.page-number', function() {
                currentPage = parseInt($(this).data('page'));
                updatePagination();
            });

            // Initial pagination
            updatePagination();
        });
    </script>

    <script>
        // Função de pesquisa por nome do funcionário
        document.getElementById('pesquisa').addEventListener('input', function() {
            var texto = this.value.toLowerCase();
            var tabela = document.getElementById('datatable-buttons');
            var linhas = tabela.getElementsByTagName('tr');

            for (var i = 1; i < linhas.length; i++) { // Começa do 1 para pular o cabeçalho
                var celulas = linhas[i].getElementsByTagName('td');
                if (celulas.length > 1) { // Verifica se tem células suficientes
                    var encontrou = false;
                    // Percorre todas as células da linha
                    for (var j = 0; j < celulas.length; j++) {
                        var conteudoCelula = celulas[j].textContent || celulas[j].innerText;
                        if (conteudoCelula.toLowerCase().includes(texto)) {
                            encontrou = true;
                            break;
                        }
                    }
                    linhas[i].style.display = encontrou ? '' : 'none';
                }
            }
        });

        function updateURL(value) {
            // Atualiza a URL
            const url = new URL(window.location.href);
            url.searchParams.set('tabela', value);
            window.history.pushState({}, '', url);

            // Atualiza a aba ativa
            document.querySelectorAll('.nav-link').forEach(link => {
                link.classList.remove('active');
            });

            if (value === 'ativo') {
                document.querySelector('[aria-controls="ativo"]').classList.add('ativo');
            } else if (value === 'inativo') {
                document.querySelector('[aria-controls="inativo"]').classList.add('active');
            }
            // Recarrega a página para aplicar o filtro
            location.reload();
        }
    </script>


    </script>
    <style>
        .dropdown-menu {
            display: none;
            max-height: 400px;
            overflow-y: auto;
            position: absolute;
            z-index: 1000;
        }

        .operacoes-dropdown-menu {
            display: none;
            max-height: 400px;
            overflow-y: auto;
            position: absolute;
            z-index: 1000;
        }

        .operacoes-dropdown-item {
            cursor: pointer;
            padding: 8px;
            background-color: #f0f0f0;
            /* Definir a cor de fundo */
            color: inherit;
            /* Preserva a cor do texto definida globalmente */
            text-decoration: none;
            /* Remove o sublinhado */
        }

        .operacoes-dropdown-item:hover {
            background-color: #f0f0f0;
        }

        .drop {
            position: relative;
            bottom: 30px;
        }

        .operacoes {
            top: 10px;
            /* Deslocamento de 10px para baixo */
        }
    </style>
</body>

</html>