<?php
require '../conexao/conexao.php';
//require '../sessao.php';
require '../conexao/acesso.php';
require '../configuracoes.php';
require '../configuracao/consulta_banco_dados.php';
require '../configuracao/filtros.php';
require '../configuracao/get_config.php';
require '../logs/gera-log.php';

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

$idVendedor = $_GET['id_vendedor'] ?? null;
$nomeVendedor = $_GET['nomeVendedor'] ?? null;
$dataInicial = $_GET['DataInicial'] ?? date('Y-m-01');
$dataFinal = $_GET['DataFinal'] ?? date('Y-m-t');
$filial = $_GET['filial'] ?? null;
$tabela = $_GET['tabela'] ?? 'Todos';

$query_string = http_build_query([
    'nomeVendedor' => $nomeVendedor,
    'DataInicial' => $dataInicial,
    'DataFinal' => $dataFinal,
    'filial' => $filial,
    'pesquisar' => ''
]);

// Inicializa o array de detalhes
$detalhes = [];
$totalGeral = 0;

// Executa a consulta se tivermos o ID do vendedor
if (!empty($idVendedor)) {
    // Verifica se a extensão Firebird/Interbase está carregada
    if (!function_exists('ibase_connect')) {
        die('Erro: A extensão Firebird/Interbase não está habilitada no PHP. Por favor, ative a extensão php_interbase no seu php.ini');
    }
    
    // Configurações de conexão
    $host = 'localhost';
    $database = 'C:/Prime/psbd.fdb';
    $username = 'sysdba';
    $password = 'masterkey';
    
    // Conectar ao banco de dados
    $connection = @ibase_connect($host . ':' . $database, $username, $password, 'UTF8', 0, 3);
    
    if (!$connection) {
        $error = ibase_errmsg();
        die('Erro na conexão com o banco de dados: ' . $error);
    }
    
    try {
        // Preparar a consulta SQL com parâmetros
        $sql = "SELECT
            A1.CODIGO_CLIENTE AS cod_cliente,
            CL.NOMECLIENTE AS nome_cliente,
            A1.cadastro_lj as filial,
            A1.codigo as requisicao,
            A2.numeroformula,
            A1.CADASTRO_DT,
            FU.nomefuncionario as vendedor,
            SUM(A2.valorformula_venda_desc) as valor
        FROM ATENDIMENTO_A1 A1
        JOIN CLIENTE CL ON CL.CODIGO = A1.CODIGO_CLIENTE
        JOIN FUNCIONARIO FU ON FU.CODIGO = IIF(A1.STATUS_MOV = 0, A1.CADASTRO_LJ, A1.AVIADA_CF)
        INNER JOIN ATENDIMENTO_A2 A2 ON A2.codigo_atend_a1 = A1.codigo
        WHERE A1.TIPO_ATENDIMENTO = 1
        AND CAST(A1.CADASTRO_DT AS DATE) BETWEEN ? AND ?
        AND A1.CODIGO_FUNCIONARIO_COMISSAO = ?";

        // Adiciona filtro de filial se fornecido
        if ($filial && $filial != "") {
            $sql .= " AND A1.cadastro_lj IN ({$filial})";
        }

        $sql .= "
        GROUP BY
            A1.CODIGO_CLIENTE,
            CL.NOMECLIENTE,
            A1.codigo,
            A1.cadastro_lj,
            A2.numeroformula,
            FU.nomefuncionario,
            A1.CADASTRO_DT
        ORDER BY A1.CADASTRO_DT DESC";

        // Preparar e executar a consulta com parâmetros
        $stmt = ibase_prepare($connection, $sql);
        
        if (!$stmt) {
            throw new Exception('Erro ao preparar a consulta: ' . ibase_errmsg());
        }
        
        $result = @ibase_execute($stmt, $dataInicial, $dataFinal, $idVendedor);
        
        if (!$result) {
            throw new Exception('Erro ao executar a consulta: ' . ibase_errmsg());
        }
        
        // Obter os resultados
        $detalhes = array();
        while ($row = ibase_fetch_assoc($result)) {
            // Converter para UTF-8 se necessário
            foreach ($row as $key => $value) {
                if (is_string($value)) {
                    $row[$key] = mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1');
                }
            }
            $detalhes[] = $row;
            $totalGeral += (float)$row['VALOR'];
        }
        
        // Liberar recursos
        ibase_free_result($result);
        
    } catch (Exception $e) {
        // Em caso de erro, definir mensagem e continuar a execução
        $error_message = $e->getMessage();
        echo "<div class='alert alert-danger'>Erro: $error_message</div>";
        $detalhes = array();
    } finally {
        // Fechar a conexão
        if (isset($connection)) {
            @ibase_close($connection);
        }
    }
}
?>


<!DOCTYPE html>
<html lang="pt-br">
<?php
$pageTitle = "Detalhar Vendedor";
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">
                            <?php echo $pageTitle; ?>
                        </h4>
                    </div>
                    <div class="col-6 text-right">
                        <!-- <button onclick="goBack()" class="btn btn-light"><i class="mdi mdi-keyboard-backspace"></i> Voltar</button> -->
                        <a href="index.php?<?= $query_string ?>" class="btn btn-light">
                            <i class="mdi mdi-keyboard-backspace"></i> Voltar
                        </a>
                    </div>
                    <div class="col-12">
                        <hr>
                    </div>
                    <div class="col-12">
                        <div class="card mb-3">
                            <div class="card-body">
                                <h5 class="card-title">Filtros</h5>
                                <form method="get" action="" class="form-inline">
                                    <input type="hidden" name="id_vendedor" value="<?= htmlspecialchars($idVendedor) ?>">
                                    <input type="hidden" name="nomeVendedor" value="<?= htmlspecialchars($nomeVendedor) ?>">
                                    
                                    <div class="form-group mb-2 mr-2">
                                        <label for="DataInicial" class="mr-2">Data Inicial:</label>
                                        <input type="date" class="form-control" id="DataInicial" name="DataInicial" 
                                               value="<?= htmlspecialchars($dataInicial) ?>">
                                    </div>
                                    
                                    <div class="form-group mb-2 mr-2">
                                        <label for="DataFinal" class="mr-2">Data Final:</label>
                                        <input type="date" class="form-control" id="DataFinal" name="DataFinal" 
                                               value="<?= htmlspecialchars($dataFinal) ?>">
                                    </div>
                                    
                                    <div class="form-group mb-2">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="mdi mdi-magnify"></i> Filtrar
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title">
                                    <?= $nome_para_vendedor ?>: <?= htmlspecialchars($nomeVendedor, ENT_QUOTES, 'UTF-8') ?>
                                </h5>
                                <p class="text-muted">
                                    Período: <?= date('d/m/Y', strtotime($dataInicial)) ?> até <?= date('d/m/Y', strtotime($dataFinal)) ?>
                                </p>

                                <div class="table-responsive">
                                    <table id="tabelaVendas" class="table table-bordered table-hover table-sm" style="width:100%;">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Código Cliente</th>
                                                <th>Nome do Cliente</th>
                                                <th>Filial</th>
                                                <th>Requisição</th>
                                                <th>Fórmula</th>
                                                <th>Data/Hora</th>
                                                <th>Valor</th>
                                                <th>Ações</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if (!empty($detalhes)): ?>
                                                <?php foreach ($detalhes as $item): ?>
                                                    <tr>
                                                        <td><?= htmlspecialchars($item['COD_CLIENTE']) ?></td>
                                                        <td><?= htmlspecialchars($item['NOME_CLIENTE']) ?></td>
                                                        <td><?= htmlspecialchars($item['FILIAL']) ?></td>
                                                        <td><?= htmlspecialchars($item['REQUISICAO']) ?></td>
                                                        <td><?= htmlspecialchars($item['NUMEROFORMULA']) ?></td>
                                                        <td data-order="<?= $item['CADASTRO_DT'] ?>">
                                                            <?= date('d/m/Y H:i', strtotime($item['CADASTRO_DT'])) ?>
                                                        </td>
                                                        <td class="text-right" data-order="<?= $item['VALOR'] ?>">
                                                            R$ <?= number_format($item['VALOR'], 2, ',', '.') ?>
                                                        </td>
                                                        <td class="text-center">
                                                            <a href="detalhar_orcamento.php?codigo_atendimento=<?= $item['REQUISICAO'] ?>&filial=<?= $item['FILIAL'] ?>" class="btn btn-sm btn-info" title="Visualizar">
                                                                <i class="mdi mdi-eye"></i> Ver Itens
                                                            </a>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="8" class="text-center">Nenhum registro encontrado</td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                        <?php if (!empty($detalhes)): ?>
                                        <tfoot>
                                            <tr class="table-active">
                                                <th colspan="6" class="text-right">Total:</th>
                                                <th class="text-right">R$ <?= number_format($totalGeral, 2, ',', '.') ?></th>
                                                <th></th>
                                            </tr>
                                        </tfoot>
                                        <?php endif; ?>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                            </div>
                        </form>

                    </div>
                </div>
            </div>
        </div> <!-- end container -->
    </div>

    <!-- end wrapper -->

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

    <!-- Footer Start -->
    <?php include('../geral/footer.php'); ?>
    <!-- end Footer -->
    
    <!-- DataTables JS -->
    <link href="../../assets/plugins/datatables/dataTables.bootstrap4.min.css" rel="stylesheet" type="text/css" />
    <link href="../../assets/plugins/datatables/buttons.bootstrap4.min.css" rel="stylesheet" type="text/css" />
    
    <script src="../../assets/plugins/datatables/jquery.dataTables.min.js"></script>
    <script src="../../assets/plugins/datatables/dataTables.bootstrap4.min.js"></script>
    <script src="../../assets/plugins/datatables/dataTables.buttons.min.js"></script>
    <script src="../../assets/plugins/datatables/buttons.bootstrap4.min.js"></script>
    <script src="../../assets/plugins/datatables/jszip.min.js"></script>
    <script src="../../assets/plugins/datatables/pdfmake.min.js"></script>
    <script src="../../assets/plugins/datatables/vfs_fonts.js"></script>
    <script src="../../assets/plugins/datatables/buttons.html5.min.js"></script>
    <script src="../../assets/plugins/datatables/buttons.print.min.js"></script>
    
    <script>
    $(document).ready(function() {
        var table = $('#tabelaVendas').DataTable({
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.10.25/i18n/Portuguese-Brasil.json"
            },
            "order": [[5, "desc"]], // Ordena por data (coluna 5) decrescente
            "pageLength": 25,
            "dom": '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6 text-right"f>>rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
            "buttons": [
                {
                    extend: 'excel',
                    text: '<i class="mdi mdi-file-excel"></i> Excel',
                    className: 'btn btn-success btn-sm',
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4, 5, 6]
                    }
                },
                {
                    extend: 'pdf',
                    text: '<i class="mdi mdi-file-pdf"></i> PDF',
                    className: 'btn btn-danger btn-sm',
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4, 5, 6]
                    },
                    customize: function(doc) {
                        doc.defaultStyle.fontSize = 8;
                        doc.styles.tableHeader.fontSize = 9;
                        doc.pageMargins = [20, 30, 20, 30];
                    }
                },
                {
                    extend: 'print',
                    text: '<i class="mdi mdi-printer"></i> Imprimir',
                    className: 'btn btn-info btn-sm',
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4, 5, 6]
                    }
                }
            ]
        });
    });
    </script>

    <?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>
</body>

</html>

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

<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>
    // Configuração da tabela DataTables
    $.fn.dataTable.ext.type.order['currency-pre'] = function(d) {
        return parseFloat(d.replace(/[^\d,-]/g, '').replace(',', '.'));
    };

    $(document).ready(function() {
        var tableConfig = {
            "language": {
                "url": "https://cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json"
            },
            "order": [
                [0, "asc"],  // Ordena por filial
                [1, "asc"]   // Depois por número do orçamento
            ],
            "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>>',
            "ordering": true,
            "pageLength": 25,
            "responsive": true
        };

        // Se estiver visualizando um orçamento específico, remove a coluna de ações
        <?php if (!empty($orcamentoId)): ?>
            tableConfig.columnDefs = [
                { "type": "num", "targets": [0, 1] },
                { "type": "date", "targets": 2 },
                { "type": "currency", "targets": [11, 12] }
            ];
        <?php else: ?>
            tableConfig.columnDefs = [
                { "type": "num", "targets": [0, 1] },
                { "type": "date", "targets": 2 },
                { "type": "currency", "targets": [11, 12] },
                { "orderable": false, "targets": 13 } // Desabilita ordenação na coluna de ações
            ];
        <?php endif; ?>

        var tabela = $('#minhaTabela').DataTable(tableConfig);

        // Remova a classe que indica que a ordenação é aplicada
        $('#minhaTabela .sorting').removeClass('sorting');
    });
</script>
<style>
    #minhaTabela_length label,
    #minhaTabela_info {
        margin: 0 !important;
        padding: 0 !important;
        align-items: center;
    }
</style>