@extends('layouts.app')

@section('content')
<div class="container">
    <h2>Nueva Cotización</h2>

    <div class="card p-3">
        <form action="{{ route('cotizaciones.store') }}" method="POST">
            @csrf

            <div class="mb-3">
                <label class="form-label">Cliente</label>
                <select name="cliente_id" class="form-control" required>
                    <option value="">Seleccione cliente</option>
                    @foreach($clientes as $cliente)
                        <option value="{{ $cliente->id }}">{{ $cliente->nombre }} ({{ $cliente->email }})</option>
                    @endforeach
                </select>
            </div>

            <h5>Productos</h5>
            <table class="table table-bordered" id="productos_table">
                <thead>
                    <tr>
                        <th>Producto</th>
                        <th>Cantidad</th>
                        <th>Precio Unitario</th>
                        <th>Total</th>
                        <th><button type="button" class="btn btn-success btn-sm" id="add_row">+</button></th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Fila inicial vacía -->
                </tbody>
            </table>

            <div class="mb-3 text-end">
                <strong>Subtotal: $<span id="subtotal">0.00</span></strong><br>
                <strong>IVA (16%): $<span id="iva">0.00</span></strong><br>
                <strong>Total: $<span id="total">0.00</span></strong>
            </div>

            <button class="btn btn-primary">Guardar Cotización</button>
            <a href="{{ route('cotizaciones.index') }}" class="btn btn-secondary">Cancelar</a>
        </form>
    </div>
</div>

<!-- Scripts para agregar filas dinámicas -->
@push('scripts')
<script>
let productos = @json($productos);

function recalcTotals() {
    let subtotal = 0;
    document.querySelectorAll('#productos_table tbody tr').forEach(tr => {
        let qty = parseFloat(tr.querySelector('.cantidad').value) || 0;
        let price = parseFloat(tr.querySelector('.precio_unitario').value) || 0;
        let total = qty * price;
        tr.querySelector('.total').textContent = total.toFixed(2);
        subtotal += total;
    });
    let iva = subtotal * 0.16;
    document.getElementById('subtotal').textContent = subtotal.toFixed(2);
    document.getElementById('iva').textContent = iva.toFixed(2);
    document.getElementById('total').textContent = (subtotal + iva).toFixed(2);
}

document.getElementById('add_row').addEventListener('click', function(){
    let tr = document.createElement('tr');
    tr.innerHTML = `
        <td>
            <select name="productos[][producto_id]" class="form-control producto_select" required>
                <option value="">Seleccione producto</option>
                ${productos.map(p => `<option value="${p.id}" data-price="${p.precio}">${p.nombre}</option>`).join('')}
            </select>
        </td>
        <td><input type="number" name="productos[][cantidad]" value="1" class="form-control cantidad" min="1" required></td>
        <td><input type="number" name="productos[][precio_unitario]" value="0" class="form-control precio_unitario" step="0.01" required></td>
        <td class="total">0.00</td>
        <td><button type="button" class="btn btn-danger btn-sm remove_row">-</button></td>
    `;
    document.querySelector('#productos_table tbody').appendChild(tr);

    tr.querySelector('.remove_row').addEventListener('click', function(){
        tr.remove();
        recalcTotals();
    });

    tr.querySelector('.cantidad').addEventListener('input', recalcTotals);
    tr.querySelector('.precio_unitario').addEventListener('input', recalcTotals);
    tr.querySelector('.producto_select').addEventListener('change', function(){
        let price = parseFloat(this.selectedOptions[0].dataset.price || 0);
        tr.querySelector('.precio_unitario').value = price.toFixed(2);
        recalcTotals();
    });
});
</script>
@endpush
@endsection
