<?php
require_once __DIR__ . '/includes/ProxyHelper.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
    exit;
}

$action = $_POST['action'] ?? '';
$helper = new ProxyHelper();
$csrf = $helper->getCsrfToken();
$extraHeaders = [
    'X-Requested-With: XMLHttpRequest',
    'Accept: application/json, text/javascript, */*; q=0.01'
];
if ($csrf) {
    $extraHeaders[] = 'X-CSRF-TOKEN: ' . $csrf;
}

function returnSuccess($data) {
    echo json_encode(['status' => 'success', 'data' => $data]);
    exit;
}

function returnError($msg, $debug = null) {
    $res = ['status' => 'error', 'message' => $msg];
    if ($debug) $res['debug'] = $debug;
    echo json_encode($res);
    exit;
}

function fetchBypassedUbrnData($ubrn, $helper, $extraHeaders) {
    // 1. Try bdris /register/search/by-ubrn
    $url = "https://bdris.gov.bd/api/br/register/search/by-ubrn?ubrn=" . urlencode($ubrn);
    $res = $helper->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/admin/br/search', $extraHeaders);
    $data = json_decode($res['body'], true);
    if (json_last_error() === JSON_ERROR_NONE && !empty($data) && !isset($data['code'])) {
        return $data;
    }

    // 2. Try bdris /search-by-ubrn
    $url = "https://bdris.gov.bd/api/br/search-by-ubrn?ubrn=" . urlencode($ubrn);
    $res = $helper->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/admin/br/search', $extraHeaders);
    $data = json_decode($res['body'], true);
    if (json_last_error() === JSON_ERROR_NONE && !empty($data) && !isset($data['code'])) {
        return $data;
    }

    // 3. Try everify /info/ubrn
    $url = "https://everify.bdris.gov.bd/api/br/info/ubrn/" . urlencode($ubrn);
    $res = $helper->fetch($url, 'GET', [], false, 'https://everify.bdris.gov.bd/');
    $data = json_decode($res['body'], true);
    if (json_last_error() === JSON_ERROR_NONE && !empty($data) && !isset($data['code'])) {
        return $data;
    }

    // 4. Try everify /register/search/by-ubrn
    $url = "https://everify.bdris.gov.bd/api/br/register/search/by-ubrn?ubrn=" . urlencode($ubrn);
    $res = $helper->fetch($url, 'GET', [], false, 'https://everify.bdris.gov.bd/');
    $data = json_decode($res['body'], true);
    if (json_last_error() === JSON_ERROR_NONE && !empty($data) && !isset($data['code'])) {
        return $data;
    }

    return null;
}

function checkRelayCache($ubrn) {
    $cacheFile = __DIR__ . '/cache/relay_' . $ubrn . '.json';
    if (file_exists($cacheFile)) {
        $cdata = json_decode(file_get_contents($cacheFile), true);
        if ($cdata && (time() - ($cdata['time'] ?? 0) < 86400 * 7)) { // 7 days TTL for static registration data
            return $cdata['data'] ?? null;
        }
    }
    return null;
}

try {
    switch ($action) {
        // 1. NID Check
        case 'nid_check':
            $nid = trim($_POST['nid'] ?? '');
            $dob = trim($_POST['dob'] ?? '');
            if (!$nid || !$dob) returnError('NID এবং Date of Birth দিন।');
            
            // Convert YYYY-MM-DD to DD/MM/YYYY
            if (preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $dob, $m)) {
                $dob = "{$m[3]}/{$m[2]}/{$m[1]}";
            }
            
            $url = "https://bdris.gov.bd/api/uid/get-nid-verification-by-nid-dob-data-group?nid=" . urlencode($nid) . "&dob=" . urlencode($dob) . "&dataGroup=1";
            $res = $helper->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/admin/br/search', $extraHeaders);
            
            // Check if response contains HTML or 404 error page (service disabled/restricted by BDRIS/EC)
            if (stripos($res['body'], '<html') !== false || stripos($res['body'], 'Page not found') !== false) {
                returnError('এনআইডি যাচাই সাময়িকভাবে বন্ধ আছে অথবা বিডিআরআইএস (BDRIS) সার্ভার এই মুহূর্তে এনআইডি ডাটাবেজের সাথে যোগাযোগ করতে পারছে না। (Upstream API 404/400)');
            }
            
            $data = json_decode($res['body'], true);
            if(json_last_error() === JSON_ERROR_NONE && !empty($data)) returnSuccess($data);
            returnError('NID যাচাই ফেইল হয়েছে। সার্ভার থেকে সঠিক রেসপন্স আসেনি।', $res['body']);

        // 2. Cancel List
        case 'cancel_list':
            $searchValue = trim($_POST['searchValue'] ?? '');
            if (!$searchValue) returnError('Application ID বা UBRN দিন।');
            
            // Get active profile to read officeId
            $activeProfile = trim((string)@file_get_contents(__DIR__.'/cookies/active_profile.txt'));
            if (!$activeProfile) $activeProfile = 'default';
            $officeIdFile = __DIR__."/cookies/active_office_{$activeProfile}.txt";
            $officeIdToken = file_exists($officeIdFile) ? trim(file_get_contents($officeIdFile)) : '';
            $officeId = $helper->getIntegerOfficeId($officeIdToken);
            
            $sparams = [
                'draw' => 1,
                'columns' => [['data' => 'applicationId', 'searchable' => true, 'orderable' => true, 'search' => ['value' => '', 'regex' => false]]],
                'order' => [['column' => 0, 'dir' => 'desc']],
                'start' => 0,
                'length' => 10,
                'search' => ['value' => $searchValue, 'regex' => false],
                'officeId' => $officeId
            ];
            $url = "https://bdris.gov.bd/api/br/certificate-cancellation-applications/search?" . http_build_query($sparams);
            $res = $helper->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/admin/br/certificate-cancellation-applications/search', $extraHeaders);
            $data = json_decode($res['body'], true);
            if(json_last_error() === JSON_ERROR_NONE && !empty($data)) returnSuccess($data);
            returnError('বাতিল আবেদনের লিস্ট আনতে ব্যর্থ হয়েছে।', $res['body']);

        // 3. Parent Info & thChild
        case 'parent_info':
            $ubrn = trim($_POST['ubrn'] ?? '');
            if (!$ubrn) returnError('UBRN দিন।');
            
            // Check Relay Cache first
            $cached = checkRelayCache($ubrn);
            if ($cached) {
                returnSuccess($cached);
            }
            
            $url = "https://bdris.gov.bd/api/br/info/ubrn/" . urlencode($ubrn);
            $res = $helper->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/admin/br/search', $extraHeaders);
            $data = json_decode($res['body'], true);
            if(json_last_error() === JSON_ERROR_NONE && !empty($data) && !isset($data['code'])) {
                returnSuccess($data);
            }
            $bypassData = fetchBypassedUbrnData($ubrn, $helper, $extraHeaders);
            if ($bypassData) {
                returnSuccess($bypassData);
            }
            returnError('পিতামাতার তথ্য পাওয়া যায়নি।', $res['body']);

        // 4. Advanced Info Search
        case 'adv_info':
            $ubrn = trim($_POST['ubrn'] ?? '');
            if (!$ubrn) returnError('UBRN দিন।');
            
            // Check Relay Cache first
            $cached = checkRelayCache($ubrn);
            if ($cached) {
                returnSuccess($cached);
            }
            
            $url = "https://bdris.gov.bd/api/br/info/ubrn/" . urlencode($ubrn);
            $res = $helper->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/admin/br/search', $extraHeaders);
            $data = json_decode($res['body'], true);
            if(json_last_error() === JSON_ERROR_NONE && !empty($data) && !isset($data['code'])) {
                returnSuccess($data);
            }
            $bypassData = fetchBypassedUbrnData($ubrn, $helper, $extraHeaders);
            if ($bypassData) {
                returnSuccess($bypassData);
            }
            returnError('কোনো তথ্য পাওয়া যায়নি।', $res['body']);

        // 5. Application Status
        case 'app_status':
            $searchValue = trim($_POST['searchValue'] ?? '');
            if (!$searchValue) returnError('Application ID বা UBRN দিন।');
            
            // Get active profile to read officeId
            $activeProfile = trim((string)@file_get_contents(__DIR__.'/cookies/active_profile.txt'));
            if (!$activeProfile) $activeProfile = 'default';
            $officeIdFile = __DIR__."/cookies/active_office_{$activeProfile}.txt";
            $officeIdToken = file_exists($officeIdFile) ? trim(file_get_contents($officeIdFile)) : '';
            $officeId = $helper->getIntegerOfficeId($officeIdToken);

            $sparams = [
                'draw' => 1,
                'columns' => [['data' => 'applicationId', 'searchable' => true, 'orderable' => true, 'search' => ['value' => '', 'regex' => false]]],
                'order' => [['column' => 0, 'dir' => 'desc']],
                'start' => 0,
                'length' => 10,
                'search' => ['value' => $searchValue, 'regex' => false],
                'officeId' => $officeId,
                'status' => 'ALL'
            ];
            $url = "https://bdris.gov.bd/api/br/applications/search?" . http_build_query($sparams);
            $res = $helper->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications/search', $extraHeaders);
            $data = json_decode($res['body'], true);
            if(json_last_error() === JSON_ERROR_NONE && !empty($data)) returnSuccess($data);
            returnError('আবেদনের স্ট্যাটাস পাওয়া যায়নি।', $res['body']);

        // 6. Alive Status
        case 'alive_status':
            $ubrn = trim($_POST['ubrn'] ?? '');
            if (!$ubrn) returnError('UBRN দিন।');
            
            // Check Relay Cache first
            $cached = checkRelayCache($ubrn);
            if ($cached) {
                returnSuccess($cached);
            }
            
            $url = "https://bdris.gov.bd/api/br/info/ubrn/" . urlencode($ubrn);
            $res = $helper->fetch($url, 'GET', [], false, 'https://bdris.gov.bd/admin/br/search', $extraHeaders);
            $data = json_decode($res['body'], true);
            if(json_last_error() === JSON_ERROR_NONE && !empty($data) && !isset($data['code'])) {
                returnSuccess($data);
            }
            $bypassData = fetchBypassedUbrnData($ubrn, $helper, $extraHeaders);
            if ($bypassData) {
                returnSuccess($bypassData);
            }
            returnError('স্ট্যাটাস জানা যায়নি।', $res['body']);

        default:
            returnError('অজানা অ্যাকশন।');
    }
} catch (Exception $e) {
    returnError('System Error: ' . $e->getMessage());
}
