<?php
/**
 * bdris-relay.php
 * এই পেজ আপনার ব্রাউজারে খুললে BDRIS API call করে ফলাফল দেখাবে।
 * আপনার ব্রাউজারে BDRIS session থাকলে cookies স্বয়ংক্রিয়ভাবে যাবে।
 */
header('Content-Type: text/html; charset=utf-8');
header('X-Frame-Options: SAMEORIGIN');
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<title>BDRIS Relay Worker</title>
<style>
body { font-family: monospace; background: #0f172a; color: #4ade80; padding: 20px; }
pre { white-space: pre-wrap; word-break: break-all; }
</style>
</head>
<body>
<pre id="out">কাজ চলছে...</pre>
<script>
(async function() {
    const params = new URLSearchParams(location.search);
    const type = params.get('type') || 'ubrn';
    const key = params.get('key') || params.get('ubrn') || '';
    const service = params.get('service') || 'br';
    const svcPrefix = (service === 'dr') ? 'dr' : 'br';
    const returnUrl = params.get('return') || '';
    const out = document.getElementById('out');
    
    let found = null;
    let finalSource = '';
    
    function log(msg) { out.textContent += '\n' + msg; }
    
    log('Type: ' + type);
    log('Key: ' + key);
    log('Service: ' + service);
    log('BDRIS API কল করছে...');
    
    let apis = [];
    let method = 'GET';
    let bodyData = null;

    if (type === 'app_id') {
        // ✅ ১-step: সরাসরি detail endpoint দিয়ে চেষ্টা
        let encId = '';
        try {
            const r1 = await fetch('https://bdris.gov.bd/api/' + svcPrefix + '/application/details/' + encodeURIComponent(key), {
                credentials: 'include',
                headers: {'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'client': 'bris'}
            });
            log('Step1 status: ' + r1.status);
            if (r1.ok) {
                const d1 = await r1.json();
                if (d1 && !d1.EXCEPTION && !d1.error) {
                    const brn = d1.birthRegistrationNumber || d1.personBrn || d1.data?.birthRegistrationNumber || d1.deathRegistrationNumber || d1.data?.deathRegistrationNumber || '';
                    encId = d1.encryptedId || d1.encryptedID || d1.encryptedApplicationId || d1.data?.encryptedId || '';
                    if (brn) {
                        log('✅ ID সরাসরি পাওয়া গেছে: ' + brn);
                        found = Object.assign({}, d1.data || d1);
                        finalSource = 'direct-detail';
                    } else if (encId) {
                        log('encryptedId পাওয়া গেছে, step 2 চেষ্টার জন্য…');
                    }
                }
            }
        } catch(e) { log('Step1 error: ' + e.message); }

        // ✅ ২-step: encryptedId দিয়ে পুরো তথ্য আনো (BRN সহ)
        if (!found && encId) {
            try {
                const r2 = await fetch('https://bdris.gov.bd/api/application/details?data=' + encodeURIComponent(encId), {
                    credentials: 'include',
                    headers: {'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'client': 'bris'}
                });
                log('Step2 status: ' + r2.status);
                if (r2.ok) {
                    const d2 = await r2.json();
                    if (d2 && !d2.EXCEPTION) {
                        found = d2.data || d2;
                        finalSource = 'encrypted-detail';
                        log('✅ Step2 থেকে পুরো তথ্য পাওয়া গেছে।');
                    }
                }
            } catch(e) { log('Step2 error: ' + e.message); }
        }

        // ✅ ৩-step: search API দিয়ে encId খোঁজা, তারপর full detail
        if (!found) {
            try {
                const sUrl = 'https://bdris.gov.bd/api/' + svcPrefix + '/applications/search?' +
                    new URLSearchParams({'status': 'ALL', 'draw': '1', 'start': '0', 'length': '10',
                        'search[value]': key, 'search[regex]': 'false',
                        'order[0][column]': '1', 'order[0][dir]': 'desc', 'order[0][name]': ''});
                const rs = await fetch(sUrl, {
                    credentials: 'include',
                    headers: {'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'client': 'bris'}
                });
                log('Step3-search status: ' + rs.status);
                if (rs.ok) {
                    const ds = await rs.json();
                    const rows = ds.data || [];
                    const match = rows.find(r => String(r.id||'') === String(key) || String(r.applicationNo||'') === String(key));
                    if (match) {
                        encId = match.encryptedId || match.encryptedID || match.encryptedApplicationId || '';
                        log('সার্চ থেকে match পাওয়া গেছে, encId: ' + encId);
                        if (encId) {
                            const rd = await fetch('https://bdris.gov.bd/api/application/details?data=' + encodeURIComponent(encId), {
                                credentials: 'include',
                                headers: {'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'client': 'bris'}
                            });
                            if (rd.ok) {
                                const dd = await rd.json();
                                found = Object.assign({}, match, dd.data || dd);
                                finalSource = 'search+detail';
                                log('✅ Step3 থেকে পুরো তথ্য পাওয়া গেছে।');
                            }
                        } else {
                            found = match; // যা আছে তাই দিয়ে show
                            finalSource = 'search-only';
                        }
                    }
                }
            } catch(e) { log('Step3 error: ' + e.message); }
        }

        // সব শেষে /api/br/info/application চেষ্টা
        if (!found) {
            apis = ['https://bdris.gov.bd/api/' + svcPrefix + '/info/application/' + encodeURIComponent(key)];
        } else {
            apis = []; // already found, skip loop
        }

    } else if (type === 'name') {
        const nameBn = params.get('nameBn') || '';
        const nameEn = params.get('nameEn') || '';
        const nameLang = params.get('nameLang') || 'BENGALI';
        method = 'POST';
        const fd = new URLSearchParams();
        fd.append('personNameBn', nameBn);
        fd.append('personNameEn', nameEn);
        fd.append('nameLang', nameLang);
        fd.append('draw', '1');
        fd.append('start', '0');
        fd.append('length', '200'); // ✅ বেশি ফলাফল
        fd.append('search[value]', '');
        fd.append('search[regex]', 'false');
        fd.append('order[0][column]', '0');
        fd.append('order[0][dir]', 'desc');
        // ✅ officeId ও data পাঠাচ্ছি না — সারা বাংলাদেশ সার্চ
        bodyData = fd;
        
        apis = [
            'https://bdris.gov.bd/api/' + svcPrefix + '/advanced-search-by-name',
            'https://bdris.gov.bd/api/' + svcPrefix + '/advanced/search-by-name',
            'https://bdris.gov.bd/api/' + svcPrefix + '/search/by-name'
        ];

    } else {
        // default: UBRN / UDRN
        const numName = (service === 'dr') ? 'udrn' : 'ubrn';
        apis = [
            'https://bdris.gov.bd/api/' + svcPrefix + '/info/' + numName + '/' + key,
            'https://bdris.gov.bd/api/' + svcPrefix + '/register/search/by-' + numName + '?' + numName + '=' + key,
            'https://everify.bdris.gov.bd/api/' + svcPrefix + '/info/' + numName + '/' + key,
        ];
    }
    
    for (const url of apis) {
        try {
            log('\nচেষ্টা: ' + url);
            const fetchOpts = {
                method: method,
                credentials: 'include',
                headers: {
                    'Accept': 'application/json, text/html, */*',
                    'X-Requested-With': 'XMLHttpRequest',
                    'client': 'bris'
                }
            };
            if (method === 'POST') {
                fetchOpts.body = bodyData;
                fetchOpts.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
            }

            const r = await fetch(url, fetchOpts);
            log('Status: ' + r.status);
            if (r.ok) {
                const text = await r.text();
                try {
                    const data = JSON.parse(text);
                    if (data && !data.error && !data.EXCEPTION) {
                        log('✅ সফল! JSON Data পাওয়া গেছে।');
                        found = data;
                        finalSource = url;
                        break;
                    }
                } catch(e) {
                    // Could be HTML (like app_id returns HTML sometimes?)
                    // Or maybe app_id returns JSON. Let's assume JSON.
                    if (type === 'app_id') {
                        // app_id usually returns JSON if we call /admin/br/applications/ ? 
                        // Wait, /admin/br/applications/ might return HTML page!
                        // Let's just save the text if it's not JSON.
                        log('✅ HTML Data পাওয়া গেছে।');
                        found = text;
                        finalSource = url;
                        break;
                    }
                }
            }
        } catch(e) {
            log('Error: ' + e.message);
        }
    }
    
    if (found) {
        // Send result back to our server
        const postUrl = '<?= (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === "on" ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["PHP_SELF"]), "/") ?>/api/relay-result.php';
        await fetch(postUrl, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({key: key, type: type, data: found, source: finalSource})
        }).catch(()=>{});

        // Extract DOB and redirect if UBRN
        const p = found?.personMaster?.data || found?.personMaster || found;
        const dob = p?.personBirthDate || p?.dateOfBirth || '';
        const name = p?.personNameBn || p?.nameBn || '';
        window.opener?.postMessage({type:'bdris_result', key, dob, name, data: found}, '*');
        log('\nফলাফল পাঠানো হয়েছে। এই ট্যাব বন্ধ করুন।');
        
        if (returnUrl) {
            window.location.href = returnUrl + (returnUrl.includes('?') ? '&' : '?') + 'key=' + key + '&dob=' + dob;
        } else {
            setTimeout(() => window.close(), 1500);
        }
    }
    
    if (!found) {
        log('\n❌ তথ্য পাওয়া যায়নি। BDRIS-এ লগিন করুন।');
        window.opener?.postMessage({type:'bdris_error', key, error: 'not_found'}, '*');
    }
})();
</script>
</body>
</html>
