@extends('layouts.app')

@section('content')

<div class="row">
    <div class="col-sm-12">
        <div class="page-title-box">
            <div class="row">
                <div class="col">
                    <h4 class="page-title">Create Invoice</h4>
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ route('finance.invoices.index') }}">Invoices</a></li>
                        <li class="breadcrumb-item active">Create</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</div>

<form id="invoice-form" action="{{ route('finance.invoices.store') }}" method="POST">
@csrf
<div class="row">

    {{-- LEFT: Client + Meta --}}
    <div class="col-lg-8">
        <div class="card shadow-sm">
            <div class="card-body p-4">

                {{-- Document type banner --}}
                <div class="row mb-4">
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Document Type</label>
                        <select name="document_type" id="document_type" class="form-select">
                            <option value="invoice" selected>Tax Invoice</option>
                            <option value="quotation">Quotation / Estimate</option>
                            <option value="proforma">Proforma Invoice</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">PDF Template</label>
                        <select name="template_name" class="form-select">
                            <option value="default" selected>Default Classic</option>
                            <option value="logo_left">Modern (Logo Left)</option>
                            <option value="logo_right">Modern (Logo Right)</option>
                        </select>
                    </div>
                </div>

                {{-- Client --}}
                <div class="mb-3">
                    <label class="form-label fw-bold">Client <span class="text-danger">*</span></label>
                    <select name="client_id" id="client_id" class="form-select select2" required>
                        <option value="">— Select Client —</option>
                        @foreach($clients as $client)
                            <option value="{{ $client->id }}"
                                data-email="{{ $client->email }}"
                                data-phone="{{ $client->phone ?? '' }}"
                                data-address="{{ $client->address ?? '' }}"
                                data-currency="{{ $client->currency_id ?? '' }}">
                                {{ $client->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                {{-- Client Address Preview --}}
                <div id="client-address-box" class="p-3 bg-light rounded mb-3 small text-muted" style="display:none; white-space:pre-line;"></div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label fw-bold">PO Number</label>
                            <input type="text" name="po_number" class="form-control" placeholder="Customer Purchase Order #">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Reference</label>
                            <input type="text" name="reference" class="form-control" placeholder="Internal reference">
                        </div>
                    </div>
                </div>

                <hr class="my-3">

                {{-- Line Items --}}
                <div class="d-flex align-items-center justify-content-between mb-2">
                    <h5 class="mb-0">Line Items</h5>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered align-middle" id="items-table">
                        <thead class="table-light">
                            <tr>
                                <th style="width:32%">Description</th>
                                <th style="width:8%">Qty</th>
                                <th style="width:12%">Unit Price</th>
                                <th style="width:10%">Disc %</th>
                                <th style="width:22%">Tax</th>
                                <th style="width:12%" class="text-end">Total</th>
                                <th style="width:4%"></th>
                            </tr>
                        </thead>
                        <tbody id="item-rows">
                            <tr class="item-row">
                                <td><input type="text" name="items[0][description]" class="form-control form-control-sm" placeholder="Item description" required></td>
                                <td><input type="number" name="items[0][quantity]" class="form-control form-control-sm item-qty" step="0.01" min="0.01" value="1" required></td>
                                <td><input type="number" name="items[0][unit_price]" class="form-control form-control-sm item-price" step="0.01" min="0" value="0.00" required></td>
                                <td><input type="number" name="items[0][discount_pct]" class="form-control form-control-sm item-disc" step="0.01" min="0" max="100" value="0" placeholder="0"></td>
                                <td>
                                    <select name="items[0][tax_ids][]" class="form-select form-select-sm item-tax select2" multiple>
                                        @foreach($taxes as $tax)
                                            <option value="{{ $tax->id }}"
                                                data-rate="{{ $tax->rate }}"
                                                data-type="{{ $tax->type }}"
                                                data-inclusive="{{ $tax->is_inclusive ? 1 : 0 }}">
                                                {{ $tax->name }} ({{ $tax->rate }}{{ $tax->type === 'percentage' ? '%' : '' }})
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td class="text-end fw-semibold item-total">0.00</td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-sm btn-link text-danger remove-item p-0" title="Remove">
                                        <i class="ti ti-trash font-16"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="d-flex gap-2 mb-3">
                    <button type="button" class="btn btn-sm btn-outline-primary" id="add-item">
                        <i class="ti ti-plus me-1"></i>Add Line
                    </button>
                </div>

                <hr class="my-4">

                {{-- Notes & Terms --}}
                <div class="row">
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Notes</label>
                        <textarea name="notes" class="form-control" rows="3" placeholder="Notes visible on invoice (e.g. bank details, thank you message)"></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-bold">Terms & Conditions</label>
                        <textarea name="terms" class="form-control" rows="3" placeholder="Payment terms, late fee policy, etc."></textarea>
                    </div>
                </div>

            </div>
        </div>
    </div>

    {{-- RIGHT: Dates, Currency, Totals --}}
    <div class="col-lg-4">
        <div class="card shadow-sm">
            <div class="card-body p-4">

                <div class="mb-3">
                    <label class="form-label fw-bold">Invoice Number <span class="text-danger">*</span></label>
                    <input type="text" name="invoice_number" class="form-control" required value="{{ $nextInvoiceNumber }}">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Invoice Date <span class="text-danger">*</span></label>
                    <input type="date" name="invoice_date" class="form-control" required value="{{ date('Y-m-d') }}">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Due Date <span class="text-danger">*</span></label>
                    <input type="date" name="due_date" class="form-control" required value="{{ date('Y-m-d', strtotime('+30 days')) }}">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">Currency <span class="text-danger">*</span></label>
                    <select name="currency_id" id="currency_id" class="form-select" required>
                        @foreach($currencies as $currency)
                            <option value="{{ $currency->id }}" data-symbol="{{ $currency->symbol }}">
                                {{ $currency->iso_code }} — {{ $currency->name ?? $currency->iso_code }} ({{ $currency->symbol }})
                            </option>
                        @endforeach
                    </select>
                </div>

                <hr class="my-3">

                {{-- Totals summary --}}
                <div class="totals-box">
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Subtotal</span>
                        <span id="summary-subtotal" class="fw-semibold">0.00</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Discount</span>
                        <span id="summary-discount" class="fw-semibold text-warning">0.00</span>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Tax</span>
                        <span id="summary-tax" class="fw-semibold">0.00</span>
                    </div>
                    <hr>
                    <div class="d-flex justify-content-between">
                        <span class="fw-bold fs-5">Total</span>
                        <span id="summary-total" class="fw-bold fs-5 text-primary">0.00</span>
                    </div>
                </div>

                <hr class="my-3">

                {{-- Action Buttons --}}
                <div class="d-grid gap-2">
                    <button type="submit" name="save_action" value="save" class="btn btn-primary">
                        <i class="ti ti-check me-1"></i>Save Invoice
                    </button>
                    <button type="submit" name="save_action" value="draft" class="btn btn-outline-secondary">
                        <i class="ti ti-device-floppy me-1"></i>Save as Draft
                    </button>
                    <a href="{{ route('finance.invoices.index') }}" class="btn btn-light">Cancel</a>
                </div>

            </div>
        </div>
    </div>

</div>
</form>
@endsection

@section('scripts')
@php
$taxOptionsData = $taxes->map(fn($t) => [
    'id'        => $t->id,
    'name'      => $t->name,
    'rate'      => $t->rate,
    'type'      => $t->type,
    'inclusive' => $t->is_inclusive ? 1 : 0,
]);
@endphp
<script>
const taxOptions = {!! json_encode($taxOptionsData) !!};

$(document).ready(function () {

    // Init Select2
    initSelect2Row($('#item-rows tr.item-row'));
    $('.select2[name="client_id"]').select2({ theme: 'bootstrap-5', placeholder: '— Select Client —' });

    // Client address preview
    $('#client_id').on('change', function () {
        const opt = $(this).find('option:selected');
        const email   = opt.data('email') || '';
        const phone   = opt.data('phone') || '';
        const address = opt.data('address') || '';
        const parts   = [email, phone, address].filter(Boolean);
        if (parts.length) {
            $('#client-address-box').text(parts.join('\n')).show();
        } else {
            $('#client-address-box').hide();
        }
    });

    // Currency symbol tracking
    function getCurrencySymbol() {
        return $('#currency_id option:selected').data('symbol') || '';
    }

    let rowIndex = 1;

    // Add line item
    $('#add-item').on('click', function () {
        const taxHtml = taxOptions.map(t =>
            `<option value="${t.id}" data-rate="${t.rate}" data-type="${t.type}" data-inclusive="${t.inclusive}">
                ${t.name} (${t.rate}${t.type === 'percentage' ? '%' : ''})
            </option>`
        ).join('');

        const tr = $(`
            <tr class="item-row">
                <td><input type="text" name="items[${rowIndex}][description]" class="form-control form-control-sm" placeholder="Item description" required></td>
                <td><input type="number" name="items[${rowIndex}][quantity]" class="form-control form-control-sm item-qty" step="0.01" min="0.01" value="1" required></td>
                <td><input type="number" name="items[${rowIndex}][unit_price]" class="form-control form-control-sm item-price" step="0.01" min="0" value="0.00" required></td>
                <td><input type="number" name="items[${rowIndex}][discount_pct]" class="form-control form-control-sm item-disc" step="0.01" min="0" max="100" value="0" placeholder="0"></td>
                <td>
                    <select name="items[${rowIndex}][tax_ids][]" class="form-select form-select-sm item-tax" multiple>
                        ${taxHtml}
                    </select>
                </td>
                <td class="text-end fw-semibold item-total">0.00</td>
                <td class="text-center">
                    <button type="button" class="btn btn-sm btn-link text-danger remove-item p-0">
                        <i class="ti ti-trash font-16"></i>
                    </button>
                </td>
            </tr>
        `);
        $('#item-rows').append(tr);
        initSelect2Row(tr);
        rowIndex++;
        calculateTotals();
    });

    function initSelect2Row(tr) {
        tr.find('.item-tax').select2({ theme: 'bootstrap-5', placeholder: 'Select taxes', allowClear: true, width: '100%' });
    }

    // Remove row
    $(document).on('click', '.remove-item', function () {
        if ($('.item-row').length > 1) {
            $(this).closest('tr').remove();
            calculateTotals();
        } else {
            Swal.fire({ icon: 'warning', title: 'At least one line item is required.', timer: 1500 });
        }
    });

    // Recalculate on change
    $(document).on('input change', '.item-qty, .item-price, .item-disc, .item-tax', calculateTotals);

    function calculateTotals() {
        let subtotal = 0, discount = 0, taxTotal = 0;

        $('.item-row').each(function () {
            const qty       = parseFloat($(this).find('.item-qty').val()) || 0;
            const price     = parseFloat($(this).find('.item-price').val()) || 0;
            const discPct   = parseFloat($(this).find('.item-disc').val()) || 0;
            const lineBase  = qty * price;
            const discAmt   = lineBase * (discPct / 100);
            const afterDisc = lineBase - discAmt;

            let itemTax = 0;
            $(this).find('.item-tax option:selected').each(function () {
                const rate      = parseFloat($(this).data('rate')) || 0;
                const type      = $(this).data('type');
                const inclusive = parseInt($(this).data('inclusive'));

                if (type === 'percentage') {
                    if (inclusive) {
                        itemTax += afterDisc - (afterDisc / (1 + rate / 100));
                    } else {
                        itemTax += afterDisc * (rate / 100);
                    }
                } else {
                    itemTax += rate;
                }
            });

            const rowTotal = afterDisc + itemTax;
            $(this).find('.item-total').text(rowTotal.toFixed(2));

            subtotal += lineBase;
            discount += discAmt;
            taxTotal += itemTax;
        });

        const grandTotal = subtotal - discount + taxTotal;
        $('#summary-subtotal').text(subtotal.toFixed(2));
        $('#summary-discount').text(discount.toFixed(2));
        $('#summary-tax').text(taxTotal.toFixed(2));
        $('#summary-total').text(grandTotal.toFixed(2));
    }

    // Track which submit button was clicked
    let saveAction = 'save';
    $(document).on('click', '#invoice-form button[type="submit"]', function () {
        saveAction = $(this).val() || 'save';
    });

    // Handle form submit (AJAX)
    $('#invoice-form').on('submit', function (e) {
        e.preventDefault();

        $.ajax({
            url: $(this).attr('action'),
            method: 'POST',
            data: $(this).serialize() + '&save_action=' + saveAction,
            success: function (res) {
                if (res.status) {
                    Swal.fire({ icon: 'success', title: 'Saved!', text: res.message, timer: 1500 })
                        .then(() => window.location.href = '/finance/invoices/' + res.id);
                }
            },
            error: function (xhr) {
                const errors = xhr.responseJSON?.errors;
                if (errors) {
                    const msg = Object.values(errors).flat().join('\n');
                    Swal.fire('Validation Error', msg, 'error');
                } else {
                    Swal.fire('Error', xhr.responseJSON?.message ?? 'Something went wrong.', 'error');
                }
            }
        });
    });

});
</script>
@endsection
