@extends('layouts.app')
@section('title', 'Fee Challans')
@section('page_title', 'Fee Challans')
@section('breadcrumbs')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Home</a></li><li class="breadcrumb-item active">Challans</li>
@endsection
@section('page_actions')
    @can('fees.create')<a href="{{ route('challans.create') }}" class="btn btn-primary"><i class="bi bi-receipt me-1"></i>Generate Challans</a>@endcan
@endsection

@section('content')
    @can('fees.collect')
    <div class="card mb-3"><div class="card-body py-2">
        <form class="row g-2 align-items-end" id="challanCollectForm" onsubmit="return false">
            <div class="col-md-5">
                <label class="form-label small mb-1"><i class="bi bi-cash-coin me-1"></i>Quick Collect — enter challan number</label>
                <div class="input-group input-group-sm">
                    <span class="input-group-text bg-white"><i class="bi bi-search text-muted"></i></span>
                    <input type="text" id="challanLookup" class="form-control" placeholder="e.g. CH-2026-00012" autocomplete="off">
                    <button type="button" id="challanLookupBtn" class="btn btn-primary">Find & Collect</button>
                </div>
                <div class="small text-danger mt-1 d-none" id="challanLookupErr"></div>
            </div>
        </form>
    </div></div>
    @endcan

    <div class="card mb-3"><div class="card-body py-2">
        <form method="GET" class="d-flex gap-2 align-items-center">
            <span class="small text-muted">Filter:</span>
            <a href="{{ route('challans.index') }}" class="btn btn-sm {{ !$status ? 'btn-primary' : 'btn-light border' }}">All</a>
            @foreach(['unpaid','partial','paid','waived'] as $st)
                <a href="{{ route('challans.index', ['status'=>$st]) }}" class="btn btn-sm text-capitalize {{ $status===$st ? 'btn-primary' : 'btn-light border' }}">{{ $st }}</a>
            @endforeach
        </form>
    </div></div>

    <div class="card"><div class="card-body">
        <table class="table table-hover align-middle">
            <thead><tr><th>Challan #</th><th>Family</th><th>Title</th><th>Due</th><th class="text-end">Net</th><th class="text-end">Paid</th><th class="text-end">Balance</th><th class="text-center">Status</th><th class="text-end">Actions</th></tr></thead>
            <tbody>
                @forelse($challans as $ch)
                    <tr>
                        <td><a href="{{ route('challans.show', $ch) }}" class="fw-semibold text-decoration-none">{{ $ch->challan_number }}</a></td>
                        <td class="small"><a href="{{ route('families.show', $ch->family_id) }}" class="text-decoration-none">{{ $ch->family?->family_code }}</a></td>
                        <td class="small">{{ $ch->title }}</td>
                        <td class="small">{{ optional($ch->due_date)->format('d M Y') }}</td>
                        <td class="text-end">{{ number_format($ch->net_payable) }}</td>
                        <td class="text-end text-success">{{ number_format($ch->paid_amount) }}</td>
                        <td class="text-end fw-semibold {{ $ch->balance > 0 ? 'text-danger' : '' }}">{{ number_format($ch->balance) }}</td>
                        <td class="text-center"><span class="badge bg-soft-{{ $ch->status_color }} text-capitalize">{{ $ch->status }}</span></td>
                        <td class="text-end">
                            <a href="{{ route('challans.show', $ch) }}" class="btn btn-sm btn-light border"><i class="bi bi-eye"></i></a>
                            <a href="{{ route('challans.print', $ch) }}" target="_blank" class="btn btn-sm btn-light border"><i class="bi bi-printer"></i></a>
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="9" class="text-center text-muted py-4">No challans found.</td></tr>
                @endforelse
            </tbody>
        </table>
        {{ $challans->links() }}
    </div></div>

    @can('fees.collect')
    {{-- Quick Collect Payment modal --}}
    <div class="modal fade" id="collectModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <form method="POST" id="collectForm" class="modal-content">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title"><i class="bi bi-cash-coin me-1"></i>Collect Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="bg-light rounded p-2 mb-3 small">
                        <div class="d-flex justify-content-between"><span class="text-muted">Challan</span><b id="cm_number"></b></div>
                        <div class="d-flex justify-content-between"><span class="text-muted">Family</span><span id="cm_family"></span></div>
                        <div class="d-flex justify-content-between"><span class="text-muted">Father Name</span><span id="cm_father" class="fw-semibold"></span></div>
                        <div class="d-flex justify-content-between"><span class="text-muted">Student(s)</span><span id="cm_students" class="text-end"></span></div>
                        <div class="d-flex justify-content-between"><span class="text-muted">Bill</span><span id="cm_title"></span></div>
                        <div class="d-flex justify-content-between"><span class="text-muted">Balance</span><b class="text-danger" id="cm_balance"></b></div>
                    </div>
                    <div class="alert alert-success py-2 small d-none" id="cm_settled">This challan is already fully paid.</div>
                    <div class="row g-2" id="cm_fields">
                        <div class="col-6">
                            <label class="form-label small">Amount</label>
                            <input type="number" step="0.01" min="0.01" name="amount" id="cm_amount" class="form-control" required>
                        </div>
                        <div class="col-6">
                            <label class="form-label small">Date</label>
                            <input type="date" name="payment_date" value="{{ now()->format('Y-m-d') }}" class="form-control" required
                                   @unless(auth()->user()->isSuperAdmin()) readonly title="Only the Super Admin can change the collection date" @endunless>
                        </div>
                        <div class="col-12">
                            <label class="form-label small">Method</label>
                            <select name="payment_method_id" id="cm_method" class="form-select" required></select>
                            <div class="form-text" id="cm_acct"></div>
                        </div>
                        <div class="col-12">
                            <label class="form-label small">Reference</label>
                            <input type="text" name="reference" class="form-control" placeholder="Txn ID / cheque no.">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <a href="#" id="cm_open" class="btn btn-light border me-auto" target="_blank"><i class="bi bi-box-arrow-up-right me-1"></i>Open Challan</a>
                    <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cancel</button>
                    <button class="btn btn-success" id="cm_submit"><i class="bi bi-check-lg me-1"></i>Record Payment</button>
                </div>
            </form>
        </div>
    </div>

    @push('scripts')
    <script>
        (function () {
            const url = @json(route('challans.lookup'));
            const input = document.getElementById('challanLookup');
            const btn = document.getElementById('challanLookupBtn');
            const err = document.getElementById('challanLookupErr');
            const modalEl = document.getElementById('collectModal');
            const modal = new bootstrap.Modal(modalEl);
            const form = document.getElementById('collectForm');
            const methodSel = document.getElementById('cm_method');
            const acct = document.getElementById('cm_acct');

            function showErr(m) { err.textContent = m; err.classList.remove('d-none'); }

            function lookup() {
                err.classList.add('d-none');
                const q = input.value.trim();
                if (!q) { showErr('Enter a challan number.'); return; }
                btn.disabled = true; btn.textContent = 'Searching…';
                fetch(url + '?q=' + encodeURIComponent(q), { headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                    .then(r => r.json())
                    .then(d => {
                        if (!d.found) { showErr(d.message || 'Not found.'); return; }
                        const c = d.challan;
                        document.getElementById('cm_number').textContent = c.number;
                        document.getElementById('cm_family').textContent = c.family;
                        document.getElementById('cm_father').textContent = c.father || '-';
                        document.getElementById('cm_students').textContent = c.students || '-';
                        document.getElementById('cm_title').textContent = c.title;
                        document.getElementById('cm_balance').textContent = 'Rs ' + Number(c.balance).toLocaleString();
                        document.getElementById('cm_open').href = c.show_url;
                        form.action = c.pay_url;
                        // methods
                        methodSel.innerHTML = '';
                        (d.methods || []).forEach(m => {
                            const o = new Option(m.label, m.id);
                            o.dataset.acct = m.account || '';
                            methodSel.appendChild(o);
                        });
                        updateAcct();
                        // settled?
                        const settled = c.settled || c.balance <= 0;
                        document.getElementById('cm_settled').classList.toggle('d-none', !settled);
                        document.getElementById('cm_fields').classList.toggle('d-none', settled);
                        document.getElementById('cm_submit').classList.toggle('d-none', settled);
                        const amt = document.getElementById('cm_amount');
                        amt.value = c.balance; amt.max = c.balance;
                        modal.show();
                    })
                    .catch(() => showErr('Lookup failed.'))
                    .finally(() => { btn.disabled = false; btn.textContent = 'Find & Collect'; });
            }
            function updateAcct() {
                const o = methodSel.options[methodSel.selectedIndex];
                acct.textContent = o && o.dataset.acct ? ('Account #: ' + o.dataset.acct) : '';
            }
            methodSel.addEventListener('change', updateAcct);
            btn.addEventListener('click', lookup);
            input.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); lookup(); } });
        })();
    </script>
    @endpush
    @endcan
@endsection
