<form method="POST" action="{{ route('masters.opening-balance.store', ['tab' => 'customers']) }}" id="obCustomersForm">
    @csrf

    <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 by code or name…" data-target="#obCustomersTable">
                </div>
                <div class="col-12 col-lg-4">
                    <div class="alert alert-info mb-0 py-2" style="font-size:12.5px">
                        <i class="bi bi-info-circle me-1"></i>
                        Positive balances debit A/R; negative balances credit A/R. <strong>Opening Balance Equity</strong> is 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-people me-2 text-primary"></i>Customer Opening Balances</span>
            <span class="text-muted" style="font-size:12.5px">{{ $rows->count() }} customers</span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0 ob-table" id="obCustomersTable">
                    <thead class="table-light">
                        <tr>
                            <th style="min-width:90px">Code</th>
                            <th style="min-width:220px">Customer Name</th>
                            <th class="text-center" style="min-width:70px">Dr/Cr</th>
                            <th class="text-end" style="min-width:150px">Opening Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($rows as $index => $row)
                        <tr data-search="{{ strtolower(($row->code ?? '') . ' ' . $row->name) }}" class="ob-party-row" data-party="customer">
                            <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="text-center ob-drcr-cell">
                                @include('masters.opening-balance.partials._dr-cr-badge', [
                                    'drCr' => $row->opening_dr_cr,
                                    'amount' => abs($row->opening_balance),
                                ])
                            </td>
                            <td class="text-end">
                                <input type="hidden" name="rows[{{ $index }}][entity_id]" value="{{ $row->id }}">
                                <input type="number"
                                       name="rows[{{ $index }}][balance]"
                                       class="form-control form-control-sm text-end ms-auto ob-balance-input"
                                       step="0.01"
                                       value="{{ old('rows.'.$index.'.balance', $row->opening_balance) }}"
                                       {{ $canSave ? '' : 'readonly' }}>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="4" class="text-center py-4 text-muted">No customers found.</td>
                        </tr>
                        @endforelse
                    </tbody>
                </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 Customers
            </button>
        </div>
        @endif
    </div>
</form>

@push('scripts')
<script>
(function () {
    function renderBadge(cell, side) {
        if (!cell) return;
        cell.innerHTML = side
            ? '<span class="badge ' + (side === 'dr' ? 'text-bg-success' : 'text-bg-danger') + '" style="font-size:11px;min-width:34px">' + side.toUpperCase() + '</span>'
            : '<span class="text-muted">—</span>';
    }

    document.querySelectorAll('.ob-party-row[data-party="customer"]').forEach(function (row) {
        var input = row.querySelector('.ob-balance-input');
        var cell = row.querySelector('.ob-drcr-cell');
        if (!input) return;
        input.addEventListener('input', function () {
            var balance = parseFloat(input.value) || 0;
            var side = Math.abs(balance) < 0.005 ? null : (balance >= 0 ? 'dr' : 'cr');
            renderBadge(cell, side);
        });
    });
})();

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';
        });
    });
});
</script>
@endpush
