

<?php $__env->startSection('title', 'Caixa'); ?>

<?php $__env->startSection('content_header'); ?>
    <h1 class="titulo-caixa">💳 Caixa / Vendas</h1>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>


<style>

/* ===============================
   TIPOGRAFIA & RESET MODERNO
================================*/
body {
    font-family: "Inter", "Segoe UI", "Roboto", sans-serif !important;
    background: #f9fafb !important;
}

/* Título */
.titulo-caixa{
    font-weight: 700;
    letter-spacing: -0.5px;
    color: #111827;
    font-size: 28px;
}

/* ===============================
   INPUTS, SELECTS, BUTTONS
================================*/
input.form-control,
select.form-control {
    border-radius: 12px !important;
    padding: 12px !important;
    border: 1px solid #d1d5db !important;
    background: #fff !important;
    transition: 0.2s;
    color: #111827;
    font-weight: 500;
}

input.form-control:focus,
select.form-control:focus {
    border-color: #2563eb !important;
    box-shadow: 0 0 0 3px rgba(37,99,235,0.2) !important;
    outline: none;
}

/* Botões estilo Microsoft/Google */
.btn-modern{
    border-radius: 12px !important;
    font-weight: 600;
    transition: 0.25s;
    padding: 10px 14px !important;
    letter-spacing: -0.3px;
    border: none !important;
}

.btn-modern:hover{
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(0,0,0,0.10);
}

/* Botão de adicionar dentro do input */
#btnAdicionar{
    border-radius: 0 12px 12px 0 !important;
}

/* ===============================
   SELECT2 MODERNO
================================*/
.select2-container--bootstrap-5 .select2-selection{
    border-radius: 12px !important;
    padding: 6px 10px !important;
    border: 1px solid #d1d5db !important;
    background: #fff !important;
    color: #111827;
}

.select2-container--bootstrap-5 .select2-selection--single .select2-selection__placeholder {
    color: #9ca3af !important;
}

.select2-container--bootstrap-5 .select2-results__option--highlighted {
    background: #2563eb !important;
    color: #fff !important;
}

/* ===============================
   TABELA MODERNA
================================*/
#tabelaCarrinho{
    border-radius: 14px !important;
    overflow: hidden !important;
    background: white;
    box-shadow: 0 3px 14px rgba(0,0,0,0.07);
}

#tabelaCarrinho thead{
    background: #1f2937;
    color: #fff;
}

#tabelaCarrinho tbody tr{
    transition: .2s;
}

#tabelaCarrinho tbody tr:hover{
    background: #f3f4f6 !important;
}

/* Campos de quantidade */
.qtd-item{
    border-radius: 10px !important;
    text-align: center;
    font-weight: 600;
}

/* Total */
#totalGeral{
    font-size: 22px;
    font-weight: 700;
    color: #059669;
}

/* ===============================
   MODAL MODERNO
================================*/
.modal-content{
    border-radius: 20px !important;
    border: none !important;
    box-shadow: 0 10px 35px rgba(0,0,0,0.2);
}

.modal-header{
    background: #111827;
    color: #fff;
    border-radius: 20px 20px 0 0 !important;
    padding: 18px !important;
}

.modal-body input, 
.modal-body select{
    border-radius: 12px !important;
    padding: 12px !important;
    background: #fff !important;
    border: 1px solid #d1d5db !important;
    color: #111827 !important;
    font-weight: 500;
}

.modal-body label{
    font-weight: 600;
    color: #374151;
    margin-top: 10px;
    display: block;
}

/* ===============================
   SELECT MÉTODO DE PAGAMENTO VISÍVEL
================================*/
#metodoPagamento {
    background: #ffffff !important;
    border: 2px solid #d1d5db !important;
    color: #111827 !important;
    font-weight: 600 !important;
    border-radius: 12px !important;
    padding: 10px 38px 10px 16px !important; /* padding direito maior para a seta */
    font-size: 15px !important;
    appearance: none !important; /* Remove o estilo padrão da seta */
    -webkit-appearance: none !important;
    -moz-appearance: none !important;
    position: relative;
    background-image: url("data:image/svg+xml;utf8,<svg fill='%23111827' height='24' viewBox='0 0 24 24' width='24' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/></svg>");
    background-repeat: no-repeat;
    background-position: right 12px center;
    background-size: 16px 16px;
    cursor: pointer;
}

/* Para o hover/focus manter a sombra */
#metodoPagamento:focus {
    border-color: #2563eb !important;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.25) !important;
    outline: none;
}


#metodoPagamento option {
    background: #fff !important;
    color: #111827 !important;
    font-weight: 500;
    padding: 8px;
}

/* ===============================
   MODAL FOOTER
================================*/
.modal-footer{
    padding: 16px !important;
}

.btn-close-white {
    filter: brightness(0) invert(1);
}

/* ===============================
   SUAVIZAÇÕES GERAIS
================================*/
.table td, .table th {
    vertical-align: middle !important;
}

small.text-muted {
    font-size: 13px;
    color: #6b7280 !important;
}

</style>




<div class="row mb-3">
    <div class="col-md-6">
        <label>Pesquisar produto (código ou nome)</label>
        <div class="input-group">
            <select id="busca_produto" class="form-control"></select>
            <button class="btn btn-secondary btn-modern" id="btnAdicionar">
                <i class="fas fa-plus"></i> Adicionar
            </button>
        </div>
        <small class="text-muted">Digite e pressione ENTER.</small>
    </div>

    <div class="col-md-3"></div>

    <div class="col-md-3">
        <label>&nbsp;</label>
        <button class="btn btn-success w-100 btn-modern" id="btnFinalizar">
            Finalizar Venda
        </button>
    </div>
</div>

<div class="table-responsive">
    <table class="table table-bordered" id="tabelaCarrinho">
        <thead>
            <tr>
                <th>Código</th>
                <th>Produto</th>
                <th>Preço</th>
                <th>Quantidade</th>
                <th>Subtotal</th>
                <th style="width:80px">Ações</th>
            </tr>
        </thead>
        <tbody></tbody>
        <tfoot>
            <tr>
                <th colspan="4" class="text-end">Total:</th>
                <th id="totalGeral">0.00 MT</th>
                <th></th>
            </tr>
        </tfoot>
    </table>
</div>



<div class="modal fade" id="modalPagamento" tabindex="-1" data-backdrop="static" data-keyboard="false">
    
    <div class="modal-dialog modal-md">
        <div class="modal-content">

            <div class="modal-header">
                <h5 class="modal-title">Pagamento</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body">

                <p><strong>Total a pagar:</strong> 
                    <span id="pagamentoTotal" class="text-success fw-bold"></span>
                </p>

                <label>Método de Pagamento</label>
                <select id="metodoPagamento" class="form-control mb-3">
                    <option value="Dinheiro">💵 Dinheiro</option>
                    <option value="M-Pesa">📱 M-Pesa</option>
                    <option value="eMola">📱 eMola</option>
                    <option value="Cartão">💳 Cartão</option>
                </select>

                <label>Referência (se aplicável)</label>
                <input type="text" id="referenciaPagamento" class="form-control mb-3" placeholder="Código de transação">

                <label>Valor Recebido</label>
                <input type="number" id="valorRecebido" class="form-control mb-2">

                <label>Troco</label>
                <input type="text" id="valorTroco" class="form-control" readonly>

            </div>

            <div class="modal-footer">
                <button class="btn btn-secondary btn-modern" data-dismiss="modal">Cancelar</button>
                <button class="btn btn-success btn-modern" id="btnConfirmarPagamento" disabled>
                    Confirmar Pagamento
                </button>
            </div>

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

<?php $__env->stopSection(); ?>
<?php $__env->startPush('css'); ?>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<?php $__env->stopPush(); ?>

<?php $__env->startPush('js'); ?>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(function () {

    let carrinho = [];

    /* ============================================
       SELECT2 - Buscar Produto
    ============================================ */
    $('#busca_produto').select2({
        theme: "bootstrap-5",
        placeholder: "Digite para buscar...",
        minimumInputLength: 1,
        ajax: {
            url: "<?php echo e(route('caixa.searchProduct')); ?>",
            delay: 200,
            dataType: 'json',
            data: params => ({ q: params.term }),
            processResults: data => ({
                results: data.map(p => ({
                    id: p.id,
                    text: p.text,
                    produto: {
                        codigo: p.id,
                        nome: p.text,
                        preco: p.preco,
                        estoque: p.estoque
                    }
                }))
            })
        }
    }).on("select2:select", function(e){

        const p = e.params.data.produto;

        if (p.estoque <= 0) {
            Swal.fire("Sem estoque", "Este produto não pode ser adicionado.", "warning");
            return;
        }

        adicionarAoCarrinho({
            codigo: p.codigo,
            nome: p.nome,
            preco: p.preco,
            estoque: p.estoque
        });

        $('#busca_produto').val(null).trigger('change');
    });


    /* ============================================
       Adicionar ao Carrinho
    ============================================ */
    function adicionarAoCarrinho(p) {

        let existente = carrinho.find(i => i.codigo === p.codigo);

        if (existente) {

            if (existente.quant + 1 > existente.estoque) {
                Swal.fire("Estoque insuficiente", "Quantidade máxima atingida.", "error");
                return;
            }

            existente.quant += 1;

        } else {

            carrinho.push({
                codigo: p.codigo,
                nome: p.nome,
                preco: parseFloat(p.preco),
                quant: 1,             // AGORA INICIA COM 1 (CORRETO)
                estoque: p.estoque
            });
        }

        atualizarTabela();
    }



    /* ============================================
       Atualizar Tabela COMPLETA (mas sem recriar inputs)
    ============================================ */
    function atualizarTabela() {

        let tbody = $("#tabelaCarrinho tbody");
        tbody.empty();

        let total = 0;

        carrinho.forEach((item, idx) => {

            let subtotal = item.preco * item.quant;
            total += subtotal;

            tbody.append(`
                <tr data-idx="${idx}">
                    <td>${item.codigo}</td>
                    <td>${item.nome}</td>
                    <td>${item.preco.toFixed(2)} MT</td>
                    <td>
                        <input type="number" min="1" max="${item.estoque}"
                               value="${item.quant}"
                               class="form-control form-control-sm qtd-item">
                    </td>
                    <td class="subtotal">${subtotal.toFixed(2)} MT</td>
                    <td>
                        <button class="btn btn-danger btn-sm btn-remover">Remover</button>
                    </td>
                </tr>
            `);
        });

        $("#totalGeral").text(total.toFixed(2) + " MT");
    }


    /* ============================================
       Atualizar somente subtotal + total
       (SEM RECRIAR A TABELA)
    ============================================ */
    function atualizarTotais() {

        let total = 0;

        $("#tabelaCarrinho tbody tr").each(function(){

            let idx = $(this).data("idx");
            let item = carrinho[idx];
            let subtotal = item.preco * item.quant;

            $(this).find(".subtotal").text(subtotal.toFixed(2) + " MT");

            total += subtotal;
        });

        $("#totalGeral").text(total.toFixed(2) + " MT");
    }



    /* ============================================
       Alterar quantidade pelo input (SEM LOOPS DUPLOS)
    ============================================ */
    $(document).on("input", ".qtd-item", function(){

        let tr = $(this).closest("tr");
        let idx = tr.data("idx");
        let novaQuant = parseInt($(this).val());
        let estoque = carrinho[idx].estoque;

        if (isNaN(novaQuant) || novaQuant < 1) novaQuant = 1;
        if (novaQuant > estoque) {
            Swal.fire("Estoque insuficiente", "Máximo permitido: " + estoque, "error");
            novaQuant = estoque;
        }

        carrinho[idx].quant = novaQuant;

        atualizarTotais();   // NÃO RECRIA A TABELA
    });



    /* ============================================
       Remover Item
    ============================================ */
    $(document).on("click", ".btn-remover", function () {
        let idx = $(this).closest("tr").data("idx");
        carrinho.splice(idx, 1);
        atualizarTabela();
    });



    /* ============================================
       Finalizar → abrir modal
    ============================================ */
    $("#btnFinalizar").on("click", function () {

        if (!carrinho.length) {
            Swal.fire("Carrinho vazio", "Adicione itens!", "warning");
            return;
        }

        $("#pagamentoTotal").text($("#totalGeral").text());
        $("#valorRecebido").val("");
        $("#valorTroco").val("");
        $("#btnConfirmarPagamento").prop("disabled", true);

        $("#modalPagamento").modal("show");
    });



    /* ============================================
       Calcular troco
    ============================================ */
    $("#valorRecebido").on("input", function(){

        let total = parseFloat($("#pagamentoTotal").text());
        let recebido = parseFloat($(this).val());

        if (recebido >= total) {
            $("#valorTroco").val((recebido - total).toFixed(2));
            $("#btnConfirmarPagamento").prop("disabled", false);
        } else {
            $("#valorTroco").val("—");
            $("#btnConfirmarPagamento").prop("disabled", true);
        }

    });



    /* ============================================
       Confirmar Pagamento
    ============================================ */
    $("#btnConfirmarPagamento").on("click", function(){



        let payload = {
            itens: carrinho,
            metodo_pagamento: $("#metodoPagamento").val(),
            valor_recebido: parseFloat($("#valorRecebido").val()) || 0,
            troco: parseFloat($("#valorTroco").val()) || 0,
            referencia: $("#referenciaPagamento").val() || null
        };
        

        $(this).prop("disabled", true).text("Processando...");

        $.ajax({
            url: "<?php echo e(route('caixa.finalizarVenda')); ?>",
            method: "POST",
            contentType: "application/json",
            data: JSON.stringify(payload),
            headers: {
                "X-CSRF-TOKEN": "<?php echo e(csrf_token()); ?>"
            },

            success: function (res) {

                $("#modalPagamento").modal("hide");

                Swal.fire({
                    icon: "success",
                    title: "Venda Finalizada!",
                    text: `Código da venda: ${res.codigoVenda}`,
                    timer: 2500
                });

                carrinho = [];
                atualizarTabela();

                $("#btnConfirmarPagamento").prop("disabled", false).text("Confirmar Pagamento");
            },

            error: function (xhr) {
                Swal.fire("Erro", xhr.responseText, "error");
                $("#btnConfirmarPagamento").prop("disabled", false).text("Confirmar Pagamento");
            }
        });

    });

});
</script>

<?php $__env->stopPush(); ?>

<?php echo $__env->make('adminlte::page', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/churasqu/public_html/admin-panel/resources/views/caixa/index.blade.php ENDPATH**/ ?>