<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');

/* ---------------------------------------------------------
   1. API CONFIGURATION (TheNextGen / ApiNexus)
   ---------------------------------------------------------
*/
$tng_apikey = JkL_get('TheNextGenAPI', 'tng_apikey');
$tng_apiurl = JkL_get('TheNextGenAPI', 'tng_apiurl');
$fee = $udata['enrollment_status_fee'] ?? 0;

$resdata = [];
$showResult = false;

/* ---------------------------------------------------------
   2. FETCH CAPTCHA (Using apiKey)
   ---------------------------------------------------------
*/
$captcha_params = http_build_query(['apiKey' => $tng_apikey]);
$captcha_json = http_get("https://$tng_apiurl/api/v1/eid/captcha?$captcha_params");
$captchaData = json_decode($captcha_json, true) ?? [];

/* ---------------------------------------------------------
   3. FORM PROCESSING
   ---------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_btn'])) {
    
    $eidNumber   = trim($_POST['eidNumber']);
    $imgcaptcha  = trim($_POST['imgcaptcha']);
    $captchaID   = trim($_POST['captchaID']);

    $appliedby   = $udata['phone'];
    $old_balance = $udata['balance'];
    $new_balance = $old_balance - $fee;

    // A. Wallet Check
    if ($old_balance < $fee) {
        echo "<script>Swal.fire('Error', 'Insufficient Balance!', 'error');</script>";
    } else {
        
        // B. API Call for Enrollment Status (EID)
        $verify_params = http_build_query([
            'apiKey'       => $tng_apikey,
            'eidNumber'    => $eidNumber,
            'imgcaptcha'   => $imgcaptcha,
            'captchaTxnId' => $captchaID,
        ]);

        $verify_json = http_get("https://$tng_apiurl/api/v1/eid/verifyEid?$verify_params");
        $resdata = json_decode($verify_json, true) ?? [];

        // C. Result Handling (Status 100 = Success)
        if (isset($resdata['status']) && $resdata['status'] == '100') {
            $showResult = true;

            // 1. Update Balance
            mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone = '$appliedby'");

            // 2. Wallet History
            mysqli_query($tng_conn, "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
                VALUES ('$appliedby', '$fee', '$new_balance', 'Aadhaar EID Status', '1', 'Debit')");

            // 3. Save Record
            $pdf_json = base64_encode(json_encode($resdata, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
            mysqli_query($tng_conn, "INSERT INTO all_pdf_records (service_name, name, username, number, pdf, date) 
                VALUES ('AADHAAR_EID_STATUS', 'EID STATUS', '$appliedby', '$eidNumber', '$pdf_json', NOW())");

            echo "<script>Swal.fire('Success', 'Status Checked Successfully', 'success');</script>";
        } else {
            $msg = $resdata['error'] ?? 'Invalid Captcha or API Error';
            echo "<script>Swal.fire('Error', '".addslashes($msg)."', 'error');</script>";
        }
    }
}
?>

<style>
    body { background: linear-gradient(135deg,#eef2ff,#f9fafb); }
    .lux-card {
        background: rgba(255,255,255,.92);
        backdrop-filter: blur(18px);
        border-radius: 22px;
        box-shadow: 0 25px 50px rgba(0,0,0,.12);
        padding: 30px;
        border: none;
    }
    .title { font-weight: 700; color: #4338ca; }
    .back-btn { font-weight: 600; text-decoration: none; }
    .form-control-lg { border-radius: 12px; font-size: 1rem; border: 2px solid #e5e7eb; }
    .form-control-lg:focus { border-color: #4338ca; box-shadow: none; }
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="container">
            <div class="row justify-content-center align-items-center" style="min-height:80vh;">
                
                <div class="col-lg-5 col-md-7">
                    <div class="lux-card">
                        <div class="mb-3">
                            <a href="javascript:history.back()" class="back-btn text-primary">
                                <i class="fa fa-arrow-left"></i> Back
                            </a>
                        </div>

                        <h4 class="title text-center mb-2">🆔 Enrollment Status</h4>
                        <p class="text-muted text-center mb-4 small">Check Aadhaar Status using 28-digit EID</p>

                        <form method="POST" id="eidForm">
                            <div class="mb-3">
                                <label class="fw-semibold mb-1">Enrollment ID (EID)</label>
                                <input type="text" name="eidNumber" class="form-control form-control-lg text-center" 
                                       placeholder="2754***********YYYYMMDDHHMMSS" maxlength="28" required>
                            </div>

                            <div class="mb-3 text-center">
                                <label class="fw-semibold d-block text-start mb-1">Captcha</label>
                                <?php if(!empty($captchaData['captchaBase64String'])): ?>
                                    <div class="bg-light p-2 rounded mb-2 border">
                                        <img src="<?= $captchaData['captchaBase64String'] ?>" class="img-fluid" style="max-height: 60px;">
                                    </div>
                                <?php endif; ?>
                                <input type="text" name="imgcaptcha" class="form-control text-center" placeholder="Enter Captcha Code" required autocomplete="off">
                                <input type="hidden" name="captchaID" value="<?= $captchaData['captchaTxnId'] ?? '' ?>">
                            </div>

                            <div class="row align-items-center mt-4">
                                <div class="col-6">
                                    <span class="badge bg-soft-success text-success p-2 w-100 border border-success">Fee: ₹<?= $fee ?></span>
                                </div>
                                <div class="col-6 text-end">
                                    <button type="submit" name="submit_btn" id="submitBtn" class="btn btn-primary px-4 rounded-pill w-100 shadow">
                                        Check Now
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <?php if ($showResult): ?>
                <div class="col-lg-6 col-md-7 mt-4 mt-lg-0">
                    <div class="lux-card border-top border-4 border-success">
                        <h5 class="fw-bold text-success mb-3"><i class="fa fa-check-circle"></i> Status Found</h5>
                        <div class="table-responsive">
                            <table class="table table-borderless">
                                <tbody>
                                    <tr class="border-bottom">
                                        <td class="text-muted py-3">Enrollment No:</td>
                                        <td class="fw-bold py-3 text-end"><?= htmlspecialchars($resdata['eid'] ?? $eidNumber); ?></td>
                                    </tr>
                                    <tr>
                                        <td class="text-muted py-3">Current Status:</td>
                                        <td class="fw-bold py-3 text-end text-primary"><?= htmlspecialchars($resdata['uidMessage'] ?? 'N/A'); ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="alert alert-info small mt-2 mb-0">
                            <i class="fa fa-info-circle"></i> This record has been saved to your history.
                        </div>
                    </div>
                </div>
                <?php endif; ?>

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let isSubmitting = false;
document.getElementById('eidForm').addEventListener('submit', function(e) {
    if(isSubmitting) return;
    
    e.preventDefault();
    let eid = document.getElementsByName('eidNumber')[0].value;
    
    if(eid.length !== 28) {
        Swal.fire('Error', 'EID must be exactly 28 digits long', 'error');
        return;
    }

    Swal.fire({
        title: 'Confirm Request?',
        text: 'Proceed to check status for EID: ' + eid,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Check',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            isSubmitting = true;
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('submitBtn').innerHTML = '<i class="fa fa-spinner fa-spin"></i> Loading...';
            this.submit();
        }
    });
});
</script>

<?php include('../template/tngweb/footer.php'); ?>