@extends('layouts.app')
@section('title', 'Edit ' . $invoice->invoice_number)
@section('page-title', 'Edit Invoice')

@push('styles')
<style>
    .form-section { background:white; border-radius:12px; box-shadow:0 1px 3px rgba(0,0,0,0.07); padding:1.5rem; margin-bottom:1.25rem; }
    .form-section-title { font-size:0.75rem; font-weight:700; text-transform:uppercase; letter-spacing:0.07em; color:#94a3b8; margin-bottom:1.25rem; }
    .line-item-row { background:#f8fafc; border-radius:8px; padding:0.75rem; margin-bottom:0.5rem; border:1px solid #e2e8f0; }
    .total-row { display:flex; justify-content:space-between; padding:0.4rem 0; font-size:0.9rem; }
    .total-row.grand { font-size:1.1rem; font-weight:700; color:#1e293b; border-top:2px solid #e2e8f0; padding-top:0.75rem; margin-top:0.5rem; }
    .remove-item { width:28px;height:28px;border:none;background:none;color:#94a3b8;border-radius:6px;display:flex;align-items:center;justify-content:center;cursor:pointer;flex-shrink:0; }
    .remove-item:hover { background:#fee2e2;color:#dc2626; }
    .form-control:focus, .form-select:focus { border-color:#00a651;box-shadow:0 0 0 0.2rem rgba(0,166,81,0.15); }
    .calculated { background:#f0fdf4!important;font-weight:600;color:#15803d; }
</style>
@endpush

@section('content')

<div class="d-flex align-items-center gap-3 mb-4">
    <a href="{{ route('invoices.show', $invoice) }}" class="btn btn-sm btn-light">
        <i class="bi bi-arrow-left"></i>
    </a>
    <div>
        <h5 class="fw-700 mb-0" style="color:#1e293b;">Edit {{ $invoice->invoice_number }}</h5>
        <small class="text-muted">Draft invoice — changes saved immediately</small>
    </div>
</div>

<form method="POST" action="{{ route('invoices.update', $invoice) }}" id="invoiceForm" novalidate>
@csrf @method('PUT')

<div class="row g-3">
    <div class="col-lg-8">
        <div class="form-section">
            <div class="form-section-title"><i class="bi bi-person me-1"></i>Invoice Details</div>
            <div class="row g-3">
                <div class="col-sm-12">
                    <label class="form-label fw-500">Client <span class="text-danger">*</span></label>
                    <select name="client_id" id="clientSelect" class="form-select" required>
                        <option value="">— Select a client —</option>
                        @foreach($clients as $client)
                            <option value="{{ $client->id }}" {{ old('client_id', $invoice->client_id) == $client->id ? 'selected' : '' }}>
                                {{ $client->display_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-sm-4">
                    <label class="form-label fw-500">Issue Date <span class="text-danger">*</span></label>
                    <input type="date" name="issue_date" class="form-control"
                           value="{{ old('issue_date', $invoice->issue_date->format('Y-m-d')) }}" required>
                </div>
                <div class="col-sm-4">
                    <label class="form-label fw-500">Due Date <span class="text-danger">*</span></label>
                    <input type="date" name="due_date" id="dueDate" class="form-control"
                           value="{{ old('due_date', $invoice->due_date->format('Y-m-d')) }}" required>
                </div>
                <div class="col-sm-4">
                    <label class="form-label fw-500">VAT Rate (%)</label>
                    <input type="number" name="vat_rate" id="vatRate" class="form-control"
                           value="{{ old('vat_rate', $invoice->vat_rate) }}" step="0.1" min="0" max="100">
                </div>
            </div>
        </div>

        <div class="form-section">
            <div class="d-flex align-items-center justify-content-between mb-3">
                <div class="form-section-title mb-0"><i class="bi bi-list-ul me-1"></i>Line Items</div>
                <button type="button" id="addItemBtn" class="btn btn-sm" style="background:#f0fdf4;color:#16a34a;border:1px solid #bbf7d0;font-weight:600;">
                    <i class="bi bi-plus-lg me-1"></i>Add Item
                </button>
            </div>
            <div id="lineItems"></div>
        </div>

        <div class="form-section">
            <div class="form-section-title"><i class="bi bi-chat-left-text me-1"></i>Notes</div>
            <textarea name="notes" rows="3" class="form-control"
                      placeholder="Payment terms, notes...">{{ old('notes', $invoice->notes) }}</textarea>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="form-section">
            <div class="form-section-title"><i class="bi bi-calculator me-1"></i>Summary</div>
            <div class="total-row"><span class="text-muted">Subtotal</span><span id="displaySubtotal">₦0.00</span></div>
            <div class="total-row"><span class="text-muted">VAT (<span id="displayVatRate">7.5</span>%)</span><span id="displayVat">₦0.00</span></div>
            <div class="total-row">
                <span class="text-muted">Discount</span>
                <div class="d-flex align-items-center gap-1">
                    <span>₦</span>
                    <input type="number" name="discount" id="discountInput" class="form-control form-control-sm text-end"
                           style="width:90px;" value="{{ old('discount', $invoice->discount) }}" min="0" step="0.01">
                </div>
            </div>
            <div class="total-row grand">
                <span>Total</span>
                <span id="displayTotal" style="color:#00a651;">₦0.00</span>
            </div>
        </div>

        <div class="form-section">
            <div class="form-section-title"><i class="bi bi-floppy me-1"></i>Save</div>
            <div class="d-grid gap-2">
                <button type="submit" class="btn fw-600" style="background:#00a651;color:white;">
                    <i class="bi bi-check-lg me-2"></i>Save Changes
                </button>
                <a href="{{ route('invoices.show', $invoice) }}" class="btn btn-outline-secondary fw-600">
                    Cancel
                </a>
            </div>
        </div>
    </div>
</div>
</form>

@endsection

@push('scripts')
<script>
let itemCount = 0;

function createItemRow(desc = '', qty = 1, price = 0) {
    const idx   = itemCount++;
    const total = (qty * price).toFixed(2);
    const row   = document.createElement('div');
    row.className = 'line-item-row d-flex gap-2 align-items-start';
    row.innerHTML = `
        <div class="flex-grow-1">
            <input type="text" name="items[${idx}][description]" class="form-control form-control-sm mb-1"
                   placeholder="Description" value="${desc}" required>
            <div class="d-flex gap-2">
                <input type="number" name="items[${idx}][quantity]"    class="form-control form-control-sm item-qty"   placeholder="Qty"    value="${qty}"   min="0.01" step="0.01" style="flex:1;" required>
                <input type="number" name="items[${idx}][unit_price]"  class="form-control form-control-sm item-price" placeholder="Price"  value="${price}" min="0"    step="0.01" style="flex:2;" required>
                <input type="number" name="items[${idx}][total]"       class="form-control form-control-sm item-total calculated" value="${total}" readonly tabindex="-1" style="flex:2;">
            </div>
        </div>
        <button type="button" class="remove-item mt-1"><i class="bi bi-trash3"></i></button>
    `;
    row.querySelector('.remove-item').addEventListener('click', () => { row.remove(); recalculate(); });
    row.querySelectorAll('.item-qty, .item-price').forEach(i => {
        i.addEventListener('input', () => {
            const q = parseFloat(row.querySelector('.item-qty').value)   || 0;
            const p = parseFloat(row.querySelector('.item-price').value) || 0;
            row.querySelector('.item-total').value = (q * p).toFixed(2);
            recalculate();
        });
    });
    return row;
}

function recalculate() {
    let subtotal = 0;
    document.querySelectorAll('.item-total').forEach(el => subtotal += parseFloat(el.value) || 0);
    const vatRate  = parseFloat(document.getElementById('vatRate').value) || 0;
    const discount = parseFloat(document.getElementById('discountInput').value) || 0;
    const vat      = subtotal * (vatRate / 100);
    const total    = Math.max(0, subtotal + vat - discount);
    document.getElementById('displaySubtotal').textContent  = '₦' + subtotal.toLocaleString('en-NG', {minimumFractionDigits:2});
    document.getElementById('displayVat').textContent       = '₦' + vat.toLocaleString('en-NG', {minimumFractionDigits:2});
    document.getElementById('displayTotal').textContent     = '₦' + total.toLocaleString('en-NG', {minimumFractionDigits:2});
    document.getElementById('displayVatRate').textContent   = vatRate;
}

document.getElementById('addItemBtn').addEventListener('click', () => {
    document.getElementById('lineItems').appendChild(createItemRow());
    recalculate();
});
document.getElementById('vatRate').addEventListener('input', recalculate);
document.getElementById('discountInput').addEventListener('input', recalculate);

// Pre-fill existing items from database
window.addEventListener('DOMContentLoaded', () => {
    const existingItems = @json($invoice->items);
    existingItems.forEach(item => {
        document.getElementById('lineItems').appendChild(
            createItemRow(item.description, item.quantity, item.unit_price)
        );
    });
    recalculate();
});
</script>
@endpush
