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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'fetch_info') {
    header('Content-Type: application/json');
    $helper = new ProxyHelper();
    $searchInput = trim($_POST['ubrn'] ?? '');
    
    if (empty($searchInput)) {
        echo json_encode(['status' => 'error', 'message' => 'তথ্য দিন।']);
        exit;
    }
    
    $results = [];

    // 1. UBRN দিয়ে চেক (যদি ১৭ ডিজিট হয়)
    if (strlen($searchInput) === 17 && is_numeric($searchInput)) {
        $url1 = "https://bdris.gov.bd/api/br/search-by-ubrn?ubrn=" . urlencode($searchInput);
        $res1 = $helper->fetch($url1, 'GET', [], false, 'https://bdris.gov.bd/admin/br/search');
        $data1 = json_decode($res1['body'] ?? '', true);
        if (json_last_error() === JSON_ERROR_NONE && !empty($data1['dateOfBirth'])) {
            $results[] = [
                'nameBn' => $data1['nameBn'] ?? '',
                'nameEn' => $data1['nameEn'] ?? '',
                'dob' => $data1['dateOfBirth'] ?? '',
                'fatherNameBn' => $data1['fatherNameBn'] ?? '',
                'motherNameBn' => $data1['motherNameBn'] ?? '',
                'source' => 'Main Register'
            ];
        }
    }

    // 2. নাম / মোবাইল / UBRN দিয়ে Applications Search এ চেক (Advanced Fallback)
    // Here we use POST because DataTables usually requires POST, but we will use the exact GET format the JS script used.
    $url2 = "https://bdris.gov.bd/api/br/applications/search?search%5Bvalue%5D=" . urlencode($searchInput) . "&draw=1&start=0&length=10";
    $res2 = $helper->fetch($url2, 'GET', [], false, 'https://bdris.gov.bd/admin/br/applications/search');
    $data2 = json_decode($res2['body'] ?? '', true);
    
    if (json_last_error() === JSON_ERROR_NONE && isset($data2['data']) && is_array($data2['data'])) {
        foreach ($data2['data'] as $item) {
            $results[] = [
                'nameBn' => $item['nameBn'] ?? '',
                'nameEn' => $item['nameEn'] ?? '',
                'dob' => $item['dateOfBirth'] ?? '',
                'fatherNameBn' => $item['fatherNameBn'] ?? '',
                'motherNameBn' => $item['motherNameBn'] ?? '',
                'source' => 'Applications Search'
            ];
        }
    }

    if (count($results) > 0) {
        echo json_encode(['status' => 'success', 'data' => $results[0]]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'কোনো তথ্য পাওয়া যায়নি!']);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Search (উন্নত অনুসন্ধান)</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f4f7f6; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .main-container { max-width: 600px; margin: 40px auto; }
        .search-card { background: #fff; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); padding: 30px; }
        .result-box { margin-top: 20px; display: none; padding: 20px; border-radius: 8px; background: #e8f4ff; border-left: 5px solid #0056b3; }
        .result-box h4 { margin-top: 0; color: #0056b3; font-weight: bold; }
        .result-box p { margin: 5px 0; font-size: 16px; color: #333; }
    </style>
</head>
<body>

<div class="container main-container">
    <div class="search-card">
        <h3 class="text-center mb-4 text-primary">Advanced Search (উন্নত অনুসন্ধান)</h3>
        <form id="searchForm">
            <div class="mb-3">
                <label class="form-label fw-bold">UBRN / নাম / মোবাইল নম্বর দিন:</label>
                <input type="text" class="form-control form-control-lg" id="searchInput" placeholder="যেমন: 20082692068091735" required>
            </div>
            <button class="btn btn-primary btn-lg w-100" type="submit" id="searchBtn">অনুসন্ধান করুন</button>
        </form>

        <div id="loading" class="text-center mt-4" style="display:none;">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-2 text-muted">অপেক্ষা করুন...</p>
        </div>

        <div class="result-box" id="resultCard">
            <h4><span id="resEmoji">🎂</span> <span id="resName"></span></h4>
            <p><strong>জন্ম তারিখ:</strong> <span id="resDob"></span></p>
            <p><strong>পিতার নাম:</strong> <span id="resFather"></span></p>
            <p><strong>মাতার নাম:</strong> <span id="resMother"></span></p>
            <p><small class="text-muted">উৎস: <span id="resSource"></span></small></p>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $('#searchForm').on('submit', function(e) {
        e.preventDefault();
        const searchInput = $('#searchInput').val().trim();
        
        $('#resultCard').hide();
        $('#loading').show();
        $('#searchBtn').prop('disabled', true);

        $.post('advanced-info.php', { action: 'fetch_info', ubrn: searchInput }, function(res) {
            $('#loading').hide();
            $('#searchBtn').prop('disabled', false);

            if(res.status === 'success' && res.data) {
                const d = res.data;
                $('#resName').text(d.nameBn || d.nameEn || 'নাম নেই');
                $('#resDob').text(d.dob || '-');
                $('#resFather').text(d.fatherNameBn || '-');
                $('#resMother').text(d.motherNameBn || '-');
                $('#resSource').text(d.source || '-');
                $('#resultCard').fadeIn();
            } else {
                alert(res.message || 'কোনো তথ্য পাওয়া যায়নি।');
            }
        }).fail(function() {
            $('#loading').hide();
            $('#searchBtn').prop('disabled', false);
            alert('সার্ভার এরর!');
        });
    });
</script>
</body>
</html>
