@extends('layouts.app')

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

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

            <div class="mb-3">
                <label class="form-label">Cliente</label>
                <select name="cliente_id" class="form-control" required>
                    @foreach($clientes as $cliente)
                        <option value="{{ $cliente->id }}"
                            {{ $cotizacion->cliente_id == $cliente->id ? 'selected' : '' }}>
                            {{ $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>
                    @foreach($cotizacion->items as $item)
                        <tr>
                            <td>
                                <select name="productos[][producto_id]" class="form-control producto_select" required>
                                    <option value="">Seleccione producto</option>
                                    @foreach($productos as $p)
                                        <option value="{{ $p->id }}" data-price="{{ $p->precio }}"
                                            {{ $item->producto_id == $p->id ? 'selected' : '' }}>
                                            {{ $p->nombre }}
                                        </option>
                                    @endforeach
                                </select>
                            </td>
                            <td><input type="number" name="productos[][cantidad]" value="{{ $item->cantidad }}" class="form-control cantidad" min="1" required></td>
                            <td><input type="number" name="productos[][precio_unitario]" value="{{ $item->precio_unitario }}" class="form-control precio_unitario" step="0.01" required></td>
                            <td class="total">{{ $item->total }}</td>
                            <td><button type="button" class="btn btn-danger btn-sm remove_row">-</button></td>
                        </tr>
                    @endforeach
                </tbody>
            </table>

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

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

@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.querySelectorAll('.remove_row').forEach(btn => {
    btn.addEventListener('click', function(){
        this.closest('tr').remove();
        recalcTotals();
    });
});

document.querySelectorAll('.cantidad, .precio_unitario, .producto_select').forEach(input => {
    input.addEventListener('input', recalcTotals);
});

document.querySelectorAll('.producto_select').forEach(select => {
    select.addEventListener('change', function(){
        let price = parseFloat(this.selectedOptions[0].dataset.price || 0);
        this.closest('tr').querySelector('.precio_unitario').value = price.toFixed(2);
        recalcTotals();
    });
});

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
