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

// Instancia a classe de consulta ao banco de dados
$consulta_clientes_orcamentos = new ConsultasClientesOrcamentos();

$filial = $_GET['filial'] ?? null;
$DataInicial = $_GET['dataInicial'] ?? null;
$DataFinal = $_GET['dataFinal'] ?? null;
$vendedor = $_GET['vendedor'] ?? null;
$cliente = $_GET['cliente'] ?? null;
$id_cliente = $_GET['id_cliente'] ?? null;
$tabela = isset($_GET['tabela']) ? $_GET['tabela'] : 'Todos';

$query_string = http_build_query([
    'filial' => $filial,
    'dataInicial' => $DataInicial,
    'dataFinal' => $DataFinal,
    'vendedor' => $vendedor,
    'cliente' => $cliente,
    'form_submitted' => isset($_GET['form_submitted']) ? $_GET['form_submitted'] : null,
]);


$detalhes = $consulta_clientes_orcamentos->get_cliente_detalhes($id_cliente, $filial, $DataInicial, $DataFinal, $vendedor, $tabela);
$clienteinfo = $consulta_clientes_orcamentos->get_cliente($id_cliente);
?>

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

<head>
    <link rel="stylesheet" href="../configuracao/modalexcluir.css">
</head>
<?php
$pageTitle = "Detalhes Cliente Orçamento";
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 Cliente Orçamento</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($clienteinfo[0]['NOMEPA']) ? htmlspecialchars($clienteinfo[0]['NOMEPA'], ENT_QUOTES, 'UTF-8') : 'N/A'; ?>
                        </p>
                    </div>
                    <div class="form-group col-md-3 ">
                        <p><b>Telefone:</b>
                            <?php echo isset($clienteinfo[0]['TELEFONE2']) ? htmlspecialchars($clienteinfo[0]['TELEFONE2'], ENT_QUOTES, 'UTF-8') : 'N/A'; ?>
                        </p>
                    </div>

                    <div class="form-group col-md-3">
                        <p><b>Celular:</b>
                            <?php
                            if (isset($clienteinfo[0]['TEL']) && isset($clienteinfo[0]['TEL'])) {
                                $telefone = $clienteinfo[0]['TEL'];
                                $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 Orçamentos</h6>
                    </div>
                    <nav>
                        <ul class="nav nav-tabs" id="myTab" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link <?php echo ($tabela == 'Todos') ? 'active' : ''; ?>" id="geral-tab" data-toggle="tab" href="#geral" role="tab" aria-controls="geral" aria-selected="<?php echo ($tabela == 'Todos') ? 'true' : 'false'; ?>" onclick="updateURL('Todos')">Geral</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo ($tabela == '1') ? 'active' : ''; ?>" id="aprovado-tab" data-toggle="tab" href="#aprovado" role="tab" aria-controls="aprovado" aria-selected="<?php echo ($tabela == '1') ? 'true' : 'false'; ?>" onclick="updateURL('1')">Aprovado</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link <?php echo ($tabela == '2') ? 'active' : ''; ?>" id="reprovado-tab" data-toggle="tab" href="#reprovado" role="tab" aria-controls="reprovado" aria-selected="<?php echo ($tabela == '2') ? 'true' : 'false'; ?>" onclick="updateURL('2')">Reprovado</a>
                            </li>
                        </ul>
                    </nav>
                    <div class="tab-content" id="myTabContent">
                        <?php if ($tabela = 'Todos') { ?>
                            <div class="tab-pane fade show active" id="geral" role="tabpanel" aria-labelledby="geral-tab">
                            <?php } elseif ($tabela = '2') { ?>
                                <div class="tab-pane fade show active" id="reprovado" role="tabpanel" aria-labelledby="reprovado-tab">
                                <?php } elseif ($tabela = '1') { ?>
                                    <div class="tab-pane fade show active" id="aprovado" role="tabpanel" aria-labelledby="aprovado-tab">
                                    <?php } ?>
                                    <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap">
                                        <thead>
                                            <tr class="text-center">
                                                <th scope="col">Filial</th>
                                                <th scope="col">Requisição</th>
                                                <th scope="col">Fórmula</th>
                                                <th scope="col"><?= $nome_para_vendedor ?></th>
                                                <th scope="col">Cod Cliente</th>
                                                <th scope="col">Cliente</th>
                                                <th>Total Vendas</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $totalValor = 0;
                                            $hasResults = false; // Inicializa a variável para verificar se há resultados
                                            foreach ($detalhes as $row) {  // Itera sobre o array $detalhes
                                                $hasResults = true;
                                                // $nome_vendedor = mb_convert_encoding($row['VENDEDOR'], 'UTF-8', 'ISO-8859-1'); 
                                                $nome_vendedor = $row['VENDEDOR']; ?>
                                                <tr class="text-center">
                                                    <td><?= htmlspecialchars($row['FILIAL']) ?></td>
                                                    <td data-order="<?= $row['REQUISICAO'] ?>"><?= $row['REQUISICAO'] ?>
                                                    <td><?= htmlspecialchars($row['NUMEROFORMULA']) ?></td>
                                                    <td><?= htmlspecialchars($nome_vendedor) ?></td>
                                                    <td><?= htmlspecialchars($row['COD_CLIENTE']) ?></td>
                                                    <td><?= htmlspecialchars($row['NOME_CLIENTE']) ?></td>
                                                    <td data-order="<?= number_format($row['VALOR'], 2, '.', '') ?>"><?= 'R$ ' . number_format($row['VALOR'], 2, ',', '.') ?>
                                                </tr>

                                            <?php
                                                $totalValor += floatval($row['VALOR']);
                                            }
                                            if (!$hasResults) {
                                                echo "<tr><td colspan='9' class='text-center'>Nenhum registro encontrado.</td></tr>";
                                            }
                                            ?>
                                        </tbody>
                                    </table> <!-- Adiciona a linha com o totalizador -->
                                    <div class="row">
                                        <div class="col-md-12">
                                            <h4>Total : R$ <?php echo number_format($totalValor, 2, ',', '.'); ?></h4>
                                        </div>
                                    </div>
                                    </div>
                                </div>
                            </div>
                    </div>
                </div>



            </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>>',
            });

            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();
        }

        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 === 'Todos') {
                document.querySelector('[aria-controls="geral"]').classList.add('active');
            } else if (value === '1') {
                document.querySelector('[aria-controls="aprovado"]').classList.add('active');
            } else if (value === '0') {
                document.querySelector('[aria-controls="reprovado"]').classList.add('active');
            }

            // Recarrega a página para aplicar o filtro
            location.reload();
        }
    </script>
    <style>
        #datatable-buttons_length label,
        #datatable-buttons_info {
            margin: 0 !important;
            padding: 0 !important;
            align-items: center;
        }
    </style>
</body>

</html>