@extends('layouts.app')
@section('title', 'New Invoice')
@section('page-title', 'New 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; }
    .line-item-row:hover { border-color:#cbd5e1; }
    .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.index') }}" class="btn btn-sm btn-light">
        <i class="bi bi-arrow-left"></i>
    </a>
    <div>
        <h5 class="fw-700 mb-0" style="color:#1e293b;">Create New Invoice</h5>
        <small class="text-muted">Next number: <strong>{{ auth()->user()->invoice_prefix }}-{{ str_pad(auth()->user()->invoice_counter + 1, 4, '0', STR_PAD_LEFT) }}</strong></small>
    </div>
</div>

<form method="POST" action="{{ route('invoices.store') }}" id="invoiceForm" novalidate>
@csrf

<div class="row g-3">
    {{-- LEFT COLUMN --}}
    <div class="col-lg-8">

        {{-- Client & Dates --}}
        <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>
                    <div class="input-group">
                        <select name="client_id" id="clientSelect" class="form-select @error('client_id') is-invalid @enderror" required>
                            <option value="">— Select a client —</option>
                            @foreach($clients as $client)
                                <option value="{{ $client->id }}" {{ old('client_id') == $client->id ? 'selected' : '' }}>
                                    {{ $client->display_name }}
                                    @if($client->email) — {{ $client->email }} @endif
                                </option>
                            @endforeach
                        </select>
                        <a href="{{ route('clients.create') }}" class="btn btn-outline-secondary" title="Add new client" target="_blank">
                            <i class="bi bi-plus-lg"></i>
                        </a>
                    </div>
                    @if($clients->isEmpty())
                        <div class="form-text text-warning">
                            <i class="bi bi-exclamation-triangle me-1"></i>
                            No clients yet. <a href="{{ route('clients.create') }}" target="_blank">Add a client first</a>.
                        </div>
                    @endif
                </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 @error('issue_date') is-invalid @enderror"
                           value="{{ old('issue_date', date('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 @error('due_date') is-invalid @enderror"
                           value="{{ old('due_date', date('Y-m-d', strtotime('+' . auth()->user()->payment_terms . ' days'))) }}" 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', 7.5) }}" step="0.1" min="0" max="100">
                </div>
            </div>
        </div>

        {{-- Line Items --}}
        <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>

            {{-- Header row (desktop) --}}
            <div class="d-none d-md-flex gap-2 mb-2 px-1" style="font-size:0.72rem;font-weight:600;color:#94a3b8;text-transform:uppercase;letter-spacing:0.05em;">
                <div style="flex:3;">Description</div>
                <div style="width:80px;text-align:right;">Qty</div>
                <div style="width:120px;text-align:right;">Unit Price (₦)</div>
                <div style="width:120px;text-align:right;">Total (₦)</div>
                <div style="width:28px;"></div>
            </div>

            <div id="lineItems">
                {{-- Rows injected by JS --}}
            </div>

            <div id="noItemsMsg" class="text-center py-3 text-muted small d-none">
                <i class="bi bi-plus-circle me-1"></i>Click "Add Item" to add your first line item
            </div>
        </div>

        {{-- Notes --}}
        <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, thank you message, bank details...">{{ old('notes', auth()->user()->default_invoice_notes) }}</textarea>
        </div>

    </div>

    {{-- RIGHT COLUMN — Totals + Actions --}}
    <div class="col-lg-4">

        {{-- Totals --}}
        <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" class="fw-500">₦0.00</span>
            </div>
            <div class="total-row">
                <span class="text-muted">VAT (<span id="displayVatRate">7.5</span>%)</span>
                <span id="displayVat" class="fw-500">₦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', 0) }}"
                           min="0" step="0.01" placeholder="0.00">
                </div>
            </div>
            <div class="total-row grand">
                <span>Total</span>
                <span id="displayTotal" style="color:#00a651;">₦0.00</span>
            </div>
        </div>

        {{-- Actions --}}
        <div class="form-section">
            <div class="form-section-title"><i class="bi bi-send me-1"></i>Save As</div>
            <div class="d-grid gap-2">
                <button type="submit" name="status" value="draft"
                        class="btn btn-outline-secondary fw-600">
                    <i class="bi bi-file-earmark me-2"></i>Save as Draft
                </button>
                <button type="submit" name="status" value="sent"
                        class="btn fw-600" style="background:#00a651;color:white;"
                        {{ $clients->isEmpty() ? 'disabled' : '' }}>
                    <i class="bi bi-send me-2"></i>Save & Send to Client
                </button>
            </div>
            @if($clients->isEmpty())
                <p class="text-muted small mt-2 mb-0">Add a client first to send invoices.</p>
            @endif
        </div>

    </div>
</div>

</form>
@endsection

@push('scripts')
<script>
// ── Line item template
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.dataset.index = idx;
    row.innerHTML = `
        <div class="flex-grow-1">
            <input type="text"
                   name="items[${idx}][description]"
                   class="form-control form-control-sm mb-1"
                   placeholder="Description of service or product"
                   value="${desc}" required>
            <div class="d-flex gap-2">
                <div style="flex:1;">
                    <label class="d-md-none" style="font-size:0.72rem;color:#94a3b8;">Qty</label>
                    <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" required>
                </div>
                <div style="flex:2;">
                    <label class="d-md-none" style="font-size:0.72rem;color:#94a3b8;">Unit Price (₦)</label>
                    <input type="number"
                           name="items[${idx}][unit_price]"
                           class="form-control form-control-sm item-price"
                           placeholder="0.00" value="${price}"
                           min="0" step="0.01" required>
                </div>
                <div style="flex:2;">
                    <label class="d-md-none" style="font-size:0.72rem;color:#94a3b8;">Total (₦)</label>
                    <input type="number"
                           name="items[${idx}][total]"
                           class="form-control form-control-sm item-total calculated"
                           value="${total}" readonly tabindex="-1">
                </div>
            </div>
        </div>
        <button type="button" class="remove-item mt-1" title="Remove item">
            <i class="bi bi-trash3"></i>
        </button>
    `;

    // Remove button
    row.querySelector('.remove-item').addEventListener('click', () => {
        row.remove();
        recalculate();
        toggleNoItems();
    });

    // Live calculation on qty/price change
    row.querySelectorAll('.item-qty, .item-price').forEach(input => {
        input.addEventListener('input', () => {
            const qty   = parseFloat(row.querySelector('.item-qty').value)   || 0;
            const price = parseFloat(row.querySelector('.item-price').value) || 0;
            row.querySelector('.item-total').value = (qty * price).toFixed(2);
            recalculate();
        });
    });

    return row;
}

function toggleNoItems() {
    const rows = document.querySelectorAll('#lineItems .line-item-row');
    document.getElementById('noItemsMsg').classList.toggle('d-none', rows.length > 0);
}

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;
}

// ── Add item button
document.getElementById('addItemBtn').addEventListener('click', () => {
    const row = createItemRow();
    document.getElementById('lineItems').appendChild(row);
    toggleNoItems();
    row.querySelector('input[name*="description"]').focus();
});

// ── VAT rate and discount live update
document.getElementById('vatRate').addEventListener('input', recalculate);
document.getElementById('discountInput').addEventListener('input', recalculate);

// ── Form validation before submit
document.getElementById('invoiceForm').addEventListener('submit', function(e) {
    const rows = document.querySelectorAll('#lineItems .line-item-row');
    if (rows.length === 0) {
        e.preventDefault();
        Swal.fire({
            icon: 'warning',
            title: 'No line items',
            text: 'Please add at least one line item to the invoice.',
            confirmButtonColor: '#00a651',
        });
        return;
    }

    if (!document.getElementById('clientSelect').value) {
        e.preventDefault();
        Swal.fire({
            icon: 'warning',
            title: 'No client selected',
            text: 'Please select a client for this invoice.',
            confirmButtonColor: '#00a651',
        });
    }
});

// ── Init: add one empty row on page load
window.addEventListener('DOMContentLoaded', () => {
    @if(old('items'))
        @foreach(old('items', []) as $i => $item)
            document.getElementById('lineItems').appendChild(
                createItemRow(
                    `{{ addslashes($item['description'] ?? '') }}`,
                    {{ $item['quantity'] ?? 1 }},
                    {{ $item['unit_price'] ?? 0 }}
                )
            );
        @endforeach
    @else
        document.getElementById('lineItems').appendChild(createItemRow());
    @endif
    toggleNoItems();
    recalculate();
});
</script>
@endpush
