<?php
// Session validation or authentication can go here if needed
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অ্যাডভান্সড সার্ভিসেস ড্যাশবোর্ড</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f8f9fa; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .sidebar { background: #343a40; min-height: 100vh; padding-top: 20px; color: white; }
        .sidebar .nav-link { color: #c2c7d0; padding: 12px 20px; margin-bottom: 5px; border-radius: 5px; font-weight: 500; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: #007bff; color: white; }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; text-align: center; }
        .main-content { padding: 30px; }
        .card { border: none; box-shadow: 0 2px 10px rgba(0,0,0,0.08); border-radius: 10px; }
        .card-header { background: #fff; border-bottom: 2px solid #007bff; padding: 20px; font-weight: bold; font-size: 1.2rem; border-top-left-radius: 10px; border-top-right-radius: 10px; }
        pre.json-result { background: #2d2d2d; color: #a4d271; padding: 15px; border-radius: 5px; max-height: 400px; overflow-y: auto; font-size: 14px; }
        .table-custom { margin-top: 20px; }
    </style>
</head>
<body>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-3 col-lg-2 sidebar">
            <h4 class="text-center mb-4 border-bottom pb-3">অফিস সার্ভিসেস</h4>
            <div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
                <button class="nav-link active" id="v-pills-nid-tab" data-bs-toggle="pill" data-bs-target="#v-pills-nid" type="button" role="tab"><i class="fas fa-id-card"></i> এনআইডি যাচাই</button>
                <button class="nav-link" id="v-pills-cancel-tab" data-bs-toggle="pill" data-bs-target="#v-pills-cancel" type="button" role="tab"><i class="fas fa-ban"></i> সার্টিফিকেট বাতিল</button>
                <button class="nav-link" id="v-pills-parent-tab" data-bs-toggle="pill" data-bs-target="#v-pills-parent" type="button" role="tab"><i class="fas fa-users"></i> পিতামাতার তথ্য</button>
                <button class="nav-link" id="v-pills-adv-tab" data-bs-toggle="pill" data-bs-target="#v-pills-adv" type="button" role="tab"><i class="fas fa-search-plus"></i> অ্যাডভান্সড তথ্য</button>
                <button class="nav-link" id="v-pills-status-tab" data-bs-toggle="pill" data-bs-target="#v-pills-status" type="button" role="tab"><i class="fas fa-tasks"></i> আবেদনের স্ট্যাটাস</button>
                <button class="nav-link" id="v-pills-alive-tab" data-bs-toggle="pill" data-bs-target="#v-pills-alive" type="button" role="tab"><i class="fas fa-heartbeat"></i> জীবিত স্ট্যাটাস</button>
                <a href="application-print.php" class="nav-link" style="color: #cbd5e1;"><i class="fas fa-print"></i> আবেদন পত্র প্রিন্ট</a>
            </div>
            <div class="mt-auto p-3 text-center w-100" style="position: absolute; bottom: 0;">
                <a href="universal-dashboard.php" class="btn btn-outline-light w-100"><i class="fas fa-arrow-left"></i> মেইন ড্যাশবোর্ড</a>
            </div>
        </div>

        <!-- Main Content -->
        <div class="col-md-9 col-lg-10 main-content">
            <div class="tab-content" id="v-pills-tabContent">
                
                <!-- 1. NID Check -->
                <div class="tab-pane fade show active" id="v-pills-nid" role="tabpanel">
                    <div class="card">
                        <div class="card-header text-primary"><i class="fas fa-id-card"></i> এনআইডি (NID) যাচাই</div>
                        <div class="card-body">
                            <form id="form-nid">
                                <input type="hidden" name="action" value="nid_check">
                                <div class="row">
                                    <div class="col-md-5 mb-3">
                                        <label>এনআইডি নম্বর (NID)</label>
                                        <input type="text" class="form-control" name="nid" required>
                                    </div>
                                    <div class="col-md-5 mb-3">
                                        <label>জন্ম তারিখ (DOB)</label>
                                        <input type="date" class="form-control" name="dob" required>
                                    </div>
                                    <div class="col-md-2 mb-3 d-flex align-items-end">
                                        <button class="btn btn-primary w-100" type="submit">যাচাই করুন</button>
                                    </div>
                                </div>
                            </form>
                            <div class="result-area mt-3" style="display:none;"></div>
                        </div>
                    </div>
                </div>

                <!-- 2. Cancel List -->
                <div class="tab-pane fade" id="v-pills-cancel" role="tabpanel">
                    <div class="card">
                        <div class="card-header text-danger"><i class="fas fa-ban"></i> বাতিল হওয়া আবেদন ও সার্চ</div>
                        <div class="card-body">
                            <form id="form-cancel">
                                <input type="hidden" name="action" value="cancel_list">
                                <div class="row">
                                    <div class="col-md-9 mb-3">
                                        <label>সার্চ ভ্যালু (UBRN / App ID)</label>
                                        <input type="text" class="form-control" name="searchValue" placeholder="খালি রাখলে লেটেস্ট ৫০টি আবেদন আসবে">
                                    </div>
                                    <div class="col-md-3 mb-3 d-flex align-items-end">
                                        <button class="btn btn-danger w-100" type="submit">লিস্ট আনুন</button>
                                    </div>
                                </div>
                            </form>
                            <div class="result-area mt-3" style="display:none;"></div>
                        </div>
                    </div>
                </div>

                <!-- 3. Parent Info -->
                <div class="tab-pane fade" id="v-pills-parent" role="tabpanel">
                    <div class="card">
                        <div class="card-header text-success"><i class="fas fa-users"></i> পিতামাতার তথ্য ও কততম সন্তান</div>
                        <div class="card-body">
                            <form id="form-parent">
                                <input type="hidden" name="action" value="parent_info">
                                <div class="row">
                                    <div class="col-md-9 mb-3">
                                        <label>জন্ম নিবন্ধন নম্বর (UBRN)</label>
                                        <input type="text" class="form-control" name="ubrn" required>
                                    </div>
                                    <div class="col-md-3 mb-3 d-flex align-items-end">
                                        <button class="btn btn-success w-100" type="submit">অনুসন্ধান</button>
                                    </div>
                                </div>
                            </form>
                            <div class="result-area mt-3" style="display:none;"></div>
                        </div>
                    </div>
                </div>

                <!-- 4. Advanced Info -->
                <div class="tab-pane fade" id="v-pills-adv" role="tabpanel">
                    <div class="card">
                        <div class="card-header text-info"><i class="fas fa-search-plus"></i> অ্যাডভান্সড তথ্য যাচাই</div>
                        <div class="card-body">
                            <form id="form-adv">
                                <input type="hidden" name="action" value="adv_info">
                                <div class="row">
                                    <div class="col-md-9 mb-3">
                                        <label>জন্ম নিবন্ধন নম্বর (UBRN)</label>
                                        <input type="text" class="form-control" name="ubrn" required>
                                    </div>
                                    <div class="col-md-3 mb-3 d-flex align-items-end">
                                        <button class="btn btn-info w-100 text-white" type="submit">পূর্ণাঙ্গ তথ্য আনুন</button>
                                    </div>
                                </div>
                            </form>
                            <div class="result-area mt-3" style="display:none;"></div>
                        </div>
                    </div>
                </div>

                <!-- 5. App Status -->
                <div class="tab-pane fade" id="v-pills-status" role="tabpanel">
                    <div class="card">
                        <div class="card-header text-warning"><i class="fas fa-tasks"></i> আবেদনের বর্তমান স্ট্যাটাস</div>
                        <div class="card-body">
                            <form id="form-status">
                                <input type="hidden" name="action" value="app_status">
                                <div class="row">
                                    <div class="col-md-9 mb-3">
                                        <label>আবেদন আইডি (App ID) অথবা UBRN</label>
                                        <input type="text" class="form-control" name="searchValue" required>
                                    </div>
                                    <div class="col-md-3 mb-3 d-flex align-items-end">
                                        <button class="btn btn-warning w-100" type="submit">স্ট্যাটাস দেখুন</button>
                                    </div>
                                </div>
                            </form>
                            <div class="result-area mt-3" style="display:none;"></div>
                        </div>
                    </div>
                </div>

                <!-- 6. Alive Status -->
                <div class="tab-pane fade" id="v-pills-alive" role="tabpanel">
                    <div class="card">
                        <div class="card-header text-secondary"><i class="fas fa-heartbeat"></i> জীবিত স্ট্যাটাস চেক</div>
                        <div class="card-body">
                            <form id="form-alive">
                                <input type="hidden" name="action" value="alive_status">
                                <div class="row">
                                    <div class="col-md-9 mb-3">
                                        <label>জন্ম নিবন্ধন নম্বর (UBRN)</label>
                                        <input type="text" class="form-control" name="ubrn" required>
                                    </div>
                                    <div class="col-md-3 mb-3 d-flex align-items-end">
                                        <button class="btn btn-secondary w-100" type="submit">যাচাই করুন</button>
                                    </div>
                                </div>
                            </form>
                            <div class="result-area mt-3" style="display:none;"></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/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $('form').on('submit', function(e) {
        e.preventDefault();
        const form = $(this);
        const btn = form.find('button[type="submit"]');
        const originalText = btn.html();
        const resultArea = form.next('.result-area');
        
        btn.html('<i class="fas fa-spinner fa-spin"></i> লোডিং...');
        btn.prop('disabled', true);
        resultArea.hide();

        $.ajax({
            url: 'proxy-services.php',
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            success: function(res) {
                btn.html(originalText);
                btn.prop('disabled', false);
                
                if (res.status === 'success') {
                    let html = '<div class="alert alert-success"><i class="fas fa-check-circle"></i> সফলভাবে ডাটা পাওয়া গেছে!</div>';
                    html += '<h5>বিস্তারিত তথ্য (Raw JSON Data):</h5>';
                    html += '<pre class="json-result">' + JSON.stringify(res.data, null, 4) + '</pre>';
                    resultArea.html(html).slideDown();
                } else {
                    const ubrnInput = form.find('input[name="ubrn"]');
                    const ubrnVal = ubrnInput.length ? ubrnInput.val().trim() : '';
                    const errorMsg = res.message || '';
                    const debugMsg = res.debug ? res.debug.toString() : '';
                    const isAreaError = errorMsg.includes('আওতাধীন নয়') || debugMsg.includes('আওতাধীন নয়') || errorMsg.includes('পিতামাতার তথ্য পাওয়া যায়নি') || errorMsg.includes('কোনো তথ্য পাওয়া যায়নি') || errorMsg.includes('স্ট্যাটাস জানা যায়নি');
                    
                    if (isAreaError && ubrnVal) {
                        let html = '<div class="alert alert-warning">';
                        html += '<i class="fas fa-exclamation-triangle me-2"></i> এটি অন্য এলাকার তথ্য (আওতাধীন নয়)।<br>';
                        html += 'বাইপাস করতে নিচের বাটনটি চাপুন — ব্রাউজার রিলে দিয়ে তথ্য আনা হবে।<br><br>';
                        html += '<button type="button" class="btn btn-success fw-bold btn-sm" onclick="triggerRelayBypass(\'' + ubrnVal + '\', this)">';
                        html += '<i class="fas fa-external-link-alt"></i> রিলে দিয়ে তথ্য আনুন</button>';
                        html += '</div>';
                        resultArea.html(html).slideDown();
                    } else {
                        let html = '<div class="alert alert-danger"><i class="fas fa-times-circle"></i> ' + (res.message || 'Error') + '</div>';
                        if(res.debug) {
                            let escapedDebug = res.debug.toString().replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
                            html += '<p><strong>সার্ভার রেসপন্স:</strong></p><pre class="json-result" style="background:#4a1515; color:#f87171;">' + escapedDebug + '</pre>';
                        }
                        resultArea.html(html).slideDown();
                    }
                }
            },
            error: function() {
                btn.html(originalText);
                btn.prop('disabled', false);
                resultArea.html('<div class="alert alert-danger">সার্ভার এরর অথবা টাইমআউট!</div>').slideDown();
            }
        });
    });

    function triggerRelayBypass(ubrn, btnEl) {
        const origHtml = btnEl.innerHTML;
        btnEl.disabled = true;
        btnEl.innerHTML = '<i class="fas fa-spinner fa-spin"></i> রিলে সক্রিয় হচ্ছে...';
        
        const w = 600, h = 480;
        const left = (screen.width/2)-(w/2);
        const top = (screen.height/2)-(h/2);
        const relayUrl = 'bdris-relay.php?type=ubrn&key=' + encodeURIComponent(ubrn);
        
        const popup = window.open(relayUrl, 'BDRISBypassRelay', `width=${w},height=${h},top=${top},left=${left}`);
        
        const pollClose = setInterval(() => {
            if (popup && popup.closed) {
                clearInterval(pollClose);
                btnEl.disabled = false;
                btnEl.innerHTML = origHtml;
            }
        }, 700);
        
        function relayHandler(e) {
            if (!e.data || e.data.type !== 'bdris_result' || e.data.ubrn !== ubrn) return;
            clearInterval(pollClose);
            window.removeEventListener('message', relayHandler);
            popup.close();
            
            // Find the active tab form and re-submit it
            const activePane = $('.tab-pane.active, .tab-pane.show.active');
            let form = activePane.find('form');
            if (!form.length) {
                form = $('form').filter(function() {
                    const inp = $(this).find('input[name="ubrn"]');
                    return inp.length && inp.val().trim() === ubrn;
                });
            }
            if (form.length) {
                form.submit();
            }
        }
        window.addEventListener('message', relayHandler);
    }
</script>
</body>
</html>
