@extends('adminlte::page')

@section('title', 'Entradas de Estoque')

@section('content_header')
<h1>Histórico de Entradas</h1>
@stop

@section('content')

{{-- 🔍 FILTROS --}}
<form method="GET" action="{{ route('estoque.index') }}" class="row g-3 mb-3 align-items-end">

    <div class="col-md-3">
        <label>Buscar Produto</label>
        <input type="text" name="produto" value="{{ request('produto') }}" class="form-control" placeholder="Nome do produto">
    </div>

    <div class="col-md-2">
        <label>Data Início</label>
        <input type="date" name="data_inicio" value="{{ request('data_inicio') }}" class="form-control">
    </div>

    <div class="col-md-2">
        <label>Data Fim</label>
        <input type="date" name="data_fim" value="{{ request('data_fim') }}" class="form-control">
    </div>

    <div class="col-md-2 d-grid">
        <button class="btn btn-primary w-100">🔍 Filtrar</button>
    </div>

    <div class="col-md-2 d-grid">
        <a href="{{ route('estoque.exportarPDF', request()->all()) }}" class="btn btn-danger w-100">📄 PDF</a>
    </div>

    <div class="col-md-1 d-grid">
        <a href="{{ route('estoque.index') }}" class="btn btn-secondary w-100">↺ Limpar</a>
    </div>

</form>

{{-- ➕ NOVA ENTRADA --}}
<button class="btn btn-primary mb-3" id="btnNovaEntrada">➕ Nova Entrada</button>

{{-- 📋 TABELA --}}
<table class="table table-striped table-modern" id="tabelaEntradas">
    <thead>
        <tr>
            <th>Produto</th>
            <th>Quantidade</th>
            <th>Preço Compra</th>
            <th>Usuário</th>
            <th>Data</th>
            <th>Ações</th>
        </tr>
    </thead>
    <tbody>
        @foreach($entradas as $e)
        <tr>
            <td>{{ $e->nome_pro }}</td>
            <td>{{ $e->quantidade }}</td>
            <td>{{ number_format($e->preco_unitario,2) }} MT</td>
            <td>{{ trim($e->usuario ?? '') !== '' ? $e->usuario : 'Sistema' }}</td>
            <td>{{ date('d/m/Y H:i', strtotime($e->data)) }}</td>
            <td>
                <button class="btn btn-danger btn-sm btnDelete" data-id="{{ $e->id }}">❌ Remover</button>
            </td>
        </tr>
        @endforeach
    </tbody>
</table>

{{-- ========================= MODAL ENTRADA ========================= --}}
<div class="modal fade" 
     id="modalEntrada" 
     tabindex="-1"
     data-backdrop="static"
     data-keyboard="false">

    <div class="modal-dialog">
        <div class="modal-content p-3">

            <div class="modal-header">
                <h5 class="modal-title">Registrar Entrada</h5>
                <button class="btn-close" data-dismiss="modal"></button>
            </div>

            <div class="modal-body">

                <label class="mt-2">Produto</label>
                <select id="produto_codigo" class="form-control"></select>

                <label class="mt-2">Quantidade</label>
                <input type="number" id="quantidade" class="form-control" placeholder="Ex: 10">

                <label class="mt-2">Preço Compra</label>
                <input type="number" step="0.01" id="preco_unitario" class="form-control" placeholder="Ex: 50.00 MT">
            </div>

            <div class="modal-footer">
                <button class="btn btn-success w-100" id="btnSalvarEntrada">💾 Salvar</button>
            </div>

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

@stop

{{-- ========================= CSS ========================= --}}
@push('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" />

<style>
/* ==================== Inputs e Botões ==================== */
input.form-control, select.form-control {
    border-radius: 8px;
    transition: border-color 0.3s, box-shadow 0.3s;
}
input.form-control:focus, select.form-control:focus {
    border-color: #3B82F6;
    box-shadow: 0 0 8px rgba(59,130,246,0.4);
}

button.btn-primary, button.btn-secondary, button.btn-danger, #btnSalvarEntrada {
    border-radius: 8px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}
button.btn-primary:hover, button.btn-secondary:hover, button.btn-danger:hover, #btnSalvarEntrada:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(0,0,0,0.25);
}

/* ==================== Tabela ==================== */
.table-modern {
    width: 100% !important;
    border-collapse: separate !important;
    border-spacing: 0 8px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    font-size: 0.95rem;
}

.table-modern thead tr th {
    background-color: #121212;
    color: #fff;
    font-weight: 600;
    border: none !important;
    padding: 12px 15px;
    border-radius: 8px 8px 0 0;
}

.table-modern tbody tr {
    background-color: #ffffff;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    border-radius: 8px;
    margin-bottom: 10px;
    display: table-row;
}

.table-modern tbody tr td {
    border: none !important;
    padding: 12px 15px;
    vertical-align: middle;
}

/* ==================== Modal ==================== */
#modalEntrada .modal-content {
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

/* ==================== Responsividade ==================== */
@media (max-width: 576px) {
    .table-modern thead { display: none; }
    .table-modern tbody tr { display: block; margin-bottom: 20px; }
    .table-modern tbody tr td {
        display: flex;
        justify-content: space-between;
        padding: 8px 10px;
        border: none !important;
        font-size: 0.9rem;
    }
    .table-modern tbody tr td::before {
        content: attr(data-label);
        font-weight: 600;
        color: #555;
        flex-basis: 50%;
        text-align: left;
    }
}
</style>
@endpush

{{-- ========================= JAVASCRIPT ========================= --}}
@push('js')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
/* ------------ Abrir modal ------------ */
$("#btnNovaEntrada").click(() => {
    $("#produto_codigo").val(null).trigger('change');
    $("#quantidade").val('');
    $("#preco_unitario").val('');
    $("#modalEntrada").modal("show");
    setTimeout(() => $("#produto_codigo").select2("open"), 300);
});

/* ------------ Select2 com autocomplete ------------ */
$('#produto_codigo').select2({
    theme: "bootstrap-5",
    dropdownParent: $('#modalEntrada'),
    allowClear: true,
    placeholder: "Digite para buscar...",
    minimumInputLength: 1,
    ajax: {
        url: "{{ route('estoque.buscarProduto') }}",
        delay: 250,
        dataType: 'json',
        data: params => ({ q: params.term }),
        processResults: data => ({ results: data })
    }
}).on("select2:select", function(e){
    $("#preco_unitario").val(e.params.data.preco);
});

/* ------------ Salvar entrada ------------ */
$("#btnSalvarEntrada").click(function(){
    let btn = $(this);
    if(!$("#produto_codigo").val() || !$("#quantidade").val()){
        Swal.fire("⚠️ Atenção", "Preencha todos os campos!", "warning");
        return;
    }
    btn.prop("disabled", true).text("Salvando...");
    $.post("{{ route('estoque.store') }}", {
        produto_codigo: $("#produto_codigo").val(),
        quantidade: $("#quantidade").val(),
        preco_unitario: $("#preco_unitario").val(),
        _token: "{{ csrf_token() }}"
    }).done(res => {
        Swal.fire("✔ Sucesso", res.msg, "success").then(() => location.reload());
    }).fail(err => {
        Swal.fire("Erro", err.responseText, "error");
        btn.prop("disabled", false).text("💾 Salvar");
    });
});

/* ------------ Remover entrada ------------ */
$(".btnDelete").click(function(){
    let id = $(this).data("id");
    Swal.fire({
        title: "Excluir?",
        text: "Isso também descontará do estoque!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, remover"
    }).then(res => {
        if(res.isConfirmed){
            $.ajax({
                url: `{{ url('/estoque') }}/${id}`,
                type: "DELETE",
                data: { _token: "{{ csrf_token() }}" },
                success: function(res){
                    Swal.fire("Removido!", res.msg, "success")
                    .then(() => location.reload());
                }
            });
        }
    });
});
</script>
@endpush
