@extends('adminlte::page')

@section('content')
<div class="container">
    <h2>Create Invoice</h2>

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

        {{-- Invoice Fields --}}
        <div class="row">
            <div class="col-md-4 mb-3">
                <label>Invoice Number</label>
                <input type="text" name="invoice_number" class="form-control" required>
            </div>
            <div class="col-md-4 mb-3">
                <label>Invoice Date</label>
                <input type="date" name="invoice_date" class="form-control" required>
            </div>
            <div class="col-md-4 mb-3">
                <label>Customer</label>
                <select name="customer_id" class="form-control" required>
                    <option value="">-- Select Customer --</option>
                    @foreach($customers as $customer)
                        <option value="{{ $customer->id }}">{{ $customer->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>

        <div class="row">
            <div class="col-md-4 mb-3">
                <label>Customer Contact</label>
                <select name="customer_contact_id" class="form-control">
                    <option value="">-- Select Contact --</option>
                    @foreach($customerContacts as $contact)
                        <option value="{{ $contact->id }}">{{ $contact->name }} ({{ $contact->mobile1 }})</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-4 mb-3">
                <label>Quote</label>
                <select name="quote_id" class="form-control">
                    <option value="">-- Select Quote --</option>
                    @foreach($quotes as $quote)
                        <option value="{{ $quote->id }}">{{ $quote->quote_number }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-4 mb-3">
                <label>Project Site</label>
                <textarea name="project_site" class="form-control"></textarea>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6 mb-3">
                <label>Rental Start</label>
                <input type="date" name="rental_start" class="form-control">
            </div>
            <div class="col-md-6 mb-3">
                <label>Rental End</label>
                <input type="date" name="rental_end" class="form-control">
            </div>
        </div>

        {{-- Line Items --}}
        <h4 class="mt-4">Invoice Items</h4>
        <div id="items-container">
            <div class="item-row border rounded p-3 mb-3">
                <div class="row">
                    <div class="col-md-2">
                        <label>Item Code</label>
                        <select name="items[0][item_code]" class="form-control item-code-select" required>
                            <option value="">Select Item</option>
                            @foreach($items as $item)
                                <option value="{{ $item->code }}" data-description="{{ $item->description }}">{{ $item->code }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label>Description</label>
                        <textarea name="items[0][description]" class="form-control description-field" readonly></textarea>
                    </div>
                    <div class="col-md-2">
                        <label>Quantity</label>
                        <input type="number" name="items[0][quantity]" class="form-control quantity" step="any" required>
                    </div>
                    <div class="col-md-2">
                        <label>Unit Price</label>
                        <input type="number" name="items[0][unit_price]" class="form-control unit_price" step="any" required>
                    </div>
                    <div class="col-md-2">
                        <label>Duration</label>
                        <input type="number" name="items[0][duration]" class="form-control duration" value="1" required>
                    </div>
                    <div class="col-md-1">
                        <label>Unit</label>
                        <select name="items[0][duration_unit]" class="form-control">
                            <option value="day">Day</option>
                            <option value="week">Week</option>
                            <option value="month">Month</option>
                        </select>
                    </div>
                    <div class="col-md-1">
                        <label>Line Total</label>
                        <input type="number" name="items[0][line_total]" class="form-control line_total" readonly>
                    </div>
                    <div class="col-md-1">
                        <label>Tax</label>
                        <input type="number" name="items[0][tax]" class="form-control tax" step="0.01" value="0">
                    </div>
                    <div class="col-md-1">
                        <label>Total w/Tax</label>
                        <input type="number" name="items[0][line_total_with_tax]" class="form-control line_total_with_tax" readonly>
                    </div>
                </div>
            </div>
        </div>

        <button type="button" class="btn btn-sm btn-success mb-3" id="add-item">+ Add Item</button>

        {{-- Totals --}}
        <div class="row">
            <div class="col-md-4 offset-md-8">
                <label>Subtotal</label>
                <input type="number" step="0.01" name="subtotal" class="form-control" id="subtotal" readonly>
                <label>Discount</label>
                <input type="number" step="0.01" name="discount" class="form-control" id="discount" value="0">
                <label>Taxable Total</label>
                <input type="number" step="0.01" name="taxable_total" class="form-control" id="taxable_total" readonly>
                <label>Tax Total</label>
                <input type="number" step="0.01" name="tax_total" class="form-control" id="tax_total" readonly>
                <label>Total</label>
                <input type="number" step="0.01" name="total" class="form-control" id="total" readonly>
            </div>
        </div>

        <div class="mt-3">
            <button type="submit" class="btn btn-primary">Save Invoice</button>
        </div>
    </form>
</div>
@endsection

@section('js')
<script>
    let index = 1;

    function recalculate() {
        let subtotal = 0, taxTotal = 0;
        document.querySelectorAll('.item-row').forEach(row => {
            const qty = parseFloat(row.querySelector('.quantity')?.value || 0);
            const price = parseFloat(row.querySelector('.unit_price')?.value || 0);
            const duration = parseFloat(row.querySelector('.duration')?.value || 1);
            const tax = parseFloat(row.querySelector('.tax')?.value || 0);

            const lineTotal = qty * price * duration;
            const lineTotalWithTax = lineTotal + tax;

            row.querySelector('.line_total').value = lineTotal.toFixed(2);
            row.querySelector('.line_total_with_tax').value = lineTotalWithTax.toFixed(2);

            subtotal += lineTotal;
            taxTotal += tax;
        });

        const discount = parseFloat(document.getElementById('discount').value || 0);
        const taxable = subtotal - discount;
        const total = taxable + taxTotal;

        document.getElementById('subtotal').value = subtotal.toFixed(2);
        document.getElementById('taxable_total').value = taxable.toFixed(2);
        document.getElementById('tax_total').value = taxTotal.toFixed(2);
        document.getElementById('total').value = total.toFixed(2);
    }

    document.getElementById('add-item').addEventListener('click', () => {
        const container = document.getElementById('items-container');
        const newRow = document.createElement('div');
        newRow.classList.add('item-row', 'border', 'rounded', 'p-3', 'mb-3');
        newRow.innerHTML = `
            <div class="row">
                <div class="col-md-2">
                    <label>Item Code</label>
                    <select name="items[${index}][item_code]" class="form-control item-code-select" required>
                        <option value="">Select Item</option>
                        @foreach($items as $item)
                            <option value="{{ $item->code }}" data-description="{{ $item->description }}">{{ $item->code }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3">
                    <label>Description</label>
                    <textarea name="items[${index}][description]" class="form-control description-field" readonly></textarea>
                </div>
                <div class="col-md-2">
                    <label>Quantity</label>
                    <input type="number" name="items[${index}][quantity]" class="form-control quantity" step="any" required>
                </div>
                <div class="col-md-2">
                    <label>Unit Price</label>
                    <input type="number" name="items[${index}][unit_price]" class="form-control unit_price" step="any" required>
                </div>
                <div class="col-md-2">
                    <label>Duration</label>
                    <input type="number" name="items[${index}][duration]" class="form-control duration" value="1" required>
                </div>
                <div class="col-md-1">
                    <label>Unit</label>
                    <select name="items[${index}][duration_unit]" class="form-control">
                        <option value="day">Day</option>
                        <option value="week">Week</option>
                        <option value="month">Month</option>
                    </select>
                </div>
                <div class="col-md-1">
                    <label>Line Total</label>
                    <input type="number" name="items[${index}][line_total]" class="form-control line_total" readonly>
                </div>
                <div class="col-md-1">
                    <label>Tax</label>
                    <input type="number" name="items[${index}][tax]" class="form-control tax" step="0.01" value="0">
                </div>
                <div class="col-md-1">
                    <label>Total w/Tax</label>
                    <input type="number" name="items[${index}][line_total_with_tax]" class="form-control line_total_with_tax" readonly>
                </div>
            </div>`;
        container.appendChild(newRow);
        index++;
    });

    document.addEventListener('input', function (e) {
        if (e.target.classList.contains('quantity') ||
            e.target.classList.contains('unit_price') ||
            e.target.classList.contains('duration') ||
            e.target.classList.contains('tax') ||
            e.target.id === 'discount') {
            recalculate();
        }
    });

    document.addEventListener('change', function (e) {
        if (e.target.classList.contains('item-code-select')) {
            const desc = e.target.selectedOptions[0].getAttribute('data-description') || '';
            e.target.closest('.item-row').querySelector('.description-field').value = desc;
        }
    });
</script>
@endsection
