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

$categorias = new Categorias($connectionmysqlfinanceiro);
$lista_categorias = $categorias->listarCategorias();

$categorias->deletaCategoria();

if (isset($_GET['categorias'])) {
    $sql .= " AND nome LIKE '%" . $_GET['categorias'] . "%'";
}

if (isset($_SESSION['message'])) {
    echo "<script>alert('" . $_SESSION['message'] . "');</script>";
    unset($_SESSION['message']); // Limpa a mensagem após exibição
}
?>


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

<!DOCTYPE html>
<html lang="pt-br">
<?php
$pageTitle = "Lista de Categorias";
include('../header.php'); ?>

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

<head>
    <link rel="icon" href="/financeiromandareceita/logo-sm.png">
    <link rel="shortcut icon" href="/financeiromandareceita/logo-sm.png">
</head>

<body>
    <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">Lista de Categorias</h4>
                    </div>
                    <div class="col-6 text-right">
                        <a href="add_categoria.php" class="btn btn-primary">
                            <i class="mdi mdi-plus"></i> Nova Categoria
                        </a>
                    </div>

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

                    <div style="margin-bottom: 20px; position: relative; width: 98%;">
                        <div style="display: inline-block;">
                            <select id="per-page-select" class="form-select" style="width: auto; padding: 6px 3px; margin-left: 22px;">
                                <option value="10">10</option>
                                <option value="25">25</option>
                                <option value="50">50</option>
                                <option value="100">100</option>
                            </select>
                            <span style="margin-left: 5px;">registros por página</span>
                        </div>
                        <div style="position: absolute; right: 0; top: 0;">
                            <input type="text" id="pesquisa" class="form-control" placeholder="Pesquisar" style="width: 200px;">
                        </div>
                    </div>

                    <div class="col-12">
                        <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap">
                            <thead>
                                <tr class="text-center">
                                    <th>Nome da Categoria</th>
                                    <th>Tipo</th>
                                    <th>Operacional</th>
                                    <th>Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($lista_categorias as $categoria) : ?>
                                    <tr>
                                        <td width="40%"><?php echo $categoria['nome']; ?></td>
                                        <td width="20%"><?php echo $categoria['tipo'] == 'R' ? 'Receita' : 'Despesa'; ?></td>
                                        <td width="20%"><?php echo $categoria['operacional'] == 'S' ? 'Sim' : 'Não'; ?></td>
                                        <td width="20%" class="text-center">
                                            <a href="alteracao_categoria.php?id=<?php echo $categoria['id']; ?>"
                                                class="table-actions link-view" title="Alterar Categoria">
                                                <i class="mdi mdi-pencil"></i>
                                            </a>
                                            <button onclick="window.location.href='index.php?id=<?php echo $categoria['id']; ?>';"
                                                type="button" class="table-actions link-view excluir-btn"
                                                title="Excluir Categoria">
                                                <i class="mdi mdi-delete-forever"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        <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>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

    <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="../../../assets/js/funcoes.js"></script>

    <script>
        $(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>
        $(document).ready(function() {
            // Função de pesquisa por forma de pagamento e observação
            $('#pesquisa').on('keyup', function() {
                var texto = $(this).val().toLowerCase();
                $('.table tbody tr').each(function() {
                    var $linha = $(this);
                    if (!$linha.is(':first-child')) { // Ignora a linha de cabeçalho
                        var categorias = $linha.find('td:eq(0)').text().toLowerCase();
                        var tipo = $linha.find('td:eq(1)').text().toLowerCase();
                        var operacional = $linha.find('td:eq(2)').text().toLowerCase();

                        if (categorias.indexOf(texto) > -1 || tipo.indexOf(texto) > -1 || operacional.indexOf(texto) > -1) {
                            $linha.show();
                        } else {
                            $linha.hide();
                        }
                    }
                });
            });
        });
    </script>

</body>

</html>