<div class="setup-container">
    <div class="form-grid-2">
        <!-- Form Column -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">نئی ادائیگی اکاؤنٹ (کیش/بینک)</h3>
            </div>
            <div class="card-body">
                <form id="accountForm">
                    <div class="form-group">
                        <label class="form-label">اکاؤنٹ کا نام</label>
                        <input type="text" class="form-control" name="name" required placeholder="مثلاً: Cash in Hand, HBL, UBL...">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">ابتدائی بیلنس (RS)</label>
                        <input type="number" class="form-control" name="balance" value="0">
                    </div>

                    <div class="form-group">
                        <label class="form-label">اکاؤنٹ کی قسم</label>
                        <select class="form-control" name="sub_type" required>
                            <option value="cash">کیش (Cash)</option>
                            <option value="bank">بینک (Bank)</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">براہ راست جمع کی اجازت دیں (Allow Direct Deposit)?</label>
                        <select class="form-control" name="allow_direct_deposit">
                            <option value="0">نہ کریں (No)</option>
                            <option value="1">ہاں، اجازت دیں (Yes)</option>
                        </select>
                        <small class="text-muted">اگر 'ہاں' کریں گے تو روزنامچہ کے 'براہ راست جمع' ڈراپ ڈاؤن میں یہ نظر آئے گا۔</small>
                    </div>

                    <div class="form-group">
                        <label class="form-label">کارڈ شروع کرنے کی تاریخ (Cycle Start Date)</label>
                        <input type="date" class="form-control" name="cycle_start_date">
                        <small class="text-muted">جس دن سے کارڈ کا نیا سائیکل شروع ہوا ہے۔</small>
                    </div>

                    <div class="form-group">
                        <label class="form-label">الرٹ کا وقفہ (دنوں میں)</label>
                        <input type="number" class="form-control" name="alert_interval_days" value="0">
                        <small class="text-muted">مثلاً: ہر 47 دن بعد الرٹ کیلئے 47 لکھیں۔</small>
                    </div>

                    <div class="form-actions" style="margin-top: var(--sp-6);">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-save"></i> محفوظ کریں
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- List Column -->
        <div class="card">
            <div class="card-header" style="flex-direction: column; align-items: stretch; gap: 10px;">
                <h3 class="card-title">دستیاب اکاؤنٹس</h3>
                <!-- Search Bar -->
                <div style="position: relative;">
                    <i class="fas fa-search" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: var(--text-muted); pointer-events: none;"></i>
                    <input type="text" id="accountSearchInput" class="form-control" placeholder="اکاؤنٹ تلاش کریں..." style="padding-right: 38px; padding-left: 12px;">
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table m-0">
                        <thead>
                            <tr>
                                <th>اکاؤنٹ کا نام</th>
                                <th>موجودہ بیلنس</th>
                                <th>براہ راست جمع</th>
                                <th>ایکشن</th>
                            </tr>
                        </thead>
                        <tbody id="accountTableBody">
                            <!-- Populated via initSetupAccount -->
                        </tbody>
                    </table>
                </div>
                <!-- Pagination Footer -->
                <div id="accountPaginationBar" style="display: flex; align-items: center; justify-content: space-between; padding: 10px 16px; border-top: 1px solid var(--border-color); flex-wrap: wrap; gap: 8px;">
                    <div id="accountPaginationInfo" style="font-size: 0.85rem; color: var(--text-muted);"></div>
                    <div id="accountPaginationBtns" style="display: flex; gap: 6px; flex-wrap: wrap;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
async function initSetupAccount() {
    const $form = $('#accountForm');
    const $tableBody = $('#accountTableBody');
    const $submitBtn = $form.find('button[type="submit"]');
    const $formTitle = $('.card-title').first();
    let editingId = null;

    // --- Pagination & Search state ---
    const PAGE_SIZE = 10;
    let currentPage = 1;
    let searchQuery = '';

    async function fetchAndRenderAccounts() {
        try {
            $tableBody.html('<tr><td colspan="4" class="text-center">لوڈنگ...</td></tr>');
            const res = await API.get('/accounts', { type: 'bank_cash' });
            MandiData.accounts = res.data;
            currentPage = 1;
            renderAccounts();
        } catch (err) {}
    }

    function getFilteredAccounts() {
        if (!MandiData.accounts) return [];
        const q = searchQuery.trim().toLowerCase();
        if (!q) return MandiData.accounts;
        return MandiData.accounts.filter(a =>
            a.name.toLowerCase().includes(q) ||
            (a.sub_type && a.sub_type.toLowerCase().includes(q))
        );
    }

    function renderAccounts() {
        const filtered = getFilteredAccounts();
        const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
        if (currentPage > totalPages) currentPage = totalPages;

        const start = (currentPage - 1) * PAGE_SIZE;
        const paginated = filtered.slice(start, start + PAGE_SIZE);

        if (filtered.length === 0) {
            $tableBody.html('<tr><td colspan="4" class="text-center">کوئی اکاؤنٹ نہیں ملا۔</td></tr>');
            $('#accountPaginationInfo').text('');
            $('#accountPaginationBtns').html('');
            return;
        }

        let html = '';
        paginated.forEach(a => {
            const allowDepBadge = parseInt(a.allow_direct_deposit) === 1
                ? '<span style="background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; padding: 3px 8px; font-size: 0.85rem; border-radius: 4px; display: inline-block; font-weight: bold;">ہاں (Allowed)</span>'
                : '<span style="background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; padding: 3px 8px; font-size: 0.85rem; border-radius: 4px; display: inline-block; font-weight: bold;">نہ کریں (No)</span>';

            html += `
                <tr class="${editingId == a.id ? 'table-active' : ''}">
                    <td class="fw-bold fs-5">${a.name} (${a.sub_type})</td>
                    <td class="text-success fw-bold">${Utils.formatNumber(a.opening_balance)}</td>
                    <td>${allowDepBadge}</td>
                    <td>
                        <button class="btn btn-outline btn-sm me-1" onclick="editAccount(${a.id})" title="تبدیل کریں">
                            <i class="fas fa-edit"></i>
                        </button>
                        ${parseInt(a.is_system) !== 1 ? `
                            <button class="btn btn-danger btn-sm" onclick="deleteAccount(${a.id}, '${a.name}')" title="حذف کریں">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                        ` : ''}
                    </td>
                </tr>
            `;
        });
        $tableBody.html(html);

        // --- Pagination Info ---
        const from = start + 1;
        const to = Math.min(start + PAGE_SIZE, filtered.length);
        $('#accountPaginationInfo').text(`دکھا رہے ہیں ${from}–${to} از ${filtered.length} اکاؤنٹس`);

        // --- Pagination Buttons ---
        let btnsHtml = '';

        // Prev button
        btnsHtml += `<button class="btn btn-sm btn-outline" onclick="saGoPage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''} title="پچھلا صفحہ">
            <i class="fas fa-chevron-right"></i>
        </button>`;

        // Page number buttons (max 5 visible)
        const maxVisible = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
        let endPage = Math.min(totalPages, startPage + maxVisible - 1);
        if (endPage - startPage < maxVisible - 1) startPage = Math.max(1, endPage - maxVisible + 1);

        for (let p = startPage; p <= endPage; p++) {
            btnsHtml += `<button class="btn btn-sm ${p === currentPage ? 'btn-primary' : 'btn-outline'}" onclick="saGoPage(${p})">${p}</button>`;
        }

        // Next button
        btnsHtml += `<button class="btn btn-sm btn-outline" onclick="saGoPage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''} title="اگلا صفحہ">
            <i class="fas fa-chevron-left"></i>
        </button>`;

        $('#accountPaginationBtns').html(btnsHtml);
        $('#accountPaginationBar').toggle(totalPages > 1 || filtered.length > 0);
    }

    window.saGoPage = function(page) {
        const filtered = getFilteredAccounts();
        const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
        if (page < 1 || page > totalPages) return;
        currentPage = page;
        renderAccounts();
    };

    // Live search
    $('#accountSearchInput').on('input', function() {
        searchQuery = $(this).val();
        currentPage = 1;
        renderAccounts();
    });

    window.editAccount = function(id) {
        const acc = MandiData.accounts.find(a => a.id == id);
        if (!acc) return;

        editingId = id;
        $form.find('input[name="name"]').val(acc.name).focus();
        $form.find('input[name="balance"]').val(acc.opening_balance).prop('disabled', true);
        $form.find('select[name="sub_type"]').val(acc.sub_type || 'cash');
        $form.find('select[name="allow_direct_deposit"]').val(acc.allow_direct_deposit || 0);
        $form.find('input[name="cycle_start_date"]').val(acc.cycle_start_date || '');
        $form.find('input[name="alert_interval_days"]').val(acc.alert_interval_days || 0);

        $formTitle.html('<i class="fas fa-edit text-accent"></i> اکاؤنٹ کی تبدیلی');
        $submitBtn.html('<i class="fas fa-save"></i> تبدیلی کو محفوظ کریں').removeClass('btn-primary').addClass('btn-accent');

        if ($('#cancelAccEditBtn').length === 0) {
            $submitBtn.after('<button type="button" id="cancelAccEditBtn" class="btn btn-outline w-100 mt-2" onclick="cancelAccountEdit()">کینسل (Cancel)</button>');
        }
        renderAccounts();
        // Scroll form into view on mobile
        $form[0].scrollIntoView({ behavior: 'smooth', block: 'start' });
    };

    window.cancelAccountEdit = function() {
        editingId = null;
        $form[0].reset();
        $form.find('input[name="balance"]').prop('disabled', false);
        $form.find('select[name="allow_direct_deposit"]').val(0);
        $formTitle.text('نئی ادائیگی اکاؤنٹ (کیش/بینک)');
        $submitBtn.html('<i class="fas fa-save"></i> محفوظ کریں').removeClass('btn-accent').addClass('btn-primary');
        $('#cancelAccEditBtn').remove();
        renderAccounts();
    };

    window.deleteAccount = async function(id, name) {
        if (!confirm(`کیا آپ واقعی "${name}" اکاؤنٹ کو حذف کرنا چاہتے ہیں؟`)) return;
        try {
            const res = await API.delete('/accounts', id);
            if (res.success) {
                Toast.success("✅ " + res.message);
                if (editingId == id) cancelAccountEdit();
                fetchAndRenderAccounts();
            }
        } catch (err) {}
    };

    fetchAndRenderAccounts();

    $form.on('submit', async function(e) {
        e.preventDefault();

        const payload = {
            name: $form.find('input[name="name"]').val().trim(),
            type: 'bank_cash',
            sub_type: $form.find('select[name="sub_type"]').val(),
            allow_direct_deposit: parseInt($form.find('select[name="allow_direct_deposit"]').val()) || 0,
            cycle_start_date: $form.find('input[name="cycle_start_date"]').val() || null,
            alert_interval_days: parseInt($form.find('input[name="alert_interval_days"]').val()) || 0
        };

        if (!editingId) {
            payload.opening_balance = parseFloat($form.find('input[name="balance"]').val()) || 0;
            payload.balance_type = 'Dr';
        }

        if (!payload.name) return;

        $submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> محفوظ ہو رہا ہے...');

        try {
            let res;
            if (editingId) {
                res = await API.put('/accounts/' + editingId, payload);
            } else {
                res = await API.post('/accounts', payload);
            }

            if (res.success) {
                Toast.success("✅ " + res.message);
                cancelAccountEdit();
                fetchAndRenderAccounts();
            }
        } catch (err) {
        } finally {
            if (!editingId) {
                $submitBtn.prop('disabled', false).html('<i class="fas fa-save"></i> محفوظ کریں');
            } else {
                $submitBtn.prop('disabled', false).html('<i class="fas fa-save"></i> تبدیلی کو محفوظ کریں');
            }
        }
    });

    Utils.setupEnterNavigation('#accountForm');
}
</script>
