<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ইউনিভার্সাল ড্যাশবোর্ড - বিডিআরআইএস</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <style>
        .required-field::after { content: " *"; color: red; }
        .widget-holder { margin-bottom: 20px; }
        .widget-bg { background: #fff; padding: 25px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .form-group label { font-weight: 600; color: #333; }
        #resultTable td .material-icons { font-size: 20px; vertical-align: middle; }
        #resultTable td a { margin-right: 8px; }
        #applicationDetailsPre { max-height: 60vh; overflow: auto; background: #f8f9fa; padding: 12px; border-radius: 6px; }
        .summary-card { cursor: pointer; transition: transform 0.2s; }
        .summary-card:hover { transform: scale(1.05); }
    </style>
</head>
<body class="bg-light">

<div class="container py-5">
    <div id="warning-message-div" class="alert alert-warning alert-dismissible fade show" role="alert" style="display: none">
        <strong>সতর্কীকরণ! </strong> <span id="warning-message-span"></span>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
        </button>
    </div>

    <div class="row">
        <div class="col-md-12 widget-holder">
            <div class="widget-bg">
                <a href="index.php" class="btn btn-outline-secondary btn-sm mb-3">ফিরে যান</a>

                <!-- Direct Print Section -->
                <div class="card mb-4 shadow-sm" style="border: 1px solid #17a2b8;">
                    <div class="card-header bg-info text-white py-2">
                        <h6 class="mb-0"><i class="material-icons" style="vertical-align: middle; font-size: 18px;">print</i> যেকোনো ইউনিয়নের আবেদন সরাসরি প্রিন্ট (পাবলিক/অফিস)</h6>
                    </div>
                    <div class="card-body py-3">
                        <div class="input-group">
                            <input type="text" id="directPrintData" class="form-control" placeholder="এখানে সম্পূর্ণ লিংকটি বা data=... এর অংশটি পেস্ট করুন">
                            <div class="input-group-append">
                                <button type="button" class="btn btn-dark" onclick="goDirectAction('app')"><i class="material-icons" style="font-size: 16px; vertical-align: text-bottom;">print</i> আবেদন প্রিন্ট</button>
                                <button type="button" class="btn btn-warning" onclick="goDirectAction('receipt')"><i class="material-icons" style="font-size: 16px; vertical-align: text-bottom;">receipt</i> রশিদ প্রিন্ট</button>
                            </div>
                        </div>
                        <small class="text-muted mt-1 d-block">পাবলিক সার্ভার থেকে আসা যেকোনো আবেদন প্রিন্ট করতে বক্সে লিংকটি দিয়ে প্রিন্ট বাটনে ক্লিক করুন।</small>
                    </div>
                </div>

                <form id="geoSearchForm">
                    <input type="hidden" name="_csrf" value="_z1vkjjrMD3VOSEYCy3rcvvLTOdH_7cl_8PpKz4kJZx-i2YvzwUJpQ3TBw74Cxh9aADfRcj-Yd92zNMIxqLeHw4XHagf71UZ">

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label required-field">দেশ</label>
                                <div class="col-md-8">
                                    <select class="form-control geoSelect" data-geo-group="officeAddr" data-geo-order="0">
                                        <option value="1">বাংলাদেশ</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label required-field">বিভাগ</label>
                                <div class="col-md-8">
                                    <select class="form-control geoSelect" id="officeAddrDiv" data-geo-group="officeAddr" data-geo-order="1">
                                        <option value="-1">বিভাগ নির্বাচন করুন</option>
                                        <option value="5514">রংপুর বিভাগ</option>
                                        <option value="5501">ঢাকা বিভাগ</option>
                                        <option value="5511">রাজশাহী বিভাগ</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6 geo-container" style="display:none">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label required-field">জেলা</label>
                                <div class="col-md-8">
                                    <select class="form-control geoSelect" id="officeAddrDist" data-geo-group="officeAddr" data-geo-order="2">
                                        <option value="-1">জেলা নির্বাচন করুন</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6 geo-container" style="display:none">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label required-field">উপজেলা</label>
                                <div class="col-md-8">
                                    <select class="form-control geoSelect" id="officeAddrCityCorpCantOrUpazila" data-geo-group="officeAddr" data-geo-order="3">
                                        <option value="-1">উপজেলা নির্বাচন করুন</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6 geo-container" style="display:none">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label required-field">ইউনিয়ন/পৌরসভা</label>
                                <div class="col-md-8">
                                    <select class="form-control geoSelect" id="officeAddrPaurasavaOrUnion" data-geo-group="officeAddr" data-geo-order="4">
                                        <option value="-1">ইউনিয়ন নির্বাচন করুন</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label">সেবা</label>
                                <div class="col-md-8">
                                    <select class="form-control" id="applicationService">
                                        <option value="br">জন্ম নিবন্ধন</option>
                                        <option value="dr">মৃত্যু নিবন্ধন</option>
                                        <option value="br_corr">জন্ম সংশোধন</option>
                                        <option value="dr_corr">মৃত্যু সংশোধন</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label">স্ট্যাটাস</label>
                                <div class="col-md-8">
                                    <select class="form-control" id="applicationStatus">
                                        <option value="ALL" selected>সবগুলো (All)</option>
                                        <option value="APPLIED">আবেদনকৃত (Applied)</option>
                                        <option value="RECEIVED">গৃহীত (Received)</option>
                                        <option value="REGISTERED">রেজিস্টারড (Registered)</option>
                                        <option value="REJECTED">বাতিল (Rejected)</option>
                                        <option value="POSSIBLE_DUPLICATE">সম্ভাব্য ডুপ্লিকেট</option>
                                        <option value="REQUIRES_APPROVAL_WHEN_PARENT_UNKNOWN">প্যারেন্ট অজানা (Approval Required)</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label">CSRF Token</label>
                                <div class="col-md-8">
                                    <input type="text" class="form-control" id="csrfTokenInput" placeholder="X-CSRF-TOKEN">
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label">UNO Token</label>
                                <div class="col-md-8">
                                    <input type="text" class="form-control" id="unoTokenInput" placeholder="data=... টোকেন (ঐচ্ছিক)">
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group row">
                                <label class="col-md-4 col-form-label">সার্চ</label>
                                <div class="col-md-8">
                                    <input type="text" class="form-control" id="applicationSearchValue" placeholder="আবেদন আইডি/UBRN/নাম">
                                    <div style="margin-top:10px;">
                                        <button type="button" onclick="goViewDirect()" class="btn btn-warning">
                                            ভিউ করুন
                                        </button>
                                        <button type="button" onclick="goDocumentPrint()" class="btn btn-secondary ml-2">
                                            <i class="material-icons" style="font-size: 16px; vertical-align: text-bottom;">folder</i> ডকুমেন্ট প্রিন্ট
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <input type="hidden" id="officeId" name="officeId">
                    </div>

                    <div class="row mt-4">
                        <div class="col-md-12 text-center">
                            <button class="btn btn-info ripple" name="searchOfficeButton" id="searchOfficeButton" type="button" disabled>অনুসন্ধান</button>
                        </div>
                    </div>
                </form>

                <div class="row mt-4 mb-4" id="summaryContainer" style="display:none">
                    <div class="col-md-2 col-sm-4 mb-2">
                        <div class="card text-center border-primary summary-card" data-status="APPLIED">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1 small">আবেদনকৃত</h6>
                                <h4 class="mb-0 text-primary" id="count-APPLIED">0</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-4 mb-2">
                        <div class="card text-center border-success summary-card" data-status="RECEIVED">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1 small">গৃহীত</h6>
                                <h4 class="mb-0 text-success" id="count-RECEIVED">0</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-4 mb-2">
                        <div class="card text-center border-warning summary-card" data-status="REQUIRES_APPROVAL_WHEN_PARENT_UNKNOWN">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1 small">প্যারেন্ট অজানা</h6>
                                <h4 class="mb-0 text-warning" id="count-REQUIRES_APPROVAL_WHEN_PARENT_UNKNOWN">0</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-4 mb-2">
                        <div class="card text-center border-info summary-card" data-status="POSSIBLE_DUPLICATE">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1 small">ডুপ্লিকেট</h6>
                                <h4 class="mb-0 text-info" id="count-POSSIBLE_DUPLICATE">0</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-4 mb-2">
                        <div class="card text-center border-secondary summary-card" data-status="REGISTERED">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1 small">রেজিস্টারড</h6>
                                <h4 class="mb-0 text-secondary" id="count-REGISTERED">0</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-2 col-sm-4 mb-2">
                        <div class="card text-center border-danger summary-card" data-status="REJECTED">
                            <div class="card-body p-2">
                                <h6 class="card-title mb-1 small">বাতিল</h6>
                                <h4 class="mb-0 text-danger" id="count-REJECTED">0</h4>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row mt-2" id="resultContainer" style="display:none">
                    <div class="col-md-12">
                        <h5 class="mb-3">আবেদন তালিকা</h5>
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped" id="resultTable">
                                <thead class="thead-dark">
                                    <tr>
                                        <th>আবেদন আইডি</th>
                                        <th>আবেদনের তারিখ</th>
                                        <th>জন্ম/মৃত্যু তারিখ</th>
                                        <th>নাম (বাংলা)</th>
                                        <th>পিতার নাম (বাংলা)</th>
                                        <th>মাতার নাম (বাংলা)</th>
                                        <th>স্ট্যাটাস</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                        <div class="d-flex flex-wrap justify-content-between align-items-center mt-3" id="paginationBar" style="display:none;">
                            <div class="d-flex align-items-center mb-2">
                                <span class="mr-2">ভিউ</span>
                                <select class="form-control form-control-sm" id="pageSizeSelect" style="width: 110px;">
                                    <option value="25">25</option>
                                    <option value="50" selected>50</option>
                                    <option value="100">100</option>
                                </select>
                                <div class="form-check ml-3">
                                    <input class="form-check-input" type="checkbox" id="loadAllToggle">
                                    <label class="form-check-label" for="loadAllToggle">সব আবেদন লোড</label>
                                </div>
                            </div>
                            <div class="d-flex align-items-center mb-2">
                                <button type="button" class="btn btn-outline-secondary btn-sm mr-2" id="prevPageBtn">পূর্ববর্তী</button>
                                <div id="pageNumbers" class="d-flex flex-wrap"></div>
                                <button type="button" class="btn btn-outline-secondary btn-sm ml-2" id="nextPageBtn">পরবর্তী</button>
                            </div>
                            <div class="text-muted small mb-2" id="pageInfo"></div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
$(document).ready(function() {
    let currentOfficeId = '';
    let lastRows = [];
    const btnText = $('#searchOfficeButton').text();
    let lastCsrfToken = '';
    let listStart = 0;
    let listLength = 50;
    let listTotal = 0;
    let lastListStatus = 'ALL';
    let lastSearchValue = '';
    let listDraw = 1;
    let loadAllToken = 0;

    function showMessage(msg) {
        $('#warning-message-span').text(String(msg || ''));
        $('#warning-message-div').fadeIn();
    }


    function esc(s) {
        return String(s === null || s === undefined ? '' : s)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function syncOfficeIdToServer(officeId) {
        const oid = String(officeId || '').trim();
        if (!oid) return;
        const digits = oid.replace(/\D+/g, '');
        if (!digits) return;
        fetch('api/check_status.php?set_office_id=' + encodeURIComponent(digits) + '&_=' + Date.now(), { cache: 'no-store' }).catch(function() {});
    }

    function syncUpazilaIdToServer(upazilaId) {
        const uid = String(upazilaId || '').trim();
        if (!uid || uid === '-1') return;
        fetch('api/check_status.php?set_upazila_id=' + encodeURIComponent(uid) + '&_=' + Date.now(), { cache: 'no-store' }).catch(function() {});
    }

    function setSearchLoading(isLoading) {
        if (isLoading) {
            $('#searchOfficeButton').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> খোঁজা হচ্ছে...');
            return;
        }
        $('#searchOfficeButton').prop('disabled', currentOfficeId === '').text(btnText);
    }

    function getCurrentService() {
        const v = String($('#applicationService').val() || '').trim().toLowerCase();
        if (v === 'dr' || v === 'br' || v === 'br_corr' || v === 'dr_corr') return v;
        return 'br';
    }

    function isCorrectionService(svc) {
        return svc === 'br_corr' || svc === 'dr_corr';
    }

    function applyStatusOptions() {
        const svc = getCurrentService();
        const $sel = $('#applicationStatus');
        const current = String($sel.val() || 'ALL');

        let options = [];
        if (isCorrectionService(svc)) {
            options = [
                { v: 'ALL', t: 'সবগুলো (All)' },
                { v: 'APPLIED', t: 'আবেদনকৃত (Applied)' },
                { v: 'RECEIVED', t: 'গৃহীত (Received)' },
                { v: 'REQUIRES_APPROVAL_OF_REMOTE_OFFICE', t: 'রিমোট অফিস অনুমোদন' },
                { v: 'REQUIRES_APPROVAL_OF_HIGHER_AUTHORITY', t: 'হাইয়ার অথরিটি অনুমোদন' },
                { v: 'PENDING_APPROVAL_FOR_NATIONALITY', t: 'জাতীয়তা অনুমোদন অপেক্ষমান' },
                { v: 'PENDING_APPROVAL_FOR_DOB', t: 'DOB অনুমোদন অপেক্ষমান' },
                { v: 'CORRECTED', t: 'সংশোধিত (Corrected)' },
                { v: 'REJECTED', t: 'বাতিল (Rejected)' }
            ];
        } else {
            options = [
                { v: 'ALL', t: 'সবগুলো (All)' },
                { v: 'APPLIED', t: 'আবেদনকৃত (Applied)' },
                { v: 'RECEIVED', t: 'গৃহীত (Received)' },
                { v: 'REGISTERED', t: 'রেজিস্টারড (Registered)' },
                { v: 'REJECTED', t: 'বাতিল (Rejected)' },
                { v: 'POSSIBLE_DUPLICATE', t: 'সম্ভাব্য ডুপ্লিকেট' },
                { v: 'REQUIRES_APPROVAL_WHEN_PARENT_UNKNOWN', t: 'প্যারেন্ট অজানা (Approval Required)' }
            ];
        }

        let html = '';
        options.forEach(o => { html += '<option value="' + esc(o.v) + '">' + esc(o.t) + '</option>'; });
        $sel.html(html);

        if (options.some(o => o.v === current)) $sel.val(current);
        else $sel.val('ALL');
    }

    $('#applicationService').on('change', function() {
        applyStatusOptions();
        listStart = 0;
        listTotal = 0;
        $('#summaryContainer').hide();
        $('#resultContainer').hide();
        $('#paginationBar').hide();
        $('#resultTable tbody').empty();
    });

    applyStatusOptions();

    function csrfToken() {
        const t = String($('#csrfTokenInput').val() || '').trim();
        lastCsrfToken = t;
        return t;
    }

    function refreshFromSaved() {
        $.getJSON('uno-token.php', function(res) {
            if (!res || !res.ok) return;
            if (res.csrfToken && !$('#csrfTokenInput').val()) $('#csrfTokenInput').val(res.csrfToken);
            if (res.token && !$('#unoTokenInput').val()) $('#unoTokenInput').val(res.token);
        });
    }

    refreshFromSaved();

    $('#csrfTokenInput').on('change', function() {
        const v = String($('#csrfTokenInput').val() || '').trim();
        if (!v) return;
        $.ajax({
            url: 'uno-token.php',
            type: 'POST',
            dataType: 'json',
            timeout: 15000,
            data: { csrfToken: v }
        });
    });

    $('#unoTokenInput').on('change', function() {
        const v = String($('#unoTokenInput').val() || '').trim();
        if (!v) return;
        $.ajax({
            url: 'uno-token.php',
            type: 'POST',
            dataType: 'json',
            timeout: 15000,
            data: { token: v, geoGroup: 'officeAddr' }
        });
    });

    function buildActionIcons(item) {
        const svc = getCurrentService();
        const isCorr = isCorrectionService(svc);
        const id = item && (item.id || item.applicationId || item.appId) ? String(item.id || item.applicationId || item.appId) : '';
        const enc = item && (item.encryptedId || item.encryptedID || item.encrypted_id) ? String(item.encryptedId || item.encryptedID || item.encrypted_id) : '';
        const st = item && (item.status || item.statusos || item.statusOs || item.statusOS)
            ? String(item.status || item.statusos || item.statusOs || item.statusOS)
            : '';
        const encAttr = enc ? 'data-encrypted-id="' + esc(enc) + '"' : '';
        const stAttr = st ? 'data-status="' + esc(st) + '"' : '';
        const idAttr = id ? 'data-app-id="' + esc(id) + '"' : '';
        let html = '';
        if (!isCorr && svc === 'br') {
            // 1. ভিউ লিংক (View)
            const brnVal = item.personBrn || item.birthRegistrationNumber || item.ubrn || '';
            if (st === 'REGISTERED' && brnVal) {
                html += '<span class="badge badge-success" title="BRN" style="font-size:13px; margin-right:5px; padding: 4px 6px; vertical-align: middle;">' + esc(brnVal) + '</span>';
            } else if (id) {
                html += '<a href="register-by-app-id.php?app_id=' + encodeURIComponent(id) + '&officeId=' + encodeURIComponent(currentOfficeId) + '&status=' + encodeURIComponent(st) + '" target="_blank" title="ভিউ" data-toggle="tooltip"><i class="material-icons" style="color:#c8c818">remove_red_eye</i></a>';
            }
            
            // 2. এপ্লিকেশন প্রিন্ট (Application Print)
            if (enc) {
                html += '<a href="print-official.php?type=app&data=' + encodeURIComponent(enc) + '" target="_blank" title="আবেদনপত্র প্রিন্ট" data-toggle="tooltip" class="print"><i class="material-icons">print</i></a>';
            } else if (id) {
                html += '<a href="print-application.php?app_id=' + encodeURIComponent(id) + '&officeId=' + encodeURIComponent(currentOfficeId) + '" target="_blank" title="আবেদনপত্র প্রিন্ট" data-toggle="tooltip" class="print"><i class="material-icons">print</i></a>';
            }
            
            // 3. প্রিন্ট ডকুমেন্ট (Document Print)
            if (id) {
                html += '<a href="print-documents.php?app_id=' + encodeURIComponent(id) + '&officeId=' + encodeURIComponent(currentOfficeId) + '" target="_blank" title="ডকুমেন্ট প্রিন্ট" data-toggle="tooltip" style="color:#17a2b8"><i class="material-icons">description</i></a>';
            }
            
            // 4. টাকার রশিদ (Payment Receipt Print) - Only if enc is available
            if (enc) {
                html += '<a href="print-official.php?type=receipt&data=' + encodeURIComponent(enc) + '" target="_blank" title="টাকার রশিদ প্রিন্ট" data-toggle="tooltip" style="color:#cb9d64" class="app_print_receipt print"><i class="material-icons">print</i></a>';
            }
            
            // 5. সার্টিফিকেট প্রিন্ট (Certificate Print)
            if (st === 'REGISTERED') {
                if (enc) {
                    html += '<a href="javascript:" class="certificate_collector_info" title="সার্টিফিকেট প্রিন্ট" data-toggle="tooltip" data-encryptedid="' + esc(enc) + '" ' + idAttr + ' ' + stAttr + ' style="color:#4350d2"><i class="material-icons">print</i></a>';
                } else if (id) {
                    html += '<a href="#" class="action-cert-print" title="সার্টিফিকেট প্রিন্ট" data-toggle="tooltip" ' + idAttr + ' style="color:#4350d2"><i class="material-icons">verified</i></a>';
                }
            }
        } else if (!isCorr && svc === 'dr') {
            if (enc) {
                html += '<a href="print-official.php?type=app&data=' + encodeURIComponent(enc) + '" target="_blank" title="আবেদনপত্র প্রিন্ট" data-toggle="tooltip" class="print"><i class="material-icons">print</i></a>';
            }
        }

        const hasEnc = !!enc;
        const canResolveEnc = (!!id && svc === 'br');

        if (hasEnc || canResolveEnc) {
            if (isCorr && hasEnc) {
                html += '<a href="#" class="action-view" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="ভিউ"><i class="material-icons" style="color:#c8c818">remove_red_eye</i></a>';
            }
            html += '<a href="#" class="action-details" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="ডিটেইলস"><i class="material-icons">info</i></a>';
            if (!isCorr && st === 'APPLIED') {
                html += '<a href="#" class="action-receive" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="Receive"><i class="material-icons" style="color:#28a745">pan_tool</i></a>';
            }
            if (!isCorr && st === 'RECEIVED') {
                html += '<a href="#" class="action-register" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="Register"><i class="material-icons" style="color:#20c997">how_to_reg</i></a>';
            }
            if (!isCorr && svc === 'br' && st === 'POSSIBLE_DUPLICATE') {
                if (hasEnc) {
                    html += '<a href="duplicates.php?data=' + encodeURIComponent(enc) + '" target="_blank" title="Possible Duplicate"><i class="material-icons" style="color:#6f42c1">content_copy</i></a>';
                } else {
                    html += '<a href="#" class="action-dup-check" ' + idAttr + ' title="Possible Duplicate"><i class="material-icons" style="color:#6f42c1">content_copy</i></a>';
                }
            }
            if (!isCorr && svc === 'br' && (st === 'POSSIBLE_DUPLICATE' || st === 'REQUIRES_APPROVAL_WHEN_PARENT_UNKNOWN')) {
                html += '<a href="#" class="action-approve" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="Approve"><i class="material-icons" style="color:#ffc107">check_circle</i></a>';
            }
            if (!isCorr && (st === 'APPLIED' || st === 'RECEIVED' || st === 'POSSIBLE_DUPLICATE' || st === 'REQUIRES_APPROVAL_WHEN_PARENT_UNKNOWN')) {
                html += '<a href="#" class="action-reject" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="Reject"><i class="material-icons" style="color:#dc3545">cancel</i></a>';
                html += '<a href="#" class="action-delete ml-1" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="Delete"><i class="material-icons" style="color:#dc3545">delete</i></a>';
            }
            if (isCorr && hasEnc && st === 'RECEIVED') {
                html += '<a href="#" class="action-correct" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="Correct"><i class="material-icons" style="color:#20c997">build</i></a>';
            }
            if (isCorr && hasEnc && (st === 'REQUIRES_APPROVAL_OF_HIGHER_AUTHORITY' || st === 'PENDING_APPROVAL_FOR_NATIONALITY' || st === 'PENDING_APPROVAL_FOR_DOB')) {
                html += '<a href="#" class="action-approve" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="Approve"><i class="material-icons" style="color:#ffc107">check_circle</i></a>';
            }
            if (isCorr && hasEnc && (st === 'APPLIED' || st === 'RECEIVED' || st === 'REQUIRES_APPROVAL_OF_REMOTE_OFFICE' || st === 'REQUIRES_APPROVAL_OF_HIGHER_AUTHORITY' || st === 'PENDING_APPROVAL_FOR_NATIONALITY' || st === 'PENDING_APPROVAL_FOR_DOB')) {
                html += '<a href="#" class="action-reject" ' + encAttr + ' ' + idAttr + ' ' + stAttr + ' title="Reject"><i class="material-icons" style="color:#dc3545">cancel</i></a>';
            }
        }
        return html;
    }

    function updatePaginationUi() {
        const bar = $('#paginationBar');
        if (listTotal <= 0) {
            bar.hide();
            return;
        }
        bar.show();

        if ($('#loadAllToggle').prop('checked')) {
            $('#pageNumbers').html('');
            $('#prevPageBtn').prop('disabled', true);
            $('#nextPageBtn').prop('disabled', true);
            $('#pageInfo').text('মোট ' + listTotal + ' টি');
            return;
        }

        const totalPages = Math.max(1, Math.ceil(listTotal / listLength));
        const currentPage = Math.min(totalPages, Math.floor(listStart / listLength) + 1);
        const from = Math.min(listTotal, listStart + 1);
        const to = Math.min(listTotal, listStart + lastRows.length);

        $('#pageInfo').text('পৃষ্ঠা ' + currentPage + ' / ' + totalPages + ' — ' + from + ' থেকে ' + to + ' (মোট ' + listTotal + ')');

        $('#prevPageBtn').prop('disabled', currentPage <= 1);
        $('#nextPageBtn').prop('disabled', currentPage >= totalPages);

        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);
        let nums = '';
        for (let p = startPage; p <= endPage; p++) {
            const active = (p === currentPage);
            nums += '<button type="button" class="btn btn-sm ' + (active ? 'btn-primary' : 'btn-outline-primary') + ' mr-1 mb-1 pageNumBtn" data-page="' + p + '">' + p + '</button>';
        }
        $('#pageNumbers').html(nums);
    }

    function getAllStatusesForCurrentService() {
        const svc = getCurrentService();
        if (isCorrectionService(svc)) {
            return [
                'APPLIED',
                'RECEIVED',
                'REQUIRES_APPROVAL_OF_REMOTE_OFFICE',
                'REQUIRES_APPROVAL_OF_HIGHER_AUTHORITY',
                'PENDING_APPROVAL_FOR_NATIONALITY',
                'PENDING_APPROVAL_FOR_DOB',
                'CORRECTED',
                'REJECTED'
            ];
        }
        if (svc === 'dr') return ['APPLIED', 'RECEIVED', 'REGISTERED', 'REJECTED'];
        return ['APPLIED', 'RECEIVED', 'REGISTERED', 'REJECTED', 'POSSIBLE_DUPLICATE', 'REQUIRES_APPROVAL_WHEN_PARENT_UNKNOWN'];
    }

    function parseDateAppliedValue(v) {
        const s = String(v || '').trim();
        if (!s) return 0;
        let m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);
        if (m) return (parseInt(m[1], 10) * 10000) + (parseInt(m[2], 10) * 100) + parseInt(m[3], 10);
        m = s.match(/^(\d{1,2})-(\d{1,2})-(\d{4})/);
        if (m) return (parseInt(m[3], 10) * 10000) + (parseInt(m[2], 10) * 100) + parseInt(m[1], 10);
        const t = Date.parse(s);
        if (isNaN(t)) return 0;
        const d = new Date(t);
        return (d.getFullYear() * 10000) + ((d.getMonth() + 1) * 100) + d.getDate();
    }

    function reloadCurrentList() {
        if ($('#loadAllToggle').prop('checked')) loadAllApplications();
        else loadList();
    }

    function loadList() {
        if (!currentOfficeId) return;

        $('#resultContainer').show();
        if (isCorrectionService(getCurrentService())) {
            $('#summaryContainer').hide();
        } else {
            $('#summaryContainer').show();
        }
        $('#paginationBar').hide();
        $('#resultTable tbody').html('<tr><td colspan="8" class="text-center"><span class="spinner-border spinner-border-sm"></span> লোড হচ্ছে...</td></tr>');

        $.ajax({
            url: 'proxy_list.php',
            type: 'POST',
            dataType: 'json',
            timeout: 30000,
            data: {
                action: 'list',
                officeId: currentOfficeId,
                status: lastListStatus,
                draw: listDraw++,
                start: listStart,
                length: listLength,
                searchValue: lastSearchValue,
                service: getCurrentService(),
                csrfToken: csrfToken()
            }
        }).done(function(res) {
            if (res && (res._error || res.error)) {
                showMessage(res._error || res.error);
            }
            const data = res && res.data ? res.data : [];
            lastRows = Array.isArray(data) ? data : [];
            renderTableRows(lastRows);
            const total = res && (res.recordsFiltered !== undefined ? res.recordsFiltered : res.recordsTotal);
            listTotal = (total !== undefined && total !== null && total !== '') ? parseInt(total, 10) : 0;
            if (isNaN(listTotal)) listTotal = 0;
            updatePaginationUi();
            $('#resultContainer').fadeIn();
        }).fail(function(jqXHR) {
            showMessage('আবেদন তালিকা আনতে সমস্যা হয়েছে। (' + (jqXHR.status || '') + ')');
            $('#resultTable tbody').html('<tr><td colspan="8" class="text-center text-danger">ডাটা পাওয়া যায়নি</td></tr>');
            listTotal = 0;
            updatePaginationUi();
        });
    }

    function loadAllApplications() {
        if (!currentOfficeId) return;

        const token = ++loadAllToken;
        const svc = getCurrentService();
        const allStatuses = (String($('#applicationStatus').val() || 'ALL') === 'ALL') ? getAllStatusesForCurrentService() : [String($('#applicationStatus').val() || 'APPLIED')];
        const perPage = Math.max(10, parseInt(String($('#pageSizeSelect').val() || '100'), 10) || 100);

        $('#resultContainer').show();
        $('#summaryContainer').hide();
        $('#paginationBar').show();
        $('#resultTable tbody').html('<tr><td colspan="8" class="text-center"><span class="spinner-border spinner-border-sm"></span> লোড হচ্ছে...</td></tr>');
        $('#pageNumbers').html('');
        $('#prevPageBtn').prop('disabled', true);
        $('#nextPageBtn').prop('disabled', true);

        const out = [];
        const seen = {};
        let statusIdx = 0;
        let start = 0;
        let currentStatus = allStatuses[0] || 'APPLIED';

        function addRows(rows) {
            (rows || []).forEach(r => {
                if (!r) return;
                const enc = r.encryptedId || r.encryptedID || r.encrypted_id || '';
                const id = r.id || r.applicationId || r.appId || '';
                const key = String(enc || id || '');
                if (!key) return;
                if (seen[key]) return;
                seen[key] = 1;
                out.push(r);
            });
        }

        function step() {
            if (token !== loadAllToken) return;
            currentStatus = allStatuses[statusIdx] || '';
            if (!currentStatus) {
                out.sort(function(a, b) {
                    const da = parseDateAppliedValue(a && a.dateApplied);
                    const db = parseDateAppliedValue(b && b.dateApplied);
                    if (da === db) {
                        const ia = String((a && (a.id || a.applicationId || a.appId)) || '');
                        const ib = String((b && (b.id || b.applicationId || b.appId)) || '');
                        return ib.localeCompare(ia);
                    }
                    return db - da;
                });
                lastRows = out;
                listStart = 0;
                listTotal = out.length;
                renderTableRows(lastRows);
                updatePaginationUi();
                return;
            }

            $('#pageInfo').text('লোড হচ্ছে: ' + currentStatus + ' — ' + out.length + ' টি');

            $.ajax({
                url: 'proxy_list.php',
                type: 'POST',
                dataType: 'json',
                timeout: 30000,
                data: {
                    action: 'list',
                    officeId: currentOfficeId,
                    status: currentStatus,
                    draw: listDraw++,
                    start: start,
                    length: perPage,
                    searchValue: lastSearchValue,
                    service: svc,
                    csrfToken: csrfToken()
                }
            }).done(function(res) {
                if (token !== loadAllToken) return;
                if (res && (res._error || res.error)) {
                    showMessage(res._error || res.error);
                }
                const rows = res && res.data ? res.data : [];
                addRows(Array.isArray(rows) ? rows : []);
                const total = res && (res.recordsFiltered !== undefined ? res.recordsFiltered : res.recordsTotal);
                const t = (total !== undefined && total !== null && total !== '') ? parseInt(total, 10) : 0;

                start += perPage;
                if (Array.isArray(rows) && rows.length > 0 && (t <= 0 || start < t)) {
                    setTimeout(step, 1200);
                    return;
                }

                statusIdx += 1;
                start = 0;
                setTimeout(step, 1200);
            }).fail(function(jqXHR) {
                if (token !== loadAllToken) return;
                showMessage('আবেদন তালিকা আনতে সমস্যা হয়েছে। (' + (jqXHR.status || '') + ')');
                statusIdx += 1;
                start = 0;
                setTimeout(step, 2000);
            });
        }

        step();
    }

    function renderTableRows(data) {
        let rows = '';
        const list = Array.isArray(data) ? data : [];
        if (list.length === 0) {
            $('#resultTable tbody').html('<tr><td colspan="8" class="text-center text-danger">কোনো তথ্য পাওয়া যায়নি</td></tr>');
            return;
        }
        list.forEach(item => {
            const st = item && (item.status || item.statusos || item.statusOs || item.statusOS)
                ? (item.status || item.statusos || item.statusOs || item.statusOS)
                : '';
            rows += '<tr>' +
                '<td>' + esc(item.id || item.applicationId || item.appId || '-') + '</td>' +
                '<td>' + esc(item.dateApplied || '-') + '</td>' +
                '<td>' + esc(item.personBirthDate || item.personDeathDate || '-') + '</td>' +
                '<td>' + esc(item.personNameBn || '-') + '</td>' +
                '<td>' + esc(item.fatherNameBn || '-') + '</td>' +
                '<td>' + esc(item.motherNameBn || '-') + '</td>' +
                '<td>' + esc(st || '-') + '</td>' +
                '<td>' + buildActionIcons(item) + '</td>' +
            '</tr>';
        });
        $('#resultTable tbody').html(rows);
    }

    function resetOfficeState() {
        currentOfficeId = '';
        $('#officeId').val('');
        $('#searchOfficeButton').prop('disabled', true);
        $('#summaryContainer').hide();
        $('#resultContainer').hide();
        $('#paginationBar').hide();
        $('#resultTable tbody').empty();
        $('#officeAlert').remove();
        listStart = 0;
        listTotal = 0;
    }

    $('.geoSelect').on('change', function() {
        const $this = $(this);
        const geoId = String($this.val() || '');
        const geoGroup = String($this.data('geo-group') || '');
        const geoOrder = parseInt($this.data('geo-order'), 10);
        const mapping = { 2: 'Dist', 3: 'CityCorpCantOrUpazila', 4: 'PaurasavaOrUnion' };
        const nextOrder = geoOrder + 1;
        const targetId = '#' + geoGroup + (mapping[nextOrder] || '');

        if (geoOrder < 4) {
            $('#officeAddrPaurasavaOrUnion').html('<option value="-1">ইউনিয়ন নির্বাচন করুন</option>').closest('.geo-container').hide();
        }
        if (geoOrder < 3) {
            $('#officeAddrCityCorpCantOrUpazila').html('<option value="-1">উপজেলা নির্বাচন করুন</option>').closest('.geo-container').hide();
        }
        if (geoOrder < 2) {
            $('#officeAddrDist').html('<option value="-1">জেলা নির্বাচন করুন</option>').closest('.geo-container').hide();
        }

        resetOfficeState();

        if (!geoId || geoId === '-1') return;

        if (geoOrder === 3) {
            syncUpazilaIdToServer(geoId);
        }

        if (mapping[nextOrder]) {
            const $target = $(targetId);
            $target.closest('.geo-container').fadeIn();
            $target.html('<option>লোডিং...</option>').prop('disabled', true);

            let geoType = 1;
            if (geoOrder === 3) geoType = 3;

            $.get('proxy_geo.php', {
                parentId: geoId,
                geoOrder: geoOrder,
                geoGroup: geoGroup,
                geoType: geoType
            }, function(res) {
                let dataList = [];
                if (Array.isArray(res)) dataList = res;
                else if (res && res.geoObject) dataList = res.geoObject;
                else if (res && res.data) dataList = res.data;

                let options = '<option value="-1">নির্বাচন করুন</option>';
                if (Array.isArray(dataList) && dataList.length > 0) {
                    dataList.forEach(item => {
                        const id = item && (item.id || item.code || item.value) ? (item.id || item.code || item.value) : '';
                        const name = item && (item.nameBn || item.name || item.text || item.title) ? (item.nameBn || item.name || item.text || item.title) : '';
                        if (id && name) options += '<option value="' + esc(id) + '">' + esc(name) + '</option>';
                    });
                    $target.html(options).prop('disabled', false);
                } else {
                    $target.html('<option value="-1">তথ্য পাওয়া যায়নি</option>').prop('disabled', true);
                }
            }, 'json').fail(function() {
                $target.html('<option value="-1">সার্ভার ত্রুটি</option>').prop('disabled', true);
            });
            return;
        }

        if (geoOrder === 4) {
            $('#officeAlert').remove();
            $('<div class="alert alert-info mt-2 small p-2" id="officeAlert"><span class="spinner-border spinner-border-sm"></span> অফিস খোঁজা হচ্ছে...</div>').insertAfter('#officeAddrPaurasavaOrUnion');
            $.get('proxy_office.php', {
                geoId: geoId,
                geoGroup: 'officeAddr',
                geoOrder: 4,
                geoType: 5
            }, function(res) {
                $('#officeAlert').remove();
                const officeVal = res && res.geoObject ? String(res.geoObject.officeId || res.geoObject.id || '') : '';
                const officeName = res && res.geoObject ? String(res.geoObject.officeNameBn || res.geoObject.officeNameEn || 'অফিস') : 'অফিস';

                if (officeVal) {
                    currentOfficeId = officeVal;
                    syncOfficeIdToServer(currentOfficeId);
                    $('#officeId').val(officeVal);
                    $('<div class="alert alert-success mt-2 small p-2" id="officeAlert">অফিস: ' + esc(officeName) + '</div>').insertAfter('#officeAddrPaurasavaOrUnion');
                    $('#searchOfficeButton').prop('disabled', false);
                    return;
                }

                $('<div class="alert alert-danger mt-2 small p-2" id="officeAlert">অফিস তথ্য পাওয়া যায়নি।</div>').insertAfter('#officeAddrPaurasavaOrUnion');
            }, 'json').fail(function() {
                $('#officeAlert').remove();
                $('<div class="alert alert-warning mt-2 small p-2" id="officeAlert">সার্ভার সমস্যা। আবার চেষ্টা করুন।</div>').insertAfter('#officeAddrPaurasavaOrUnion');
            });
        }
    });

    $('#searchOfficeButton').on('click', function() {
        const unoToken = String($('#unoTokenInput').val() || '').trim();
        if (unoToken) currentOfficeId = unoToken;

        if (!currentOfficeId) {
            showMessage('অফিস নির্বাচন সম্পন্ন হয়নি।');
            return;
        }
        syncOfficeIdToServer(currentOfficeId);

        $('#warning-message-div').hide();
        setSearchLoading(true);
        listStart = 0;
        listLength = parseInt(String($('#pageSizeSelect').val() || '50'), 10);
        if (isNaN(listLength) || listLength <= 0) listLength = 50;
        lastListStatus = String($('#applicationStatus').val() || 'ALL');
        lastSearchValue = String($('#applicationSearchValue').val() || '').trim();

        if (isCorrectionService(getCurrentService())) {
            $('#summaryContainer').hide();
            setSearchLoading(false);
        } else {
            $('#summaryContainer').show();
            const statuses = ['APPLIED', 'RECEIVED', 'REQUIRES_APPROVAL_WHEN_PARENT_UNKNOWN', 'POSSIBLE_DUPLICATE', 'REGISTERED', 'REJECTED'];
            statuses.forEach(st => $('#count-' + st).html('<span class="spinner-border spinner-border-sm"></span>'));

            $.ajax({
                url: 'proxy_list.php',
                type: 'POST',
                dataType: 'json',
                timeout: 30000,
                data: { action: 'counts', force: 1, officeId: currentOfficeId, statuses: statuses.join(','), service: getCurrentService(), csrfToken: csrfToken() }
            }).done(function(res) {
                if (res && (res._error || res.error)) {
                    showMessage(res._error || res.error);
                }
                const map = res && res.counts ? res.counts : {};
                statuses.forEach(st => {
                    const v = map && map[st] !== undefined ? parseInt(map[st], 10) : 0;
                    $('#count-' + st).text(isNaN(v) ? 0 : v);
                });
            }).fail(function(jqXHR) {
                showMessage('কাউন্ট আনতে সমস্যা হয়েছে। (' + (jqXHR.status || '') + ')');
                statuses.forEach(st => $('#count-' + st).text('!'));
            }).always(function() {
                setSearchLoading(false);
            });
        }

        reloadCurrentList();
    });

    $('#applicationStatus').on('change', function() {
        if (!currentOfficeId) return;
        lastListStatus = String($('#applicationStatus').val() || 'ALL');
        listStart = 0;
        reloadCurrentList();
    });

    $(document).on('click', '.summary-card', function() {
        const st = $(this).data('status');
        if (st) {
            $('#applicationStatus').val(st).trigger('change');
        }
    });

    $('#applicationSearchValue').on('keypress', function(e) {
        const k = e && (e.which || e.keyCode) ? (e.which || e.keyCode) : 0;
        if (k === 13) {
            e.preventDefault();
            if (!$('#searchOfficeButton').prop('disabled')) {
                $('#searchOfficeButton').trigger('click');
            }
        }
    });

    $('#pageSizeSelect').on('change', function() {
        listLength = parseInt(String($('#pageSizeSelect').val() || '50'), 10);
        if (isNaN(listLength) || listLength <= 0) listLength = 50;
        listStart = 0;
        if (!currentOfficeId) return;
        reloadCurrentList();
    });

    $('#loadAllToggle').on('change', function() {
        if (!currentOfficeId) return;
        listStart = 0;
        reloadCurrentList();
    });

    $('#prevPageBtn').on('click', function() {
        if ($('#loadAllToggle').prop('checked')) return;
        if (listStart <= 0) return;
        listStart = Math.max(0, listStart - listLength);
        reloadCurrentList();
    });

    $('#nextPageBtn').on('click', function() {
        if ($('#loadAllToggle').prop('checked')) return;
        const totalPages = Math.max(1, Math.ceil(listTotal / listLength));
        const currentPage = Math.floor(listStart / listLength) + 1;
        if (currentPage >= totalPages) return;
        listStart = listStart + listLength;
        reloadCurrentList();
    });

    $(document).on('click', '.pageNumBtn', function() {
        if ($('#loadAllToggle').prop('checked')) return;
        const p = parseInt(String($(this).attr('data-page') || ''), 10);
        if (isNaN(p) || p <= 0) return;
        listStart = (p - 1) * listLength;
        reloadCurrentList();
    });

    function resolveEncryptedId(appId, onDone) {
        $.ajax({
            url: 'proxy_list.php',
            type: 'POST',
            dataType: 'json',
            timeout: 30000,
            data: { action: 'resolve_encrypted', appId: String(appId || '').trim(), officeId: currentOfficeId, service: getCurrentService(), csrfToken: csrfToken() }
        }).done(function(resp) {
            const enc = resp && resp.encryptedId ? String(resp.encryptedId) : '';
            if (!enc) {
                showMessage(resp && resp.error ? resp.error : 'Encrypted ID পাওয়া যায়নি।');
                return;
            }
            onDone(enc);
        }).fail(function(jqXHR) {
            showMessage('Encrypted ID আনতে সমস্যা হয়েছে। (' + (jqXHR.status || '') + ')');
        });
    }

    function ensureEncryptedId($el, onDone) {
        const existing = String($el.attr('data-encrypted-id') || '').trim();
        if (existing) {
            onDone(existing);
            return;
        }
        const appId = String($el.attr('data-app-id') || '').trim();
        if (!appId) {
            showMessage('আবেদন আইডি পাওয়া যায়নি।');
            return;
        }
        resolveEncryptedId(appId, function(enc) {
            const $td = $el.closest('td');
            if ($td.length) {
                $td.find('[data-app-id="' + appId + '"]').attr('data-encrypted-id', enc);
            } else {
                $el.attr('data-encrypted-id', enc);
            }
            onDone(enc);
        });
    }

    $(document).on('click', '.action-details', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        $('#applicationDetailsPre').text('Loading...');
        $('#applicationDetailsModal').modal('show');
        const $self = $(this);
        ensureEncryptedId($self, function(enc) {
            $.ajax({
                url: 'proxy_list.php',
                type: 'POST',
                dataType: 'json',
                timeout: 30000,
                data: { action: 'details', encryptedId: enc, service: getCurrentService(), csrfToken: csrfToken() }
            }).done(function(resp) {
                $('#applicationDetailsPre').text(JSON.stringify(resp || {}, null, 2));
            }).fail(function(jqXHR) {
                $('#applicationDetailsPre').text('ডাটা আনতে সমস্যা হয়েছে। (' + (jqXHR.status || '') + ')');
            });
        });
    });

    $(document).on('click', '.action-view', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        $(this).closest('td').find('.action-details').trigger('click');
    });

    $(document).on('click', '.action-possible-dups', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const enc = $(this).attr('data-encrypted-id') || '';
        $('#possibleDuplicatesPre').text('Loading...');
        $('#possibleDuplicatesModal').modal('show');
        if (!enc) {
            $('#possibleDuplicatesPre').text('encryptedId পাওয়া যায়নি।');
            return;
        }
        $.ajax({
            url: 'proxy_list.php',
            type: 'POST',
            dataType: 'json',
            timeout: 30000,
            data: { action: 'possible_duplicates', encryptedId: enc, service: getCurrentService(), csrfToken: csrfToken() }
        }).done(function(resp) {
            $('#possibleDuplicatesPre').text(JSON.stringify(resp || {}, null, 2));
        }).fail(function(jqXHR) {
            $('#possibleDuplicatesPre').text('ডাটা আনতে সমস্যা হয়েছে। (' + (jqXHR.status || '') + ')');
        });
    });

    $(document).on('click', '.action-receive', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const $self = $(this);
        if (!confirm('আপনি কি এই আবেদনটি Receive করতে চান?')) return;
        const $icon = $self.find('i');
        const origIcon = $icon.text();
        $icon.text('hourglass_empty');
        $self.css('pointer-events','none');
        ensureEncryptedId($self, function(enc) {
            $.ajax({
                url: 'proxy_list.php',
                type: 'POST',
                dataType: 'json',
                timeout: 30000,
                data: { action: 'receive', encryptedId: enc, service: getCurrentService(), csrfToken: csrfToken() }
            }).done(function(resp) {
                const msg = resp && resp.message ? resp.message : (resp && resp.error ? resp.error : 'Receive সফল হয়েছে।');
                showMessage(msg);
            }).fail(function(jqXHR) {
                showMessage('⚠ Receive ব্যর্থ হয়েছে। (HTTP ' + (jqXHR.status || 'error') + ')');
            }).always(function() {
                $icon.text(origIcon);
                $self.css('pointer-events','');
                setTimeout(function(){ reloadCurrentList(); }, 800);
            });
        });
    });

    $(document).on('click', '.action-approve', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const $self = $(this);
        const st = $self.attr('data-status') || '';
        if (!confirm('আপনি কি এই আবেদনটি Approve করতে চান?')) return;
        const $icon = $self.find('i');
        const origIcon = $icon.text();
        $icon.text('hourglass_empty');
        $self.css('pointer-events','none');
        ensureEncryptedId($self, function(enc) {
            $.ajax({
                url: 'proxy_list.php',
                type: 'POST',
                dataType: 'json',
                timeout: 30000,
                data: { action: 'approve', encryptedId: enc, status: st, service: getCurrentService(), csrfToken: csrfToken() }
            }).done(function(resp) {
                const msg = resp && resp.message ? resp.message : (resp && resp.error ? resp.error : 'Approve সফল হয়েছে।');
                showMessage(msg);
            }).fail(function(jqXHR) {
                showMessage('⚠ Approve ব্যর্থ হয়েছে। (HTTP ' + (jqXHR.status || 'error') + ')');
            }).always(function() {
                $icon.text(origIcon);
                $self.css('pointer-events','');
                setTimeout(function(){ reloadCurrentList(); }, 800);
            });
        });
    });

    $(document).on('click', '.action-delete', function(e) {
        e.preventDefault();
        const $t = $(this);
        const enc = $t.data('encrypted-id');
        const appId = $t.data('app-id');
        if (!enc) { showMessage('Encrypted ID missing'); return; }

        if (!confirm('আপনি কি এই আবেদনটি সম্পূর্ণ মুছে ফেলতে (Delete) চান?')) return;

        const ogHtml = $t.html();
        $t.html('<span class="spinner-border spinner-border-sm" style="color:#dc3545"></span>');
        $.ajax({
            url: 'proxy_list.php',
            type: 'POST',
            dataType: 'json',
            timeout: 20000,
            data: { action: 'delete', encryptedId: enc, service: getCurrentService(), csrfToken: csrfToken() }
        }).done(function(resp) {
            $t.html(ogHtml);
            if (resp && resp.error) {
                showMessage(resp.error);
            } else {
                showMessage('আবেদনটি সফলভাবে Delete হয়েছে।');
                reloadCurrentList();
            }
        }).fail(function(jqXHR) {
            $t.html(ogHtml);
            showMessage('⚠ Delete ব্যর্থ হয়েছে। (HTTP ' + (jqXHR.status || 'error') + ')');
        });
    });

    $(document).on('click', '.action-correct', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const $self = $(this);
        if (!confirm('আপনি কি এই আবেদনটি Correct করতে চান?')) return;
        const $icon = $self.find('i');
        const origIcon = $icon.text();
        $icon.text('hourglass_empty');
        $self.css('pointer-events','none');
        ensureEncryptedId($self, function(enc) {
            $.ajax({
                url: 'proxy_list.php',
                type: 'POST',
                dataType: 'json',
                timeout: 30000,
                data: { action: 'correct', encryptedId: enc, service: getCurrentService(), csrfToken: csrfToken() }
            }).done(function(resp) {
                const msg = resp && resp.message ? resp.message : (resp && resp.error ? resp.error : 'Correct সফল হয়েছে।');
                showMessage(msg);
            }).fail(function(jqXHR) {
                showMessage('⚠ Correct ব্যর্থ হয়েছে। (HTTP ' + (jqXHR.status || 'error') + ')');
            }).always(function() {
                $icon.text(origIcon);
                $self.css('pointer-events','');
                setTimeout(function(){ reloadCurrentList(); }, 800);
            });
        });
    });

    $(document).on('click', '.action-reject', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const $self = $(this);
        const reason = prompt('বাতিলের কারণ লিখুন (Reject করতে কারণ আবশ্যক):');
        if (reason === null) return;
        const reasonTrim = String(reason || '').trim();
        if (!reasonTrim) {
            showMessage('⚠ বাতিলের কারণ খালি রাখা যাবে না।');
            return;
        }
        if (!confirm('আপনি কি এই আবেদনটি বাতিল (Reject) করতে চান?')) return;
        const $icon = $self.find('i');
        const origIcon = $icon.text();
        $icon.text('hourglass_empty');
        $self.css('pointer-events','none');
        ensureEncryptedId($self, function(enc) {
            $.ajax({
                url: 'proxy_list.php',
                type: 'POST',
                dataType: 'json',
                timeout: 30000,
                data: { action: 'reject', encryptedId: enc, causeOfRejection: reasonTrim, causeOfRejections: reasonTrim, service: getCurrentService(), csrfToken: csrfToken() }
            }).done(function(resp) {
                const msg = resp && resp.message ? resp.message : (resp && resp.error ? resp.error : 'Reject সফল হয়েছে।');
                showMessage(msg);
            }).fail(function(jqXHR) {
                showMessage('⚠ Reject ব্যর্থ হয়েছে। (HTTP ' + (jqXHR.status || 'error') + ')');
            }).always(function() {
                $icon.text(origIcon);
                $self.css('pointer-events','');
                setTimeout(function(){ reloadCurrentList(); }, 800);
            });
        });
    });

    $(document).on('click', '.action-cert-print', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const appId = $(this).attr('data-app-id') || '';
        if (!appId) return;
        const targetName = 'cert_' + String(appId);
        const certTab = window.open('about:blank', targetName);
        if (!certTab) {
            showMessage('পপ-আপ ব্লক হয়েছে।');
            return;
        }
        $.ajax({
            url: 'proxy_list.php',
            type: 'POST',
            dataType: 'json',
            timeout: 30000,
            data: { action: 'resolve_ubrn', appId: appId, service: getCurrentService(), csrfToken: csrfToken() }
        }).done(function(resp) {
            if (resp && resp.ubrn && resp.dob) {
                const url = 'print-certificate.php?action=print&ubrn=' + encodeURIComponent(resp.ubrn) + '&dob=' + encodeURIComponent(resp.dob);
                try { certTab.location = url; } catch (e) { window.open(url, '_blank'); }
                return;
            }
            showMessage((resp && resp.error) ? resp.error : 'UBRN/DOB resolve করা যায়নি।');
            try { certTab.close(); } catch (e) {}
        }).fail(function(jqXHR) {
            showMessage('সার্টিফিকেট ডাটা আনতে সমস্যা হয়েছে। (' + (jqXHR.status || '') + ')');
            try { certTab.close(); } catch (e) {}
        });
    });

    $(document).on('click', '.certificate_collector_info', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const $self = $(this);
        const encryptedId = String($self.attr('data-encryptedid') || $self.attr('data-encryptedId') || $self.attr('data-encrypted-id') || '').trim();
        const appId = String($self.attr('data-app-id') || '').trim();
        const targetName = 'cert_' + (appId || encryptedId || String(Date.now())).substring(0, 12);

        const $icon = $self.find('i');
        const origIcon = $icon.text();
        $icon.text('hourglass_empty');
        $self.css('pointer-events', 'none');
        const resetBtn = function() { $icon.text(origIcon); $self.css('pointer-events', ''); };

        const certTab = window.open('about:blank', targetName);
        if (!certTab) {
            showMessage('⚠ পপ-আপ ব্লক হয়েছে। ব্রাউজারে পপ-আপ অনুমতি দিন।');
            resetBtn();
            return;
        }

        const openWithUbrn = function(ubrn, dob) {
            const url = 'print-certificate.php?action=print&mode=main&ubrn=' + encodeURIComponent(ubrn) + '&dob=' + encodeURIComponent(dob || '');
            try { certTab.location = url; } catch (ex) { window.open(url, '_blank'); }
            resetBtn();
        };

        const openPdfFallback = function(pdfUrl) {
            if (pdfUrl) {
                try { certTab.location = pdfUrl; } catch (ex) { window.open(pdfUrl, '_blank'); }
            } else {
                try { certTab.close(); } catch(ex){}
            }
            resetBtn();
        };

        function tryResolveViaEncId(enc) {
            $.ajax({
                url: 'proxy_list.php', type: 'POST', dataType: 'json', timeout: 30000,
                data: { action: 'resolve_cert_ubrn', encryptedId: enc, service: getCurrentService(), csrfToken: csrfToken() }
            }).done(function(resp2) {
                if (resp2 && resp2.ubrn && resp2.dob) {
                    openWithUbrn(resp2.ubrn, resp2.dob);
                } else if (resp2 && resp2.pdf_url) {
                    showMessage('⚠ UBRN সরাসরি পাওয়া যায়নি, PDF ওপেন করা হচ্ছে...');
                    openPdfFallback(resp2.pdf_url);
                } else {
                    showMessage((resp2 && resp2.error) ? '⚠ ' + resp2.error : '⚠ সার্টিফিকেট তথ্য পাওয়া যায়নি।');
                    openPdfFallback(null);
                }
            }).fail(function(jqXHR) {
                showMessage('⚠ সার্টিফিকেট ডাটা আনতে সমস্যা হয়েছে। (HTTP ' + (jqXHR.status || 'error') + ')');
                openPdfFallback(null);
            });
        }

        if (appId) {
            $.ajax({
                url: 'proxy_list.php', type: 'POST', dataType: 'json', timeout: 30000,
                data: { action: 'resolve_ubrn', appId: appId, service: getCurrentService(), csrfToken: csrfToken() }
            }).done(function(resp) {
                if (resp && resp.ubrn && resp.dob) {
                    openWithUbrn(resp.ubrn, resp.dob);
                } else if (encryptedId) {
                    tryResolveViaEncId(encryptedId);
                } else {
                    showMessage('⚠ সার্টিফিকেট ডাটা আনতে সমস্যা হয়েছে।');
                    openPdfFallback(null);
                }
            }).fail(function(){
                 if (encryptedId) tryResolveViaEncId(encryptedId);
                 else openPdfFallback(null);
            });
            return;
        }

        if (!encryptedId) {
            showMessage('⚠ Encrypted ID পাওয়া যায়নি।');
            try { certTab.close(); } catch (ex) {}
            resetBtn();
            return;
        }

        tryResolveViaEncId(encryptedId);
    });

    $(document).on('click', '.action-register', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const $self = $(this);
        const svc = getCurrentService();
        ensureEncryptedId($self, function(enc) {
            if (svc === 'dr') {
                if (!confirm('আপনি কি Register করতে চান?')) return;
                $.ajax({
                    url: 'proxy_list.php',
                    type: 'POST',
                    dataType: 'json',
                    timeout: 30000,
                    data: { action: 'register', encryptedId: enc, service: svc, csrfToken: csrfToken() }
                }).done(function(resp) {
                    showMessage(resp && (resp.message || resp.error) ? (resp.message || resp.error) : 'Register রিকুয়েস্ট পাঠানো হয়েছে।');
                }).fail(function(jqXHR) {
                    showMessage('Register ব্যর্থ। (' + (jqXHR.status || '') + ')');
                }).always(function() {
                    reloadCurrentList();
                });
                return;
            }

            $('#registerEncryptedId').val(enc);
            $('#registerOtp').val('');
            $('#registerBirthVerifierName').val('');
            $('#registerBirthVerifierBrn').val('');
            $('#registerBirthVerifierDate').val('');
            $('#registerAddrVerifierName').val('');
            $('#registerAddrVerifierBrn').val('');
            $('#registerAddrVerifierDate').val('');
            $('#registerModal').modal('show');
        });
    });

    $(document).on('click', '.action-dup-check', function(e) {
        if (e && e.preventDefault) e.preventDefault();
        const $self = $(this);
        ensureEncryptedId($self, function(enc) {
            window.open('duplicates.php?data=' + encodeURIComponent(enc), '_blank');
        });
    });

    $('#registerConfirmBtn').on('click', function() {
        const enc = String($('#registerEncryptedId').val() || '').trim();
        if (!enc) return;
        const payload = {
            action: 'register',
            encryptedId: enc,
            service: getCurrentService(),
            csrfToken: csrfToken(),
            birthPlaceAndDobVerifierName: String($('#registerBirthVerifierName').val() || '').trim(),
            birthPlaceAndDobVerifierBrn: String($('#registerBirthVerifierBrn').val() || '').trim(),
            birthPlaceAndDobVerificationDate: String($('#registerBirthVerifierDate').val() || '').trim(),
            permAddrVerifierName: String($('#registerAddrVerifierName').val() || '').trim(),
            permAddrVerifierBrn: String($('#registerAddrVerifierBrn').val() || '').trim(),
            permAddrVerificationDate: String($('#registerAddrVerifierDate').val() || '').trim(),
            otp: String($('#registerOtp').val() || '').trim()
        };

        $.ajax({
            url: 'proxy_list.php',
            type: 'POST',
            dataType: 'json',
            timeout: 30000,
            data: payload
        }).done(function(resp) {
            $('#registerModal').modal('hide');
            showMessage(resp && (resp.message || resp.error) ? (resp.message || resp.error) : 'Register রিকুয়েস্ট পাঠানো হয়েছে।');
        }).fail(function(jqXHR) {
            showMessage('Register ব্যর্থ। (' + (jqXHR.status || '') + ')');
        }).always(function() {
            reloadCurrentList();
        });
    });
});

function goDuplicateDirect(){
    let appId = document.getElementById("applicationSearchValue").value;
    if(!appId){
        alert("আবেদন নম্বর দিন");
        return;
    }
    let officeId = document.getElementById("officeId").value;
    let service = document.getElementById("applicationService").value;
    let csrfToken = String((document.getElementById("csrfTokenInput") || {}).value || "").trim();
    fetch("proxy_list.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: "action=resolve_encrypted&appId=" + encodeURIComponent(appId) + "&officeId=" + encodeURIComponent(officeId) + "&service=" + encodeURIComponent(service) + "&csrfToken=" + encodeURIComponent(csrfToken)
    })
    .then(res => res.json())
    .then(data => {
        if(data.encryptedId){
            window.open("duplicates.php?data=" + encodeURIComponent(data.encryptedId), "_blank");
        }else{
            alert("Encrypted ID পাওয়া যায়নি");
        }
    });
}

function goViewDirect(){
    let appId = document.getElementById("applicationSearchValue").value;
    if(!appId){
        alert("আবেদন নম্বর দিন");
        return;
    }
    let officeId = document.getElementById("officeId").value;
    let service = document.getElementById("applicationService").value;
    let csrfToken = String((document.getElementById("csrfTokenInput") || {}).value || "").trim();
    fetch("proxy_list.php", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: "action=resolve_encrypted&appId=" + encodeURIComponent(appId) + "&officeId=" + encodeURIComponent(officeId) + "&service=" + encodeURIComponent(service) + "&csrfToken=" + encodeURIComponent(csrfToken)
    })
    .then(res => res.json())
    .then(data => {
        if(data.encryptedId){
            const enc = data.encryptedId;
            $('#applicationDetailsPre').text('Loading...');
            $('#applicationDetailsModal').modal('show');
            $.ajax({
                url: 'proxy_list.php',
                type: 'POST',
                dataType: 'json',
                data: { action: 'details', encryptedId: enc, service: String($('#applicationService').val() || 'br'), csrfToken: String($('#csrfTokenInput').val() || '').trim() }
            }).done(function(resp) {
                $('#applicationDetailsPre').text(JSON.stringify(resp || {}, null, 2));
            }).fail(function(jqXHR) {
                $('#applicationDetailsPre').text('ডাটা আনতে সমস্যা হয়েছে। (' + (jqXHR.status || '') + ')');
            });
        }else{
            alert("আবেদন খুঁজে পাওয়া যায়নি");
        }
    });
}

function goDirectAction(type) {
    let input = document.getElementById("directPrintData").value.trim();
    if (!input) {
        alert("অনুগ্রহ করে বক্সে লিংক বা ডাটা পেস্ট করুন");
        return;
    }
    let dataVal = input;
    let match = input.match(/[?&]data=([A-Za-z0-9_\-]+)/i);
    if (match) {
        dataVal = match[1];
    } else if (input.indexOf('http') === 0) {
        alert("লিংকে data= প্যারামিটার পাওয়া যায়নি।");
        return;
    }
    
    let url = "";
    if (type === 'duplicate') {
        url = "duplicates.php?data=" + encodeURIComponent(dataVal);
    } else {
        url = "print-official.php?type=" + type + "&data=" + encodeURIComponent(dataVal);
    }
    
    window.open(url, "_blank");
}

function goDocumentPrint() {
    let appId = document.getElementById("applicationSearchValue").value.trim();
    if (!appId) {
        alert("আবেদন নম্বর দিন");
        return;
    }
    let officeId = document.getElementById("officeId").value;
    let url = "print-documents.php?app_id=" + encodeURIComponent(appId) + "&officeId=" + encodeURIComponent(officeId);
    window.open(url, "_blank");
}
</script>

<div class="modal fade" id="applicationDetailsModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">আবেদনপত্রের বিবরণ</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <pre id="applicationDetailsPre" class="mb-0"></pre>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="possibleDuplicatesModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Possible Duplicate</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <pre id="possibleDuplicatesPre" class="mb-0"></pre>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">রেজিস্টার (Birth)</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="registerEncryptedId">

                <div class="form-group">
                    <label>Birth Place &amp; DOB Verifier Name</label>
                    <input type="text" class="form-control" id="registerBirthVerifierName">
                </div>
                <div class="form-group">
                    <label>Birth Place &amp; DOB Verifier BRN</label>
                    <input type="text" class="form-control" id="registerBirthVerifierBrn">
                </div>
                <div class="form-group">
                    <label>Birth Place &amp; DOB Verification Date</label>
                    <input type="text" class="form-control" id="registerBirthVerifierDate" placeholder="YYYY-MM-DD অথবা DD/MM/YYYY">
                </div>

                <div class="form-group">
                    <label>Permanent Address Verifier Name</label>
                    <input type="text" class="form-control" id="registerAddrVerifierName">
                </div>
                <div class="form-group">
                    <label>Permanent Address Verifier BRN</label>
                    <input type="text" class="form-control" id="registerAddrVerifierBrn">
                </div>
                <div class="form-group">
                    <label>Permanent Address Verification Date</label>
                    <input type="text" class="form-control" id="registerAddrVerifierDate" placeholder="YYYY-MM-DD অথবা DD/MM/YYYY">
                </div>

                <div class="form-group">
                    <label>OTP (যদি লাগে)</label>
                    <input type="text" class="form-control" id="registerOtp">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">বন্ধ</button>
                <button type="button" class="btn btn-primary" id="registerConfirmBtn">Confirm</button>
            </div>
        </div>
    </div>
</div>

</body>
</html>
