@php
    $selectedAccountType = $accountFilters['section'] ?? '';
@endphp

<div class="card mb-3">
    <div class="card-header fw-semibold">
        <i class="bi bi-funnel me-2 text-primary"></i>Filter Accounts
    </div>
    <div class="card-body">
        <form method="GET" action="{{ route('masters.opening-balance.index') }}">
            <input type="hidden" name="tab" value="accounts">
            <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">Account Type</label>
                    <select name="account_type" class="form-select">
                        <option value="">All Account Types</option>
                        @foreach($accountTypeGroups as $types)
                            @foreach($types as $value => $label)
                                <option value="{{ $value }}" {{ $selectedAccountType === $value ? 'selected' : '' }}>{{ $label }}</option>
                            @endforeach
                        @endforeach
                    </select>
                </div>
                <div class="col-sm-6 col-md-4 col-lg-3 d-flex gap-2">
                    <button type="submit" class="btn btn-primary flex-grow-1">
                        <i class="bi bi-search me-1"></i>Load Accounts
                    </button>
                    @if($selectedAccountType)
                    <a href="{{ route('masters.opening-balance.index', ['tab' => 'accounts']) }}" class="btn btn-outline-secondary" title="Clear filter">
                        <i class="bi bi-x-lg"></i>
                    </a>
                    @endif
                </div>
                <div class="col-12 col-lg-6">
                    <div class="alert alert-info mb-0 py-2" style="font-size:12.5px">
                        <i class="bi bi-info-circle me-1"></i>
                        Filter by account type (Bank, A/R, Fixed Assets, etc.). Each balance posts as Debit or Credit; <strong>Opening Balance Equity</strong> is the offset.
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<form method="POST" action="{{ route('masters.opening-balance.store', ['tab' => 'accounts']) }}" id="obAccountsForm">
    @csrf
    @if($selectedAccountType)
        <input type="hidden" name="filter_account_type" value="{{ $selectedAccountType }}">
    @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 accounts by code or name…" data-target="#obAccountsTable">
                </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-journal-text me-2 text-primary"></i>Account Opening Balances</span>
            <span class="text-muted" style="font-size:12.5px">{{ $rows->count() }} accounts</span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0 ob-table" id="obAccountsTable">
                    <thead class="table-light">
                        <tr>
                            <th style="min-width:90px">Code</th>
                            <th style="min-width:180px">Account Name</th>
                            <th class="d-none d-md-table-cell">Type</th>
                            <th class="text-end" style="min-width:130px">Current Balance</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-account-row"
                            data-account-type="{{ $row->type }}">
                            <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-md-table-cell text-muted" style="font-size:12.5px">{{ $row->account_type_label }}</td>
                            <td class="text-end text-money text-muted" style="font-size:13px">
                                {{ $currencySymbol }}{{ number_format($row->current_balance, 2) }}
                            </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="6" class="text-center py-4 text-muted">No accounts match the selected filter.</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 Accounts
            </button>
        </div>
        @endif
    </div>
</form>

@push('scripts')
<script>
(function () {
    var creditNormalTypes = ['liability', 'equity', 'income'];

    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-account-row').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 creditNormal = creditNormalTypes.indexOf(row.dataset.accountType) !== -1;
            var side = null;
            if (Math.abs(balance) >= 0.005) {
                side = creditNormal
                    ? (balance >= 0 ? 'cr' : 'dr')
                    : (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
