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

// Instancia a classe de consulta ao banco de dados
$consulta_descontos = new ConsultaDescontos();
$totalValor = 0;
$totalDesconto = 0;


$filial = $_GET['filial'] ?? null;
$DataInicial = $_GET['DataInicial'] ?? null;
$DataFinal = $_GET['DataFinal'] ?? null;
$id_desconto = $_GET['id_desconto'] ?? null;
$nome = $_GET['nome'] ?? null;
$filial_pagamento = $_GET['filial_pagamento'] ?? null;
$requisicao = $_GET['requisicao'] ?? null;
$valor_recebido = $_GET['valor_recebido'] ?? null;
$percent_desc = $_GET['PERCENT_DESC'] ?? null;
$tipoSelecionado = $_GET['tipo'] ?? '1';
if ($tipoSelecionado) {
    $tabela = $tipoSelecionado;
} else {
    $tabela = isset($_GET['tabela']) ? $_GET['tabela'] : '1';
}

$query_string = http_build_query([
    'filial' => (strpos($filial, ',') !== false ? '' : $filial),
    'DataInicial' => $DataInicial,
    'DataFinal' => $DataFinal,
    'tipo' => $tipoSelecionado,
    'form_submitted' => '1'
]);


if ($tabela == '1') {
    $detalhes = $consulta_descontos->get_desconto_manipulado($filial, $DataInicial, $DataFinal, $requisicao);
} elseif ($tabela == '2') {
    $detalhes = $consulta_descontos->get_desconto_varejo($filial, $DataInicial, $DataFinal, $requisicao);
}
?>

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

<head>
    <link rel="stylesheet" href="../configuracao/modalexcluir.css">
</head>
<?php
$pageTitle = "Detalhes do descontos";
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">Detalhes Do Desconto</h4>
                    </div>
                    <div class="col-6 text-right">
                        <a href="index.php?<?= $query_string ?>" class="btn btn-light">
                            <i class="mdi mdi-keyboard-backspace"></i> Voltar
                        </a>
                        <!-- <button onclick="goBack()" class="btn btn-light"><i class="mdi mdi-keyboard-backspace"></i> Voltar</button> -->
                    </div>
                    <div class="col-12">
                        <hr>
                    </div>
                </div>

                <div class="form-row mb-3">
                    <div class="form-group col-md-3 ">
                        <p><b>Nome:</b>
                            <?php echo isset($nome) ? htmlspecialchars($nome, ENT_QUOTES, 'UTF-8') : 'N/A'; ?>
                        </p>
                    </div>
                    <div class="form-group col-md-3 ">
                        <p><b>Data Inicial:</b>
                            <?php echo isset($DataInicial) ? date('d/m/Y', strtotime($DataInicial)) : 'N/A'; ?>
                        </p>
                    </div>
                    <div class="form-group col-md-3 ">
                        <p><b>Data Final:</b>
                            <?php echo isset($DataFinal) ? date('d/m/Y', strtotime($DataFinal)) : 'N/A'; ?>
                        </p>
                    </div>
                </div>


                <div class="col-12">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <h6>Lista de Dados</h6>
                    </div>
                    <?php if (!$tipoSelecionado) : // Verifica se $tipoSelecionado não está definido ou é falso 
                    ?>
                        <nav>
                            <ul class="nav nav-tabs" id="myTab" role="tablist">
                                <li class="nav-item">
                                    <a class="nav-link <?php echo ($tabela == '1') ? 'active' : ''; ?>" id="manipulado-tab" data-toggle="tab" href="#manipulado" role="tab" aria-controls="manipulado" aria-selected="<?php echo ($tabela == '1') ? 'true' : 'false'; ?>" onclick="updateURL('1')">Manipulado</a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link <?php echo ($tabela == '2') ? 'active' : ''; ?>" id="varejo-tab" data-toggle="tab" href="#varejo" role="tab" aria-controls="varejo" aria-selected="<?php echo ($tabela == '2') ? 'true' : 'false'; ?>" onclick="updateURL('2')">Varejo</a>
                                </li>
                            </ul>
                        </nav>
                    <?php endif; ?>
                    <?php if (!$tipoSelecionado) : // Verifica se $tipoSelecionado não está definido ou é falso 
                    ?>
                        <div class="tab-content" id="myTabContent">
                            <?php
                            if ($tabela == '2') { ?>
                                <div class="tab-pane fade show active" id="varejo" role="tabpanel" aria-labelledby="varejo-tab">
                                    <!-- Conteúdo da aba Varejo -->
                                </div>
                            <?php } elseif ($tabela == '1') { ?>
                                <div class="tab-pane fade show active" id="manipulado" role="tabpanel" aria-labelledby="manipulado-tab">
                                    <!-- Conteúdo da aba Manipulado -->
                                </div>
                            <?php } ?>
                        <?php endif; ?>

                        <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap">
                            <?php if ($tabela == '1') { ?>
                                <thead>
                                    <?php if ($tabela == '1') { ?>
                                        <tr class="text-center">
                                            <th class="text-center">Requisição</th>
                                            <th class="text-center">Filial</th>
                                            <th class="text-center">Fórmula</th>
                                            <th class="text-center">Cod Produto</th>
                                            <th class="text-center">Nome Produto</th>
                                            <th class="text-center">Lote</th>
                                            <th class="text-center">Quantidade</th>
                                            <th class="text-center">Unidade</th>
                                            <th class="text-center">Quantidade Calculo</th>
                                            <!-- <th class="text-center">Valor</th> -->
                                        </tr>
                                    <?php } ?>
                                </thead>
                                <tbody>
                                    <?php
                                    $hasResults = false;
                                    foreach ($detalhes as $row) {
                                        //print_r($detalhes);
                                        $hasResults = true; ?>
                                        <tr class="text-center">
                                            <td data-order="<?= $row['CODIGO_ATEND_A1'] ?>"><?= $row['CODIGO_ATEND_A1'] ?></td>
                                            <td data-order="<?= $row['CADASTRO_LJ'] ?>"><?= $row['CADASTRO_LJ'] ?></td>
                                            <td data-order="<?= $row['NUMEROFORMULA'] ?>"><?= $row['NUMEROFORMULA'] ?></td>
                                            <td data-order="<?= $row['CODIGO_PRODUTO'] ?>"><?= $row['CODIGO_PRODUTO'] ?></td>
                                            <td data-order="<?= $row['NOMEPRODUTO'] ?>"><?= $row['NOMEPRODUTO'] ?></td>
                                            <td data-order="<?= $row['LOTE_LA'] ?>"><?= $row['LOTE_LA'] ?></td>
                                            <td data-order="<?= number_format($row['QUANTIDADE'], 2, '.', '') ?>"><?= number_format($row['QUANTIDADE'], 2, ',', '.') ?></td>
                                            <td data-order="<?= $row['UNIDADE'] ?>"><?= $row['UNIDADE'] ?></td>
                                            <td data-order="<?= number_format($row['QUANTIDADE_CALCULO'], 2, '.', '') ?>"><?= number_format($row['QUANTIDADE_CALCULO'], 2, ',', '.') ?></td>
                                            <!-- <td data-order="<?= number_format($row['VALORVENDA'], 2, '.', '') ?>"><?= 'R$ ' . number_format($row['VALORVENDA'], 2, ',', '.') ?></td> -->
                                        </tr>
                                        <?php
                                        $totalValor += ($row['VALORVENDA']);
                                        //$totalDesconto += ($desconto_manipulado);
                                        ?>
                                    <?php } ?>
                                    <?php if (!$hasResults) {
                                        echo "<tr><td colspan='9' class='text-center'>Nenhum registro encontrado.</td></tr>";
                                    } ?>
                                </tbody>
                            <?php } elseif ($tabela == '2') { ?>
                                <thead>
                                    <tr class="text-center">
                                        <th class="text-center">Código do Cliente</th>
                                        <th class="text-center">Cupom</th>
                                        <th class="text-center">Valor Líquido</th>
                                        <th class="text-center">Valor Desconto</th>
                                        <th class="text-center">Valor Bruto</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $hasResults = false;
                                    foreach ($detalhes as $row) {
                                        $percentual_desconto_varejo = (($row['VALOR_BRUTO_VAREJO'] - $row['VALOR_LIQUIDO_VAREJO']) / $row['VALOR_BRUTO_VAREJO']) * 100;
                                        $hasResults = true; ?>
                                        <tr class="text-center">
                                            <td data-order="<?= $row['CODIGO_CLIENTE'] ?>"><?= $row['CODIGO_CLIENTE'] ?></td>
                                            <td data-order="<?= $row['CUPOM'] ?>"><?= $row['CUPOM'] ?></td>
                                            <td data-order="<?= number_format($row['VALOR_LIQUIDO_VAREJO'], 2, '.', ',') ?>"><?= 'R$ ' . number_format($row['VALOR_LIQUIDO_VAREJO'], 2, ',', '.') ?></td>
                                            <td data-order="<?= number_format($percentual_desconto_varejo, 2, '.', '') ?>"><?= 'R$ ' . number_format($percentual_desconto_varejo, 2, ',', '.') ?></td>
                                            <td data-order="<?= number_format($row['VALOR_BRUTO_VAREJO'], 2, '.', '') ?>"><?= number_format($row['VALOR_BRUTO_VAREJO'], 2, ',', '.') ?></td>

                                        </tr>
                                    <?php
                                        $totalValor += ($row['VALOR_BRUTO_VAREJO']);
                                        $totalDesconto += ($percentual_desconto_varejo);
                                    } ?>
                                    <?php if (!$hasResults) {
                                        echo "<tr><td colspan='7' class='text-center'>Nenhum registro encontrado.</td></tr>";
                                    } ?>
                                </tbody>
                            <?php } ?>

                        </table>
                        <?php //if (!empty($detalhes)) : 
                        ?>
                        <!-- <div class="row">
                                <div class="col-md-12">
                                    <h4>Total Valor: R$ <?php // echo number_format($totalValor, 2, ',', '.'); 
                                                        ?></h4>
                                     <h4>Total de Desconto: R$ <?php  //echo number_format($totalDesconto, 2, ',', '.'); 
                                                                ?></h4> 
                                </div>
                            </div>-->
                        <?php // endif 
                        ?>
                        </div>
                </div>
            </div>

            <script>
                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 === '1') {
                        document.querySelector('[aria-controls="manipulado"]').classList.add('active');
                    } else if (value === '2') {
                        document.querySelector('[aria-controls="varejo"]').classList.add('active');
                    }

                    location.reload();
                }
            </script>

        </div>
    </div>
    </div>

    <!-- FINAL MODAL DE EXCLUIR -->

    <!-- end wrapper -->

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

    <!-- 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>
    <!-- Inclua isso no cabeçalho para garantir que as bibliotecas sejam carregadas -->
    <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 table = $('#datatable-buttons').DataTable({
                "language": {
                    "url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json"
                },
                "ordering": true,
                "responsive": true,
                "autoWidth": false,
                "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>>',
            });

            setTimeout(function() {
                $("#datatable-buttons_filter").children("label").css("font-size", "15px");
            }, 150);

            setTimeout(function() {
                $("#datatable-buttons_length").children("label").css("font-size", "15px", "margin-top", "8px");
            }, 150);
        });

        function goBack() {
            window.history.back();
        }
    </script>
    <style>
        #datatable-buttons_length label,
        #datatable-buttons_info {
            margin: 0 !important;
            padding: 0 !important;
            align-items: center;
        }
    </style>
</body>

</html>