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

// Instancia a classe de consulta_bb ao banco de dados
//$configuracoes = new Configuracoes();
$consulta_clientes = new ConsultaClientesValores();
$totalValor = 0;

// $operacoes = $configuracoes->get_operacoes_em_uso(); // Supondo que já seja um array
// if (!empty($operacoes)) {
//     sort($operacoes);
//     $operacoes = implode(',', array_map('intval', $operacoes));
// } else {
//     $operacoes = null;
// }

$filial = $_GET['filial'] ?? null;
$DataInicial = $_GET['DataInicial'] ?? null;
$DataFinal = $_GET['DataFinal'] ?? null;
$id_cliente = $_GET['id_cliente'] ?? null;
$nome = $_GET['nome'] ?? null;
$tel = $_GET['tel'] ?? null;
$celular = $_GET['celular'] ?? null;
$email = $_GET['email'] ?? 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_clientes->get_cliente_detalhe_manpilado($filial, $DataInicial, $DataFinal,  $id_cliente);
} elseif ($tabela == '2') {
    $detalhes = $consulta_clientes->get_cliente_detalhe_varejo($filial, $DataInicial, $DataFinal, $id_cliente);
}
//var_dump($detalhes);
?>

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

<head>
    <link rel="stylesheet" href="../configuracao/modalexcluir.css">
</head>
<?php
$pageTitle = "Detalhes Cliente Recebidos";
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 Cliente</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>Telefone:</b>
                            <?php echo isset($tel) ? htmlspecialchars($tel, ENT_QUOTES, 'UTF-8') : 'N/A'; ?>
                        </p>
                    </div>
                    <div class="form-group col-md-3 ">
                        <p><b>E-mail:</b>
                            <?php echo isset($email) ? htmlspecialchars($email, ENT_QUOTES, 'UTF-8') : 'N/A'; ?>
                        </p>
                    </div>
                    <div class="form-group col-md-3">
                        <p><b>Celular:</b>
                            <?php
                            if (isset($celular)) {
                                $telefone = $celular;
                                $telefone_whatsapp = preg_replace("/[^0-9]/", "", $telefone);
                                // Verifique se o número de telefone não está vazio
                                if (!empty($telefone_whatsapp)) {
                                    // Crie o link para o WhatsApp
                                    $link_whatsapp = "https://api.whatsapp.com/send?phone=55" . $telefone_whatsapp;
                                    // Exiba o número de telefone como um hyperlink com o ícone do WhatsApp
                                    echo '<a href="' . htmlspecialchars($link_whatsapp) . '" target="_blank" style="color: green;">';
                                    echo '<svg class="svg-inline--fa fa-whatsapp link-success" aria-hidden="true" focusable="false" data-prefix="fab" data-icon="whatsapp" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" data-fa-i2svg="" style="width: 18px; height: auto;"><path fill="currentColor" d="M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7.9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z"></path></svg>';
                                    echo ' ' . htmlspecialchars($telefone, ENT_QUOTES, 'UTF-8');
                                    echo '</a>';
                                } else {
                                    echo 'Número de telefone inválido';
                                }
                            } else {
                                echo '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')">Revenda</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" class="text-center" class="col-1" scope="col">Filial</th>
                                            <th class="text-center" class="text-center" scope="col">Requisição</th>
                                            <!-- <th class="text-center" scope="col">Data</th> -->
                                            <!-- <th class="text-center"scope="col">Saldo</th> -->
                                            <th class="text-center">Valor</th>
                                        </tr>
                                    <?php } ?>
                                </thead>
                                <tbody>
                                    <?php
                                    $hasResults = false;
                                    foreach ($detalhes as $row) {
                                        $hasResults = true; ?>
                                        <tr class="text-center">
                                            <td><?= htmlspecialchars($row['LJ']) ?></td>
                                            <?php // echo '<td data-order="' . $row['AVIADA_DT'] . '">' . ($row['AVIADA_DT'] !== null ? date('d/m/Y', strtotime($row['AVIADA_DT'])) : 'N/A') . '</td>'; 
                                            ?>
                                            <td data-order="<?= $row['REQUISICAO'] ?>"><?= $row['REQUISICAO'] ?></td>
                                            <td data-order="<?= number_format($row['VALOR'], 2, '.', '') ?>"><?= 'R$ ' . number_format($row['VALOR'], 2, ',', '.') ?></td>
                                        </tr>
                                        <?php
                                        $totalValor += ($row['VALOR']);
                                        ?>
                                    <?php } ?>
                                    <?php if (!$hasResults) {
                                        echo "<tr><td colspan='3' class='text-center'>Nenhum registro encontrado.</td></tr>";
                                    } ?>
                                </tbody>
                            <?php } elseif ($tabela == '2') { ?>
                                <thead>
                                    <tr class="text-center">
                                        <th class="text-center" class="col-1" scope="col">Filial</th>
                                        <th class="text-center" scope="col">Cupom</th>
                                        <!-- <th scope="col">Data</th> -->
                                        <th class="text-center" scope="col">Cod.Produto</th>
                                        <th class="text-center" scope="col">Produto</th>
                                        <th class="text-center" scope="col">Valor</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $hasResults = false;
                                    foreach ($detalhes as $row) {
                                        $hasResults = true;
                                        $row['NOMEPRODUTO'] = mb_convert_encoding($row['NOMEPRODUTO'], 'UTF-8', 'ISO-8859-1'); ?>
                                        <tr class="text-center">
                                            <td><?= htmlspecialchars($row['CODLJ']) ?></td>
                                            <td data-order="<?= $row['CUPOM'] ?>"><?= $row['CUPOM'] ?></td>
                                            <!-- <td><?= htmlspecialchars($row['DTSAI']) ?></td> -->
                                            <td><?= htmlspecialchars($row['CODIGO_PRODUTO']) ?></td>
                                            <td class="col-3"><?= htmlspecialchars($row['NOMEPRODUTO']) ?></td>
                                            <td data-order="<?= $row['VALOR'] ?>"><?= 'R$ ' . number_format($row['VALOR'], 2, ',', '.') ?></td>

                                        </tr>
                                    <?php
                                        $totalValor += ($row['VALOR']);
                                    } ?>
                                    <?php if (!$hasResults) {
                                        echo "<tr><td colspan='5' 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>
                                </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": [
                    //'copyHtml5',
                    '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>>',
                //"dom": 'lBfrtip'
            });

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

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

        function goBack() {
            window.history.back();
        }
    </script>

</body>

</html>