@php
    $note = $purchaseBill ?? null;
    $isEdit = (bool) $note;
    $formAction = $isEdit ? route('admin.purchase-bills.update', $note) : route('admin.purchase-bills.store');
    $labels = $docLabels;
    $lineItems = $lineItems ?? [['item_name' => '', 'description' => '', 'unit' => 'NOS', 'quantity' => 1, 'rate' => 0, 'discount_percent' => 0, 'tax_rate' => 0]];
@endphp

<form method="POST" action="{{ $formAction }}" id="purchase-bill-form" class="billing-invoice-form{{ ($gstEnabled ?? false) ? ' billing-invoice-form--gst' : '' }}"
    data-gst-enabled="{{ ($gstEnabled ?? false) ? '1' : '0' }}"
    data-company-state="{{ $company->state ?? '' }}"
    data-vendors='@json($vendorsJson ?? [])'
    data-items='@json($itemsJson)'
    data-tax-rates='@json($taxRatesJson)'
    data-units='@json($unitsJson)'>
    @csrf
    @if($isEdit) @method('PUT') @endif
    @include('partials.admin.billing-catalog-items-json')

    <div class="billing-form-card card border-0 mb-3">
        <div class="card-body">
            <h5 class="fw-semibold mb-1">{{ $isEdit ? 'Edit' : 'Add New' }} {{ $typeLabel }}</h5>
            <p class="text-muted small mb-4">Select vendor, add line items, and enter bill and PO details.</p>

            <div class="row g-3 billing-invoice-header-grid">
                <div class="col-md-4">
                    <label class="form-label">Vendor name <span class="text-danger">*</span></label>
                    <div class="billing-client-picker billing-unit-picker billing-unit-picker--lg" data-vendor-picker data-placeholder="Select Vendor">
                        <input type="hidden" name="vendor_id" id="billing-vendor-id" data-field="vendor_id" value="{{ old('vendor_id', $note?->vendor_id) }}" required>
                        <button type="button" class="billing-unit-picker__trigger form-select text-start" aria-haspopup="listbox">
                            <span class="billing-unit-picker__label text-truncate text-muted">Select Vendor</span>
                            <i class="ri-arrow-down-s-line billing-unit-picker__arrow"></i>
                        </button>
                        <div class="billing-unit-picker__dropdown d-none">
                            <div class="billing-unit-picker__search-wrap">
                                <input type="text" class="form-control form-control-sm billing-unit-picker__search" placeholder="Type to search" autocomplete="off">
                            </div>
                            <ul class="billing-unit-picker__list billing-vendor-picker__list"></ul>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <label class="form-label">{{ $labels['number'] }} <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <input type="text" name="bill_prefix" class="form-control" style="max-width:45%" value="{{ old('bill_prefix', $note?->bill_prefix ?? $defaultPrefix) }}" required>
                        <input type="number" name="bill_seq" class="form-control" min="1" value="{{ old('bill_seq', $note?->bill_seq ?? $defaultSeq) }}" required>
                    </div>
                </div>
                <div class="col-md-4">
                    <label class="form-label">{{ $labels['date'] }} <span class="text-danger">*</span></label>
                    <input type="date" name="bill_date" class="form-control" value="{{ old('bill_date', $note?->bill_date?->format('Y-m-d') ?? date('Y-m-d')) }}" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Due date</label>
                    <input type="date" name="due_date" class="form-control" value="{{ old('due_date', $note?->due_date?->format('Y-m-d') ?? $defaultDueDate) }}">
                </div>
                <div class="col-md-4">
                    <label class="form-label">PO no</label>
                    <input type="text" name="po_number" class="form-control" value="{{ old('po_number', $note?->po_number) }}" placeholder="PO number">
                </div>
                <div class="col-md-4">
                    <label class="form-label">PO date</label>
                    <input type="date" name="po_date" class="form-control" value="{{ old('po_date', $note?->po_date?->format('Y-m-d')) }}">
                </div>
                <div class="col-md-4">
                    <label class="form-label">Invoice number</label>
                    <input type="text" name="vendor_invoice_number" class="form-control" value="{{ old('vendor_invoice_number', $note?->vendor_invoice_number) }}" placeholder="Vendor invoice no">
                </div>
            </div>

            @include('partials.admin.gst-vendor-form-fields', ['purchaseBill' => $note, 'gstEnabled' => $gstEnabled ?? false, 'indianStates' => $indianStates ?? []])
        </div>
    </div>

    <div class="billing-form-card card border-0 mb-3">
        <div class="card-body p-0">
            <div class="px-3 pt-3 pb-2">
                <h6 class="fw-semibold mb-0">{{ $labels['title'] }}</h6>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered billing-line-items-table mb-0{{ ($gstEnabled ?? false) ? ' billing-line-items-table--gst' : '' }}">
                    <thead class="table-light">
                        <tr>
                            <th class="col-no">No</th>
                            <th class="col-item">Item Name</th>
                            <th class="col-desc">Description</th>
                            <th class="col-unit">Unit</th>
                            <th class="col-qty">QTY</th>
                            <th class="col-price">Price</th>
                            <th class="col-disc">Disc. %</th>
                            @include('partials.admin.gst-line-item-columns', ['gstEnabled' => $gstEnabled ?? false])
                            @if(!($gstEnabled ?? false))
                            <th class="col-tax">Tax</th>
                            @endif
                            <th class="col-total text-end">Total</th>
                            <th class="col-act"></th>
                        </tr>
                    </thead>
                    <tbody id="line-items-body">
                        @foreach($lineItems as $idx => $line)
                        @php
                            $unitCode = $line['unit'] ?? 'NOS';
                            $unitMeta = collect($unitsCatalog)->firstWhere('code', $unitCode);
                            $unitLabel = $unitMeta['label'] ?? $unitCode;
                        @endphp
                        <tr class="line-item-row">
                            <td class="text-center line-no">{{ $idx + 1 }}</td>
                            <td class="col-item">
                                <select name="line_items[{{ $idx }}][item_id]" data-field="item_id" class="form-select form-select-sm mb-1">
                                    <option value="">Select Item</option>
                                    @include('partials.admin.catalog-item-options', [
                                        'catalogItems' => $catalogItems,
                                        'selectedId' => $line['item_id'] ?? null,
                                        'rateColumn' => 'purchase_rate',
                                    ])
                                </select>
                                <input type="text" name="line_items[{{ $idx }}][item_name]" data-field="item_name" class="form-control form-control-sm" value="{{ $line['item_name'] ?? '' }}" placeholder="Item name" required>
                            </td>
                            <td class="col-desc">
                                <textarea name="line_items[{{ $idx }}][description]" data-field="description" class="form-control form-control-sm billing-desc-field" rows="2" maxlength="1000" placeholder="Description">{{ $line['description'] ?? '' }}</textarea>
                                <small class="text-muted billing-desc-hint">1000 characters left</small>
                            </td>
                            <td class="col-unit">
                                @include('partials.admin.unit-combobox', [
                                    'name' => "line_items[{$idx}][unit]",
                                    'value' => $unitCode,
                                    'label' => $unitLabel,
                                ])
                            </td>
                            <td class="col-qty"><input type="number" step="0.001" min="0.001" name="line_items[{{ $idx }}][quantity]" data-field="quantity" class="form-control form-control-sm text-center" value="{{ $line['quantity'] ?? 1 }}"></td>
                            <td class="col-price"><input type="number" step="0.01" min="0" name="line_items[{{ $idx }}][rate]" data-field="rate" class="form-control form-control-sm" value="{{ $line['rate'] ?? 0 }}" placeholder="0"></td>
                            <td class="col-disc"><input type="number" step="0.01" min="0" max="100" name="line_items[{{ $idx }}][discount_percent]" data-field="discount_percent" class="form-control form-control-sm" value="{{ $line['discount_percent'] ?? 0 }}" placeholder="0"></td>
                            @include('partials.admin.gst-line-item-cells', ['gstEnabled' => $gstEnabled ?? false, 'idx' => $idx, 'line' => $line, 'taxRates' => $taxRates])
                            @if(!($gstEnabled ?? false))
                            <td>
                                <select name="line_items[{{ $idx }}][tax_rate]" data-field="tax_rate" class="form-select form-select-sm">
                                    <option value="0">Select Tax</option>
                                    @foreach($taxRates as $tax)
                                        <option value="{{ $tax->rate }}" data-tax-name="{{ $tax->name }}" @selected(($line['tax_rate'] ?? 0) == $tax->rate)>{{ $tax->name }} ({{ $tax->rate }}%)</option>
                                    @endforeach
                                </select>
                            </td>
                            @endif
                            <td class="text-end fw-medium" data-line-total>₹ 0.00</td>
                            <td class="text-center">
                                <button type="button" class="btn btn-sm btn-soft-danger btn-remove-line"><i class="ri-delete-bin-line"></i></button>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
            <div class="p-3 border-top text-end">
                <button type="button" class="btn btn-primary btn-sm" id="btn-add-line">
                    <i class="ri-add-line me-1"></i> Add line
                </button>
            </div>
        </div>
    </div>

    @php
        $discAllType = old('discount_all_type', $note?->discount_all_type ?? 'percent');
        $discAllVal = old('discount_all_value', $note?->discount_all_value ?? $note?->discount_all_percent ?? 0);
    @endphp
    <div class="row g-3 billing-invoice-options-row align-items-start">
        <div class="col-lg-6">
            <div class="billing-form-card card border-0 h-100">
                <div class="card-body billing-invoice-options">
                    <h6 class="billing-options-heading"><i class="ri-settings-4-line me-1"></i> Additional options</h6>

                    <div class="billing-option-block" data-option="shipping">
                        <div class="billing-option-head">
                            <input class="form-check-input" type="checkbox" name="has_shipping" id="has_shipping" value="1" @checked(old('has_shipping', $note?->has_shipping))>
                            <label class="form-check-label fw-medium" for="has_shipping">Add shipping charges</label>
                        </div>
                        <div class="billing-option-body {{ old('has_shipping', $note?->has_shipping) ? '' : 'd-none' }}" id="has_shipping_wrap">
                            <div class="row g-2">
                                <div class="col-sm-5">
                                    <select name="shipping_mode" id="shipping_mode" class="form-select form-select-sm">
                                        <option value="">Select mode</option>
                                        @foreach($shippingModes as $key => $label)
                                            <option value="{{ $key }}" @selected(old('shipping_mode', $note?->shipping_mode) === $key)>{{ $label }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-sm-7">
                                    <input type="number" step="0.01" min="0" name="shipping_charges" id="shipping_charges" class="form-control form-control-sm" value="{{ old('shipping_charges', $note?->shipping_charges ?? 0) }}" placeholder="Shipping Amount">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="billing-option-block" data-option="discount_total">
                        <div class="billing-option-head">
                            <input class="form-check-input" type="checkbox" name="has_discount_total" id="has_discount_total" value="1" @checked(old('has_discount_total', $note?->has_discount_total))>
                            <label class="form-check-label fw-medium" for="has_discount_total">Add Discount On Total</label>
                        </div>
                        <div class="billing-option-body {{ old('has_discount_total', $note?->has_discount_total) ? '' : 'd-none' }}" id="has_discount_total_wrap">
                            <input type="number" step="0.01" min="0" name="discount_on_total" id="discount_on_total" class="form-control form-control-sm" value="{{ old('discount_on_total', $note?->discount_on_total ?? 0) }}" placeholder="0">
                        </div>
                    </div>

                    <div class="billing-option-block" data-option="discount_all">
                        <div class="billing-option-head">
                            <input class="form-check-input" type="checkbox" name="has_discount_all" id="has_discount_all" value="1" @checked(old('has_discount_all', $note?->has_discount_all))>
                            <label class="form-check-label fw-medium" for="has_discount_all">Add discount to all</label>
                        </div>
                        <div class="billing-option-body {{ old('has_discount_all', $note?->has_discount_all) ? '' : 'd-none' }}" id="has_discount_all_wrap">
                            <div class="row g-2">
                                <div class="col-sm-5">
                                    <input type="number" step="0.01" min="0" name="discount_all_value" id="discount_all_value" class="form-control form-control-sm" value="{{ $discAllVal }}" placeholder="0">
                                </div>
                                <div class="col-sm-7">
                                    <select name="discount_all_type" id="discount_all_type" class="form-select form-select-sm">
                                        @foreach($discountAllTypes as $key => $label)
                                            <option value="{{ $key }}" @selected($discAllType === $key)>{{ $label }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="billing-option-block" data-option="custom">
                        <div class="billing-option-head">
                            <input class="form-check-input" type="checkbox" name="has_custom_amount" id="has_custom_amount" value="1" @checked(old('has_custom_amount', $note?->has_custom_amount))>
                            <label class="form-check-label fw-medium" for="has_custom_amount">Add Custom Amount</label>
                        </div>
                        <div class="billing-option-body {{ old('has_custom_amount', $note?->has_custom_amount) ? '' : 'd-none' }}" id="has_custom_amount_wrap">
                            <div class="row g-2">
                                <div class="col-sm-6">
                                    <input type="text" name="custom_amount_label" id="custom_amount_label" class="form-control form-control-sm" value="{{ old('custom_amount_label', $note?->custom_amount_label) }}" placeholder="Custom Amount Label">
                                </div>
                                <div class="col-sm-6">
                                    <input type="number" step="0.01" min="0" name="custom_amount" id="custom_amount" class="form-control form-control-sm" value="{{ old('custom_amount', $note?->custom_amount ?? 0) }}" placeholder="Custom Amount">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="billing-option-block" data-option="advance">
                        <div class="billing-option-head">
                            <input class="form-check-input" type="checkbox" name="has_advance_payment" id="has_advance_payment" value="1" @checked(old('has_advance_payment', $note?->has_advance_payment))>
                            <label class="form-check-label fw-medium" for="has_advance_payment">Use Advance Payment</label>
                            <span class="billing-option-inline-val text-muted small" id="advance-inline-display">{{ old('has_advance_payment', $note?->has_advance_payment) ? '₹ '.number_format(old('advance_payment', $note?->advance_payment ?? 0), 2) : '' }}</span>
                        </div>
                        <div class="billing-option-body {{ old('has_advance_payment', $note?->has_advance_payment) ? '' : 'd-none' }}" id="has_advance_payment_wrap">
                            <input type="number" step="0.01" min="0" name="advance_payment" id="advance_payment" class="form-control form-control-sm mb-1" value="{{ old('advance_payment', $note?->advance_payment ?? 0) }}">
                            <a href="#" class="small text-primary" id="link-add-advance"><i class="ri-add-line"></i> Add advance payment</a>
                        </div>
                    </div>

                    <div class="billing-option-block" data-option="total_quantity">
                        <div class="billing-option-head">
                            <input class="form-check-input" type="checkbox" name="has_total_quantity" id="has_total_quantity" value="1" @checked(old('has_total_quantity', $note?->has_total_quantity))>
                            <label class="form-check-label fw-medium" for="has_total_quantity">Total quantity</label>
                        </div>
                        <div class="billing-option-body {{ old('has_total_quantity', $note?->has_total_quantity) ? '' : 'd-none' }}" id="has_total_quantity_wrap">
                            <div class="row g-2">
                                <div class="col-sm-5">
                                    <input type="text" name="total_quantity_unit" class="form-control form-control-sm" value="{{ old('total_quantity_unit', $note?->total_quantity_unit) }}" placeholder="Unit">
                                </div>
                                <div class="col-sm-7">
                                    <input type="number" step="0.001" min="0" name="total_quantity" class="form-control form-control-sm" value="{{ old('total_quantity', $note?->total_quantity) }}" placeholder="Quantity">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="billing-option-block">
                        <div class="billing-option-head">
                            <input class="form-check-input" type="checkbox" name="show_cess" id="show_cess" value="1" @checked(old('show_cess', $note?->show_cess))>
                            <label class="form-check-label fw-medium" for="show_cess">Show CESS</label>
                        </div>
                    </div>

                    <div class="billing-option-block">
                        <div class="billing-option-head">
                            <input class="form-check-input" type="checkbox" name="reverse_charge" id="reverse_charge" value="1" @checked(old('reverse_charge', $note?->reverse_charge))>
                            <label class="form-check-label fw-medium" for="reverse_charge">Subject to reverse charge</label>
                        </div>
                    </div>

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

        <div class="col-lg-6">
            <div class="billing-invoice-summary card border-0 h-100 sticky-lg-top" style="top:80px">
                <div class="card-body p-0">
                    <div class="billing-summary-header px-3 py-2">Amount summary</div>
                    <div class="billing-summary-lines px-3 py-2">
                        <div class="billing-summary-line">
                            <span>Subtotal</span>
                            <span id="summary-subtotal" class="fw-medium">₹ 0.00</span>
                        </div>
                        @include('partials.admin.gst-summary-rows', ['gstEnabled' => $gstEnabled ?? false])
                        <div id="summary-tax-breakdown" class="billing-summary-tax-breakdown"></div>
                        <div class="billing-summary-line billing-summary-line--deduct d-none" id="row-summary-advance" data-summary="advance">
                            <span>Used Advanced Payment</span>
                            <span class="text-danger">(-) <span id="summary-advance">₹ 0.00</span></span>
                        </div>
                        <div class="billing-summary-line d-none" id="row-summary-shipping" data-summary="shipping">
                            <span>Shipping &amp; Packaging charges</span>
                            <span id="summary-shipping" class="text-primary">₹ 0.00</span>
                        </div>
                        <div class="billing-summary-line billing-summary-line--deduct d-none" id="row-summary-discount-total" data-summary="discount_total">
                            <span>Discount On Total</span>
                            <span class="text-danger">(-) <span id="summary-discount-total">₹ 0.00</span></span>
                        </div>
                        <div class="billing-summary-line billing-summary-line--deduct d-none" id="row-summary-discount-all" data-summary="discount_all">
                            <span id="summary-discount-all-label">Discount on all</span>
                            <span class="text-danger">(-) <span id="summary-discount-all">₹ 0.00</span></span>
                        </div>
                        <div class="billing-summary-line d-none" id="row-summary-custom" data-summary="custom">
                            <span id="summary-custom-label">Custom Amount</span>
                            <span id="summary-custom">₹ 0.00</span>
                        </div>
                    </div>
                    <div class="billing-summary-total px-3 py-3">
                        <span class="fw-semibold">Total</span>
                        <span class="billing-summary-total__amount" id="summary-total">₹ 0</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-3 mt-1">
        <div class="col-md-6">
            <label class="form-label">Terms &amp; Conditions</label>
            <textarea name="terms" class="form-control" rows="4" placeholder="Payment terms visible on document">{{ old('terms', $note?->terms) }}</textarea>
        </div>
        <div class="col-md-6">
            <label class="form-label">Private notes <span class="text-muted">(not shown to vendor)</span></label>
            <textarea name="private_notes" class="form-control" rows="4" placeholder="Internal notes">{{ old('private_notes', $note?->private_notes) }}</textarea>
        </div>
    </div>

    <div class="billing-form-footer mt-4">
        <div class="d-flex flex-wrap gap-2 ms-md-auto">
            <button type="submit" name="save_action" value="preview" class="btn btn-success">
                <i class="ri-eye-line me-1"></i> Save &amp; Preview
            </button>
            <button type="submit" name="save_action" value="save" class="btn btn-outline-success">
                <i class="ri-check-line me-1"></i> Save
            </button>
            <button type="submit" name="save_action" value="draft" class="btn btn-light border">
                Save as draft
            </button>
            <a href="{{ route('admin.purchase-bills.index') }}" class="btn btn-light">Cancel</a>
        </div>
    </div>
</form>

<div class="modal fade" id="modal-add-unit" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header py-2">
                <h6 class="modal-title">Add new unit</h6>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="form-add-unit">
                <div class="modal-body">
                    <div class="mb-2">
                        <label class="form-label small">Unit name</label>
                        <input type="text" name="name" class="form-control form-control-sm" required placeholder="e.g. Carton">
                    </div>
                    <div class="mb-2">
                        <label class="form-label small">Unit code</label>
                        <input type="text" name="code" class="form-control form-control-sm" required placeholder="e.g. CTN" maxlength="20">
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_gst" value="1" id="new_unit_gst">
                        <label class="form-check-label small" for="new_unit_gst">GST unit</label>
                    </div>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-light btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success btn-sm">Add unit</button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
    window.__billingUnits = @json($unitsJson);
    window.__billingCsrf = '{{ csrf_token() }}';
    window.__billingUnitsStore = '{{ route('admin.units.store') }}';
</script>
<script src="{{ asset('js/unit-picker.js') }}"></script>
@include('partials.admin.invoice-form-script')
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('purchase-bill-form');
        const vendors = @json($vendorsJson ?? []);
        const vendorHidden = document.getElementById('billing-vendor-id');

        function initVendorPicker() {
            const picker = form?.querySelector('[data-vendor-picker]');
            if (!picker || picker.dataset.initialized) return;
            picker.dataset.initialized = '1';
            const hidden = picker.querySelector('[data-field="vendor_id"]');
            const label = picker.querySelector('.billing-unit-picker__label');
            const list = picker.querySelector('.billing-vendor-picker__list');
            const search = picker.querySelector('.billing-unit-picker__search');

            function render(filter) {
                const q = (filter || '').toLowerCase();
                const rows = vendors.filter(v => !q || `${v.name} ${v.city || ''}`.toLowerCase().includes(q));
                list.innerHTML = rows.map(v => `
                    <li class="billing-unit-picker__option" role="option" data-id="${v.id}" tabindex="0">
                        <span>${v.name}${v.city ? ' - ' + v.city : ''}</span>
                    </li>
                `).join('') || '<li class="text-muted small px-2 py-2">No vendors found</li>';
            }

            function select(id) {
                const v = vendors.find(x => String(x.id) === String(id));
                if (hidden) hidden.value = v ? String(v.id) : '';
                if (label) {
                    label.textContent = v ? `${v.name}${v.city ? ' - ' + v.city : ''}` : 'Select Vendor';
                    label.classList.toggle('text-muted', !v);
                }
                picker.querySelector('.billing-unit-picker__dropdown')?.classList.add('d-none');
                hidden?.dispatchEvent(new CustomEvent('billing-vendor-changed', { bubbles: true }));
                hidden?.dispatchEvent(new Event('change', { bubbles: true }));
            }

            picker.querySelector('.billing-unit-picker__trigger')?.addEventListener('click', function (e) {
                e.preventDefault();
                picker.querySelector('.billing-unit-picker__dropdown')?.classList.toggle('d-none');
                render('');
            });
            search?.addEventListener('input', e => render(e.target.value));
            list?.addEventListener('click', e => {
                const opt = e.target.closest('.billing-unit-picker__option');
                if (opt?.dataset.id) select(opt.dataset.id);
            });
            if (hidden?.value) select(hidden.value);
        }
        initVendorPicker();

        document.dispatchEvent(new CustomEvent('billing-invoice-form-ready'));
    });
</script>
@endpush
