<?php
require '../conexao/conexao.php';
require '../conexao/acesso.php';
require '../configuacoes.php';
require '../configuracao/consulta_banco_dados.php';
require '../configuracao/filtros.php';
require '../querys/query-configuracao-metas.php';
require 'consulta_db.php';
require '../configuracao/get_config.php';

$configuracoes = new Configuracoes();
$nome_para_vendedores = $configuracoes->get_nomeclatura_vendedor();
$nome_para_vendedor = $configuracoes->get_nomeclatura_vendedor(true);

$ConfiguracaoMetas = new ConfiguracaoMetas($connectionmysql);
$consulta_bb = new ConsultaBancoDeDados();
$filtros = new Filtros();

// CORREÇÃO AQUI: Passando a conexão global para a classe
global $connection; 
$consulta_caixa = new ConsultaCaixa($connection);

$resultmeta = null;
$ConsultaPermissoes = $ConfiguracaoMetas->consultaPermissoes();
$filiais = $consulta_bb->get_filiais();
$cidades = $consulta_bb->get_cidades();

$exibirManipulado = false;
$exibirRevenda = false;
$exibirMarcaPropria = false;

foreach ($ConsultaPermissoes as $permissao) {
    if ($permissao['id_tipo_meta'] == 2) {
        $exibirManipulado = true;
    } elseif ($permissao['id_tipo_meta'] == 1) {
        $exibirRevenda = true;
    } elseif ($permissao['id_tipo_meta'] == 3) {
        $exibirMarcaPropria = true;
    }
}

$ids = array_column($filiais, 'ID');
$ids_filial = implode(',', $ids);
$filial = !empty($_GET['filial']) ? $_GET['filial'] : $ids_filial;
if (strpos($filial, ',') !== false) {
    $allfilial = explode(',', $filial);
} else {
    $allfilial = [$filial];
}

$cidade = $_GET['cidade'] ?? null;
$DataInicial = $_GET['DataInicial'] ?? null;
$DataFinal = $_GET['DataFinal'] ?? null;
$nome = $_GET['nome'] ?? null;
$codigo = $_GET['id_vendedor'] ?? null;
$tabela = isset($_GET['tabela']) ? $_GET['tabela'] : 'manipulado'; 

$queryString = http_build_query([
    'cidade' => $cidade,
    'filial' => $filial,
    'DataInicial' => $DataInicial,
    'DataFinal' => $DataFinal,
    'form_submitted' => '1'
]);

// Removida as validações de convênio
if ($tabela == 'manipulado' && $exibirManipulado) {
    $detalhes_vendedores = $consulta_caixa->getDetalhesManipulado($DataInicial, $DataFinal, $filial, $codigo);
} elseif ($tabela == 'revenda' && $exibirRevenda) {
    $detalhes_vendedores = $consulta_caixa->getDetalhesRevenda($DataInicial, $DataFinal, $filial, $codigo);
} elseif ($tabela == 'marca' && $exibirMarcaPropria) {
    $detalhes_vendedores = $consulta_caixa->getDetalhesMarca($DataInicial, $DataFinal, $filial, $codigo);
} 
?>

<!DOCTYPE html>
<html lang="pt-br">
<?php
$pageTitle = "Detalhes " . $nome_para_vendedor;
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"><?php echo $pageTitle; ?></h4>
                    </div>
                    <div class="col-6 text-right">
                        <a href="caixa_vendedor.php?<?= $queryString ?>" class="btn btn-light">
                            <i class="mdi mdi-keyboard-backspace"></i> Voltar
                        </a>
                    </div>
                    <div class="col-12"><hr></div>
                    
                    <div class="col-12">
                        <form method="post" action="" onsubmit="return validarFormulario();">
                            <div class="form-row mb-3">
                                <div class="form-group col-md-3 ">
                                    <p><b>Nome:</b> <?php echo htmlspecialchars($nome, ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>
                                <div class="form-group col-md-3 ">
                                    <p><b>Codigo <?= $nome_para_vendedor ?>:</b> <?php echo htmlspecialchars($codigo, ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>

                                <div class="col-12">
                                    <h6>Tabela de Vendas</h6>
                                    <nav>
                                        <ul class="nav nav-tabs" id="myTab" role="tablist" style="font-size: medium;">
                                            <?php if ($exibirManipulado) { ?>
                                                <li class="nav-item">
                                                    <a class="nav-link <?php echo ($tabela == 'manipulado') ? 'active' : ''; ?>" id="manipulado-tab" data-toggle="tab" href="#manipulado" role="tab" aria-controls="manipulado" onclick="updateURL('manipulado')">Manipulado</a>
                                                </li>
                                            <?php } ?>

                                            <?php if ($exibirRevenda) { ?>
                                                <li class="nav-item">
                                                    <a class="nav-link <?php echo ($tabela == 'revenda') ? 'active' : ''; ?>" id="revenda-tab" data-toggle="tab" href="#revenda" role="tab" aria-controls="revenda" onclick="updateURL('revenda')">Revenda</a>
                                                </li>
                                            <?php } ?>

                                            <?php if ($exibirMarcaPropria) { ?>
                                                <li class="nav-item">
                                                    <a class="nav-link <?php echo ($tabela == 'marca') ? 'active' : ''; ?>" id="marca-tab" data-toggle="tab" href="#marca" role="tab" aria-controls="marca" onclick="updateURL('marca')">Marca Própria</a>
                                                </li>
                                            <?php } ?>
                                        </ul>
                                    </nav>
                                    
                                    <div class="tab-content" id="myTabContent">
                                        <div class="tab-pane fade show active">
                                            <table id="minhaTabela" class="table table-bordered table-hover table-sm" style="width:100%;">
                                                <thead class="thead-light">
                                                    <tr>
                                                        <th scope="col">Filial</th>             
                                                        <th scope="col"><?php echo ($tabela == 'manipulado') ? 'Número Requisição' : 'Número Cupom'; ?></th>
                                                        <th scope="col">Valor</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    $totalValor = 0;
                                                    $hasResults = false;
                                                    if (isset($detalhes_vendedores) && is_array($detalhes_vendedores)) {
                                                        foreach ($detalhes_vendedores as $row) {
                                                            $hasResults = true;
                                                            echo '<tr>';
                                                            echo '<td>' . ($row['CDFIL'] ?? 'N/A') . '</td>';
                                                            echo '<td>' . ($row['NRCPM'] ?? 'N/A') . '</td>';
                                                            echo '<td data-order="' . $row['SOMA'] . '">' . ($row['SOMA'] !== null ? number_format($row['SOMA'], 2, ',', '.') : 'N/A') . '</td>';
                                                            echo '</tr>';
                                                            
                                                            $totalValor += floatval($row['SOMA']);
                                                        }
                                                    }
                                                    if (!$hasResults) {
                                                        echo "<tr><td colspan='3' class='text-center'>Sem resultado para a consulta</td></tr>";
                                                    }
                                                    ?>
                                                </tbody>
                                            </table>
                                            
                                            <div class="row mt-3">
                                                <div class="col-md-12">
                                                    <h4>Total Valor: R$ <?php echo number_format($totalValor, 2, ',', '.'); ?></h4>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include('../geral/footer.php'); ?>
    <?php include('../geral/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>
</body>
</html>

<script src="../geral/javascript.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>
    $(document).ready(function() {
        var tabela = $('#minhaTabela').DataTable({
            "language": {
                "url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json"
            },
            "buttons": [
                'excelHtml5',
                'csvHtml5',
                'pdfHtml5'
            ],
            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>>',
            "ordering": true,
        });
    });

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

        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
        });

        if (value === 'manipulado') {
            document.querySelector('[aria-controls="manipulado"]').classList.add('active');
        } else if (value === 'marca') {
            document.querySelector('[aria-controls="marca"]').classList.add('active');
        } else if (value === 'revenda') {
            document.querySelector('[aria-controls="revenda"]').classList.add('active');
        } 

        location.reload();
    }
</script>
<style>
    .dataTables_length label,
    .dataTables_info {
        margin: 0 !important;
        padding: 0 !important;
        align-items: center;
    }
</style>