<?php
require_once 'includes/verificar_permissao.php';
verificarPermissao(__FILE__);
?>
<?php
require_once 'includes/config.php';
require_once 'includes/auth.php';

$pageTitle = "Provas";
require_once 'includes/header.php';
require_once 'config/database.php';
?>

<div class="wrapper">
    <!-- Sidebar -->
    <?php require_once 'includes/sidebar.php'; ?>

    <!-- Content -->
    <div id="content">
        <!-- Navbar -->
        <nav class="navbar navbar-expand-lg bg-white">
            <div class="container-fluid">
                <h2 class="navbar-title">Provas</h2>
                <div class="ms-auto">
                </div>
            </div>
        </nav>

        <div class="container-fluid">
            <!-- Filtros -->
            <div class="row mb-4">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body">
                            <form id="filtroForm" class="row g-3">
                                <div class="col-md-3">
                                    <label for="dataInicio" class="form-label">Data Início</label>
                                    <input type="date" class="form-control" id="dataInicio" name="dataInicio">
                                </div>
                                <div class="col-md-3">
                                    <label for="dataFim" class="form-label">Data Fim</label>
                                    <input type="date" class="form-control" id="dataFim" name="dataFim">
                                </div>
                                <div class="col-md-4">
                                    <label for="cliente" class="form-label">Cliente</label>
                                    <select class="form-select" id="cliente" name="cliente">
                                        <option value="">Todos</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Listagem de Provas -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Data</th>
                                            <th>Cliente</th>
                                            <th>Itens</th>
                                            <th>Valor Total</th>
                                            <th>Ações</th>
                                        </tr>
                                    </thead>
                                    <tbody id="provasTableBody">
                                        <!-- Dados serão carregados via JavaScript -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal de Confirmação -->
<div class="modal fade" id="confirmacaoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirmação</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="confirmacaoMensagem"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="confirmarAcao">Confirmar</button>
            </div>
        </div>
    </div>
</div>

<!-- Toast para mensagens -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="toast" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="d-flex">
            <div class="toast-body"></div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Carregar clientes no select
    function carregarClientes() {
        $.get('actions/get_clientes.php', function(response) {
            if (response.success) {
                const select = $('#cliente');
                response.data.forEach(cliente => {
                    select.append(new Option(cliente.nome, cliente.id));
                });
            }
        });
    }

    // Carregar provas
    function carregarProvas(filtros = {}) {
        $.get('actions/get_provas.php', filtros, function(response) {
            if (response.success) {
                const tbody = $('#provasTableBody');
                tbody.empty();

                response.data.forEach(prova => {
                    const row = $('<tr>');
                    row.append($('<td>').text(formatarData(prova.created_at)));
                    row.append($('<td>').text(prova.cliente_nome));
                    row.append($('<td>').text(prova.itens.map(item => 
                        `${item.quantidade}x ${item.produto_nome} (${item.tamanho})`
                    ).join(', ')));
                    row.append($('<td>').text(formatarMoeda(prova.valor_total)));
                    
                    const btnGroup = $('<td>').append(
                        $('<div>').addClass('btn-group').append(
                            $('<button>')
                                .addClass('btn btn-sm btn-warning')
                                .text('Devolver')
                                .on('click', () => confirmarDevolucao(prova.id)),
                            $('<button>')
                                .addClass('btn btn-sm btn-success')
                                .text('Finalizar Venda')
                                .on('click', () => finalizarVenda(prova.id))
                        )
                    );
                    row.append(btnGroup);
                    
                    tbody.append(row);
                });
            }
        });
    }

    // Formatar data
    function formatarData(data) {
        return new Date(data).toLocaleDateString('pt-BR');
    }

    // Formatar moeda
    function formatarMoeda(valor) {
        return new Intl.NumberFormat('pt-BR', {
            style: 'currency',
            currency: 'BRL'
        }).format(valor);
    }

    // Confirmar devolução
    function confirmarDevolucao(provaId) {
        $('#confirmacaoMensagem').text('Deseja realmente devolver os itens desta prova para o estoque?');
        $('#confirmarAcao').off('click').on('click', () => devolverProva(provaId));
        $('#confirmacaoModal').modal('show');
    }

    // Devolver prova
    function devolverProva(provaId) {
        $.post('actions/devolver_prova.php', { prova_id: provaId })
            .done(function(response) {
                $('#confirmacaoModal').modal('hide');
                
                const toast = $('#toast');
                toast.removeClass('bg-success bg-danger')
                    .addClass(response.success ? 'bg-success' : 'bg-danger');
                
                $('.toast-body').text(response.message);
                bootstrap.Toast.getOrCreateInstance(toast).show();

                if (response.success) {
                    carregarProvas(getFilterValues());
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                $('#confirmacaoModal').modal('hide');
                
                const toast = $('#toast');
                toast.removeClass('bg-success bg-danger').addClass('bg-danger');
                
                let errorMessage = 'Erro ao devolver itens: ';
                if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
                    errorMessage += jqXHR.responseJSON.message;
                } else {
                    errorMessage += textStatus;
                }
                
                $('.toast-body').text(errorMessage);
                bootstrap.Toast.getOrCreateInstance(toast).show();
            });
    }

    // Finalizar venda
    function finalizarVenda(provaId) {
        window.location.href = `pdv.php?prova_id=${provaId}&tipo=venda`;
    }

    // Obter valores dos filtros
    function getFilterValues() {
        return {
            dataInicio: $('#dataInicio').val(),
            dataFim: $('#dataFim').val(),
            cliente: $('#cliente').val()
        };
    }

    // Event Listeners
    $('#filtroForm').on('submit', function(e) {
        e.preventDefault();
        carregarProvas(getFilterValues());
    });

    // Inicialização
    carregarClientes();
    carregarProvas();
});
</script>

<?php require_once 'includes/footer.php'; ?>