@php
    $selectedWarehouse = (int) ($itemFilters['warehouse_id'] ?? 0);
    $selectedType = $itemFilters['type'] ?? '';
    $selectedCategory = (int) ($itemFilters['category_id'] ?? 0);
    $filtersApplied = $selectedWarehouse > 0;
@endphp

<div class="card mb-3">
    <div class="card-header fw-semibold">
        <i class="bi bi-funnel me-2 text-primary"></i>Filter Items
    </div>
    <div class="card-body">
        <form method="GET" action="{{ route('masters.opening-balance.index') }}">
            <input type="hidden" name="tab" value="items">
            <div class="row g-3 align-items-end">
                <div class="col-sm-6 col-md-3">
                    <label class="form-label fw-semibold" style="font-size:13px">Warehouse <span class="text-danger">*</span></label>
                    <select name="warehouse" class="form-select" required>
                        <option value="">Select warehouse…</option>
                        @foreach($warehouses as $warehouse)
                            <option value="{{ $warehouse->id }}" {{ $selectedWarehouse === $warehouse->id ? 'selected' : '' }}>
                                {{ $warehouse->code ? $warehouse->code . ' — ' : '' }}{{ $warehouse->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-sm-6 col-md-3">
                    <label class="form-label fw-semibold" style="font-size:13px">Item Type</label>
                    <select name="item_type" class="form-select">
                        <option value="">All Types</option>
                        @foreach($itemTypes as $value => $label)
                            <option value="{{ $value }}" {{ $selectedType === $value ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-sm-6 col-md-3">
                    <label class="form-label fw-semibold" style="font-size:13px">Category</label>
                    <select name="category" class="form-select">
                        <option value="">All Categories</option>
                        @foreach($categories as $category)
                            <option value="{{ $category->id }}" {{ $selectedCategory === $category->id ? 'selected' : '' }}>
                                {{ str_repeat('›  ', $category->depth) }}{{ $category->name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-sm-6 col-md-3 d-flex gap-2">
                    <button type="submit" class="btn btn-primary flex-grow-1">
                        <i class="bi bi-search me-1"></i>Load Items
                    </button>
                    @if($filtersApplied)
                    <a href="{{ route('masters.opening-balance.index', ['tab' => 'items']) }}" class="btn btn-outline-secondary" title="Clear filters">
                        <i class="bi bi-x-lg"></i>
                    </a>
                    @endif
                </div>
            </div>
            <p class="text-muted mb-0 mt-3" style="font-size:12.5px">
                <i class="bi bi-info-circle me-1"></i>
                Select a warehouse and optional type/category, then load items to enter opening balances part by part.
            </p>
        </form>
    </div>
</div>

@if(!$filtersApplied)
<div class="card">
    <div class="card-body text-center py-5 text-muted">
        <i class="bi bi-box-seam d-block mb-2" style="font-size:2rem;opacity:.5"></i>
        Choose a <strong>Warehouse</strong> and click <strong>Load Items</strong> to begin entering opening balances.
    </div>
</div>
@else
<form method="POST" action="{{ route('masters.opening-balance.store', ['tab' => 'items']) }}" id="obItemsForm">
    @csrf
    <input type="hidden" name="filter_warehouse" value="{{ $selectedWarehouse }}">
    @if($selectedType)
        <input type="hidden" name="filter_item_type" value="{{ $selectedType }}">
    @endif
    @if($selectedCategory)
        <input type="hidden" name="filter_category" value="{{ $selectedCategory }}">
    @endif

    <div class="card mb-3">
        <div class="card-body">
            <div class="row g-3 align-items-end">
                <div class="col-sm-6 col-md-4 col-lg-3">
                    <label class="form-label fw-semibold" style="font-size:13px">As of Date</label>
                    <input type="date" name="as_of_date" class="form-control" value="{{ $asOfDate }}" {{ $canSave ? '' : 'readonly' }}>
                </div>
                <div class="col-sm-6 col-md-4 col-lg-5">
                    <label class="form-label fw-semibold" style="font-size:13px">Search</label>
                    <input type="search" class="form-control ob-filter" placeholder="Filter loaded items by code or name…" data-target="#obItemsTable">
                </div>
                <div class="col-12 col-lg-4">
                    @php
                        $whName = $warehouses->firstWhere('id', $selectedWarehouse)?->name ?? 'Selected warehouse';
                    @endphp
                    <div class="alert alert-info mb-0 py-2" style="font-size:12.5px">
                        <i class="bi bi-building me-1"></i>
                        Entering opening balance for <strong>{{ $whName }}</strong>. Inventory debits on save; <strong>Opening Balance Equity</strong> credits the offset.
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
            <span class="fw-semibold"><i class="bi bi-box-seam me-2 text-primary"></i>Item Opening Balances</span>
            <span class="text-muted" style="font-size:12.5px">{{ $rows->count() }} items</span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0 ob-table" id="obItemsTable">
                    <thead class="table-light">
                        <tr>
                            <th style="min-width:90px">Code</th>
                            <th style="min-width:180px">Item Name</th>
                            <th class="d-none d-lg-table-cell" style="min-width:120px">Type</th>
                            <th class="d-none d-xl-table-cell" style="min-width:140px">Category</th>
                            <th class="text-center" style="min-width:70px">Dr/Cr</th>
                            <th class="text-end" style="min-width:120px">Quantity</th>
                            <th class="text-end" style="min-width:130px">Rate</th>
                            <th class="text-end" style="min-width:130px">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($rows as $index => $row)
                        @php
                            $typeLabels = ['inventory' => 'Inventory', 'service' => 'Service', 'non_inventory' => 'Non-Inventory'];
                        @endphp
                        <tr data-search="{{ strtolower($row->code . ' ' . $row->name) }}" class="ob-item-row">
                            <td><code class="fw-semibold" style="font-size:12.5px">{{ $row->code }}</code></td>
                            <td style="font-size:13.5px">{{ $row->name }}</td>
                            <td class="d-none d-lg-table-cell text-muted" style="font-size:12.5px">{{ $typeLabels[$row->type] ?? $row->type }}</td>
                            <td class="d-none d-xl-table-cell text-muted" style="font-size:12.5px">{{ $row->category?->name ?? '—' }}</td>
                            <td class="text-center ob-drcr-cell">
                                @include('masters.opening-balance.partials._dr-cr-badge', [
                                    'drCr' => $row->opening_dr_cr,
                                    'amount' => $row->opening_amount,
                                ])
                            </td>
                            <td class="text-end">
                                <input type="hidden" name="rows[{{ $index }}][entity_id]" value="{{ $row->id }}">
                                <input type="hidden" name="rows[{{ $index }}][warehouse_id]" value="{{ $selectedWarehouse }}">
                                <input type="number"
                                       name="rows[{{ $index }}][quantity]"
                                       class="form-control form-control-sm text-end ms-auto ob-qty"
                                       step="0.0001"
                                       min="0"
                                       value="{{ old('rows.'.$index.'.quantity', $row->opening_quantity) }}"
                                       {{ $canSave ? '' : 'readonly' }}>
                            </td>
                            <td class="text-end">
                                <input type="number"
                                       name="rows[{{ $index }}][rate]"
                                       class="form-control form-control-sm text-end ms-auto ob-rate"
                                       step="0.000001"
                                       min="0"
                                       value="{{ old('rows.'.$index.'.rate', $row->opening_rate) }}"
                                       {{ $canSave ? '' : 'readonly' }}>
                            </td>
                            <td class="text-end ob-amount-cell">
                                <span class="ob-amount fw-semibold text-money">{{ $currencySymbol }}{{ number_format($row->opening_amount, 2) }}</span>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="8" class="text-center py-4 text-muted">No items match the selected filters.</td>
                        </tr>
                        @endforelse
                    </tbody>
                    @if($rows->isNotEmpty())
                    <tfoot class="table-light">
                        <tr>
                            <td colspan="5" class="text-end fw-semibold d-none d-xl-table-cell">Totals (visible rows)</td>
                            <td colspan="3" class="text-end fw-semibold d-xl-none">Totals (visible rows)</td>
                            <td class="text-end fw-bold ob-total-qty text-money">0</td>
                            <td></td>
                            <td class="text-end fw-bold ob-total-amount text-money">{{ $currencySymbol }}0.00</td>
                        </tr>
                    </tfoot>
                    @endif
                </table>
            </div>
        </div>
        @if($canSave && $rows->isNotEmpty())
        <div class="card-footer text-end">
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-check-lg me-1"></i>Save Items
            </button>
        </div>
        @endif
    </div>
</form>
@endif

@push('scripts')
<script>
(function () {
    var symbol = @json($currencySymbol);

    function parseNum(value) {
        var n = parseFloat(value);
        return isNaN(n) ? 0 : n;
    }

    function formatMoney(amount) {
        return symbol + amount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function updateRow(row) {
        var qty = parseNum(row.querySelector('.ob-qty')?.value);
        var rate = parseNum(row.querySelector('.ob-rate')?.value);
        var amount = qty * rate;
        var amountEl = row.querySelector('.ob-amount');
        var drcrCell = row.querySelector('.ob-drcr-cell');
        if (amountEl) {
            amountEl.textContent = formatMoney(amount);
        }
        if (drcrCell) {
            drcrCell.innerHTML = amount >= 0.005
                ? '<span class="badge text-bg-success" style="font-size:11px;min-width:34px">DR</span>'
                : '<span class="text-muted">—</span>';
        }
    }

    function updateTotals() {
        var table = document.getElementById('obItemsTable');
        if (!table) return;

        var totalQty = 0;
        var totalAmount = 0;

        table.querySelectorAll('tbody tr.ob-item-row').forEach(function (row) {
            if (row.style.display === 'none') return;
            totalQty += parseNum(row.querySelector('.ob-qty')?.value);
            totalAmount += parseNum(row.querySelector('.ob-qty')?.value) * parseNum(row.querySelector('.ob-rate')?.value);
        });

        var qtyEl = table.querySelector('.ob-total-qty');
        var amountEl = table.querySelector('.ob-total-amount');
        if (qtyEl) qtyEl.textContent = totalQty.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 4 });
        if (amountEl) amountEl.textContent = formatMoney(totalAmount);
    }

    document.querySelectorAll('.ob-item-row').forEach(function (row) {
        row.querySelectorAll('.ob-qty, .ob-rate').forEach(function (input) {
            input.addEventListener('input', function () {
                updateRow(row);
                updateTotals();
            });
        });
        updateRow(row);
    });

    updateTotals();

    document.querySelectorAll('.ob-filter').forEach(function (input) {
        input.addEventListener('input', function () {
            var q = this.value.trim().toLowerCase();
            var table = document.querySelector(this.dataset.target);
            if (!table) return;
            table.querySelectorAll('tbody tr[data-search]').forEach(function (row) {
                row.style.display = !q || row.dataset.search.includes(q) ? '' : 'none';
            });
            updateTotals();
        });
    });
})();
</script>
@endpush
