<?php
header('Content-Type: text/html; charset=utf-8');
include __DIR__ . '/includes/header.php';

$selected_service = $_GET['service'] ?? 'br';
if ($selected_service !== 'dr') {
    $selected_service = 'br';
}
?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-7">
            <div class="card shadow-lg border-0" style="border-radius: 16px; overflow: hidden; background: #fff;">
                <div class="card-header py-4 text-center text-white" style="background: linear-gradient(135deg, #1e40af, #2563eb);">
                    <h4 class="mb-1 font-weight-bold"><i class="fas fa-print me-2"></i>আবেদনপত্র প্রিন্ট করুন</h4>
                    <p class="mb-0 text-white-50" style="font-size: 0.9rem;">Application Print Service</p>
                </div>
                <div class="card-body p-4 p-md-5">
                    
                    <div id="alertBox" class="alert alert-danger d-none rounded-3 align-items-center" role="alert">
                        <i class="fas fa-exclamation-circle me-2 fs-5"></i>
                        <div id="alertText">Error message here.</div>
                    </div>

                    <form id="printForm" onsubmit="event.preventDefault(); processPrint();">
                        <div class="mb-4">
                            <label class="form-label fw-bold text-secondary d-block">আবেদনের ধরণ (Application Type):</label>
                            <div class="btn-group w-100" role="group" aria-label="Service type selection">
                                <input type="radio" class="btn-check" name="service" id="serviceBr" value="br" <?php echo $selected_service === 'br' ? 'checked' : ''; ?> autocomplete="off">
                                <label class="btn btn-outline-primary fw-bold py-2.5" for="serviceBr">
                                    <i class="fas fa-baby me-2"></i>জন্ম নিবন্ধন
                                </label>
                                
                                <input type="radio" class="btn-check" name="service" id="serviceDr" value="dr" <?php echo $selected_service === 'dr' ? 'checked' : ''; ?> autocomplete="off">
                                <label class="btn btn-outline-danger fw-bold py-2.5" for="serviceDr">
                                    <i class="fas fa-bed me-2"></i>মৃত্যু নিবন্ধন
                                </label>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label for="appInput" class="form-label fw-bold text-secondary">আবেদনপত্র নম্বর (Application ID):</label>
                            <div class="input-group input-group-lg shadow-sm" style="border-radius: 10px; overflow: hidden;">
                                <span class="input-group-text bg-light border-end-0 text-muted"><i class="fas fa-file-invoice"></i></span>
                                <input type="text" class="form-control form-control-lg border-start-0 fs-5" id="appInput" 
                                       placeholder="যেমন: 261870138" required 
                                       oninput="this.value=this.value.replace(/[^0-9]/g,'')">
                            </div>
                        </div>

                        <div class="mb-4">
                            <label for="dobInput" class="form-label fw-bold text-secondary">জন্ম তারিখ (Date of Birth):</label>
                            <div class="input-group input-group-lg shadow-sm" style="border-radius: 10px; overflow: hidden;">
                                <span class="input-group-text bg-light border-end-0 text-muted"><i class="fas fa-calendar-alt"></i></span>
                                <input type="text" class="form-control form-control-lg border-start-0 fs-5" id="dobInput" placeholder="dd/mm/yyyy" required>
                            </div>
                        </div>

                        <div class="d-grid mt-4">
                            <button class="btn btn-primary btn-lg fw-bold py-3 shadow-sm" type="submit" id="searchBtn" style="border-radius: 10px; background: linear-gradient(135deg, #1e40af, #2563eb); border: none; transition: transform 0.2s, box-shadow 0.2s;">
                                <i class="fas fa-search me-2"></i>খুঁজুন ও প্রিন্ট করুন
                            </button>
                        </div>
                    </form>

                    <!-- Loader & Status -->
                    <div id="statusMessage" class="text-center mt-4" style="display: none;">
                        <div class="spinner-border text-primary" role="status" style="width: 2.5rem; height: 2.5rem;">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                        <p class="mt-3 text-secondary fw-bold fs-5" id="statusText">আবেদন খোঁজা হচ্ছে, দয়া করে অপেক্ষা করুন...</p>
                        
                        <!-- Relay Trigger UI -->
                        <div id="relayContainer" class="mt-4 p-3 bg-light rounded-3 d-none border">
                            <p class="text-danger fw-bold mb-2">BDRIS সার্ভার কানেকশন ব্লক করছে অথবা আবেদন পাওয়া যায়নি!</p>
                            <p class="text-muted small">নিচের বাটনটিতে ক্লিক করে ব্রাউজার রিলে দিয়ে তথ্য ফেস করুন।</p>
                            <button id="relayBtn" class="btn btn-success fw-bold px-4 py-2" onclick="triggerRelay()">
                                <i class="fas fa-external-link-alt me-2"></i>ব্রাউজার রিলে দিয়ে লোড করুন
                            </button>
                        </div>
                    </div>

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

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let currentAppId = "";
let currentDob = "";

function showAlert(msg, isWarning = false) {
    let alertBox = document.getElementById("alertBox");
    let alertText = document.getElementById("alertText");
    alertBox.classList.remove("d-none", "alert-danger", "alert-warning");
    alertBox.classList.add("d-flex", isWarning ? "alert-warning" : "alert-danger");
    alertText.innerHTML = msg;
}

function hideAlert() {
    document.getElementById("alertBox").classList.add("d-none");
    document.getElementById("alertBox").classList.remove("d-flex");
}

function processPrint() {
    hideAlert();
    let appId = document.getElementById("appInput").value.trim();
    let dob = document.getElementById("dobInput").value.trim();
    let service = document.querySelector('input[name="service"]:checked').value;

    if (!appId || !dob) {
        showAlert("অনুগ্রহ করে আবেদন নম্বর এবং জন্ম তারিখ সঠিকভাবে প্রদান করুন।");
        return;
    }

    currentAppId = appId;
    currentDob = dob;

    let statusDiv = document.getElementById("statusMessage");
    let statusText = document.getElementById("statusText");
    let btn = document.getElementById("searchBtn");
    let relayContainer = document.getElementById("relayContainer");
    
    btn.disabled = true;
    statusDiv.style.display = "block";
    relayContainer.classList.add("d-none");
    statusText.innerHTML = "সার্ভার থেকে আবেদন খোঁজা হচ্ছে...";

    $.ajax({
        url: 'proxy_list.php',
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'resolve_encrypted',
            appId: appId,
            dob: dob,
            service: service,
            csrfToken: '',
            officeId: ''
        }
    }).done(function(resp) {
        if (resp && resp.encryptedId) {
            statusText.innerText = "আবেদন পাওয়া গেছে! প্রিন্ট পেজ ওপেন হচ্ছে...";
            setTimeout(function() {
                statusDiv.style.display = "none";
                btn.disabled = false;
                window.open("print-official.php?type=app&data=" + encodeURIComponent(resp.encryptedId), "_blank");
            }, 1000);
        } else if (resp && resp.error === 'dob_mismatch') {
            statusDiv.style.display = "none";
            btn.disabled = false;
            showAlert("❌ " + resp.message + " (প্রদত্ত জন্ম তারিখ মেলেনি।)");
        } else {
            // Not found or blocked by WAF
            statusText.innerText = "আবেদন সরাসরি পাওয়া যায়নি।";
            btn.disabled = false;
            relayContainer.classList.remove("d-none");
        }
    }).fail(function(jqXHR) {
        statusText.innerText = "সার্ভারে যোগাযোগ করা যায়নি।";
        btn.disabled = false;
        relayContainer.classList.remove("d-none");
    });
}

function triggerRelay() {
    if (!currentAppId) return;
    let service = document.querySelector('input[name="service"]:checked').value;
    const w = 800;
    const h = 600;
    const left = (screen.width - w) / 2;
    const top = (screen.height - h) / 2;
    const relayUrl = "bdris-relay.php?type=app_id&key=" + encodeURIComponent(currentAppId) + "&service=" + encodeURIComponent(service);
    window.open(relayUrl, "BDRISRelay", `width=${w},height=${h},top=${top},left=${left}`);
}

// Listen for message events from bdris-relay.php
window.addEventListener('message', function(e) {
    if (e.data && e.data.type === 'bdris_result') {
        if (String(e.data.key) === String(currentAppId)) {
            // Relayed data is now cached. Re-run search
            document.getElementById("statusText").innerHTML = "<span class='text-success'>রিলে সম্পূর্ণ! ডাটা পুনরায় প্রসেস করা হচ্ছে...</span>";
            setTimeout(processPrint, 1000);
        }
    }
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
