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

/* --- Internal Functions (Updated with apiKey) --- */
function get_page_captcha($apikey, $apiurl) {
    // API request me 'apiKey' (K capital) use kiya gaya hai
    $params = http_build_query(['apiKey' => $apikey]);
    $res = http_get("https://$apiurl/api/v1/eid/captcha?$params");
    return json_decode($res, true) ?? [];
}

function verify_page_aadhaar($request, $apikey, $apiurl) {
    // API parameters ko documentation ke hisab se set kiya gaya hai
    $params = http_build_query([
        'apiKey'       => $apikey, // Capital K
        'uidNumber'    => $request['aadhar'],     
        'imgcaptcha'   => $request['captcha'],    
        'captchaTxnId' => $request['captchaSID'], 
    ]);
    $res = http_get("https://$apiurl/api/v1/eid/verifyUid?$params");
    return json_decode($res, true) ?? [];
}

/* --- Variables & Config --- */
$tng_apikey = JkL_get('TheNextGenAPI', 'tng_apikey');
$tng_apiurl = JkL_get('TheNextGenAPI', 'tng_apiurl');
$fee = $udata['aadhar_validation_fee'] ?? 0;

$resdata = [];
$showResult = false;

// Load Captcha on page load
$captchaData = get_page_captcha($tng_apikey, $tng_apiurl);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['aadhar'])) {

    $aadhar      = trim($_POST['aadhar']);
    $captcha     = trim($_POST['captcha']);
    $captchaSID  = trim($_POST['captchaSID']);

    $appliedby  = $udata['phone'];
    $wallet     = $udata['balance'];
    $debit_fee  = $wallet - $fee;

    if ($wallet < $fee) {
        echo "<script>Swal.fire('Error','Wallet Low','error').then(()=>window.location='wallet.php');</script>";
    } else {
        
        $api_req = ['aadhar' => $aadhar, 'captcha' => $captcha, 'captchaSID' => $captchaSID];
        $resdata = verify_page_aadhaar($api_req, $tng_apikey, $tng_apiurl);
        
        // Status 100 check for Success
        if (isset($resdata['status']) && $resdata['status'] == '100') {
            $showResult = true;

            // 1. Balance Update
            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', '$debit_fee', 'Aadhaar Validation', '1', 'Debit')");

            // 3. Save Record
            $base64Json = base64_encode(json_encode($resdata, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $uName = mysqli_real_escape_string($tng_conn, $resdata['uidNumber'] ?? 'AADHAAR');
            mysqli_query($tng_conn, "INSERT INTO all_pdf_records (service_name,name,username,number,pdf,date) 
                VALUES('AADHAAR_VALIDATION', '$uName', '$appliedby', '$aadhar', '$base64Json', NOW())");

            echo "<script>Swal.fire('Success','Aadhaar Validated','success');</script>";
        } else {
            // Agar fail hua to error dikhayega
            $err = $resdata['error'] ?? 'Invalid Captcha or Server Error';
            echo "<script>Swal.fire('Error','".addslashes($err)."','error');</script>";
        }
    }
}
?>

<div class="page-wrapper">
    <div class="page-content">
        <div class="container d-flex flex-column align-items-center">

            <div class="card luxury-card col-lg-6 col-md-8 p-4">
                <h4 class="text-center fw-bold text-primary mb-4">🆔 Aadhaar Validation (Captcha)</h4>

                <form method="POST" id="aadhaarForm">
                    <div class="mb-3">
                        <label class="fw-semibold">Enter Aadhaar Number</label>
                        <input type="text" name="aadhar" maxlength="12" minlength="12" required class="form-control text-center fw-bold" placeholder="Enter 12 digit Aadhaar" autocomplete="off">
                    </div>

                    <div class="mb-3">
                        <label class="fw-semibold">Enter Captcha</label><br>
                        <div class="text-center bg-light p-2 mb-2 rounded border">
                            <?php if(!empty($captchaData['captchaBase64String'])): ?>
                                <img src="<?= $captchaData['captchaBase64String'] ?>" alt="Captcha" style="max-height:65px;">
                            <?php else: ?>
                                <span class="text-danger small">Captcha not loading...</span>
                            <?php endif; ?>
                        </div>
                        <input type="text" name="captcha" required class="form-control text-center fw-bold" placeholder="Type Captcha Here" autocomplete="off">
                        <input type="hidden" name="captchaSID" value="<?= $captchaData['captchaTxnId'] ?? '' ?>">
                    </div>

                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <div class="input-group w-50 pe-2">
                            <span class="input-group-text bg-primary text-white">₹</span>
                            <input class="form-control text-center fw-bold" value="<?= $fee ?>" readonly>
                        </div>
                        <button type="button" id="submitBtn" class="btn btn-success rounded-pill px-4 flex-fill">
                            <i class="fa fa-check-circle me-1"></i> Submit
                        </button>
                    </div>

                    <div class="text-center mt-3">
                        <a href="javascript:history.back()" class="text-decoration-none text-muted">⬅️ Back to Dashboard</a>
                    </div>
                </form>
            </div>

            <?php if ($showResult): ?>
            <div class="card luxury-card col-lg-6 col-md-8 mt-4 p-0 overflow-hidden border-success">
                <div class="bg-success text-white p-3 text-center fw-bold shadow-sm">
                    <i class="fa fa-user-check me-2"></i>Verification Successful
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <tbody>
                            <tr><td class="ps-4"><strong>UID Number</strong></td><td><?= htmlspecialchars($resdata['uidNumber'] ?? 'N/A'); ?></td></tr>
                            <tr><td class="ps-4"><strong>Location/State</strong></td><td><?= htmlspecialchars($resdata['address'] ?? 'N/A'); ?></td></tr>
                            <tr><td class="ps-4"><strong>Age Band</strong></td><td><?= htmlspecialchars($resdata['ageBand'] ?? 'N/A'); ?></td></tr>
                            <tr><td class="ps-4"><strong>Gender</strong></td><td><?= htmlspecialchars($resdata['gender'] ?? 'N/A'); ?></td></tr>
                            <tr><td class="ps-4"><strong>Mobile Status</strong></td><td><span class="badge bg-primary px-3 py-2"><?= htmlspecialchars($resdata['maskedMobileNumber'] ?? 'N/A'); ?></span></td></tr>
                            <tr><td class="ps-4"><strong>Remark</strong></td><td class="text-success fw-bold"><?= htmlspecialchars($resdata['uidMessage'] ?? 'Active'); ?></td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

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

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let isSubmitting = false;
document.getElementById('submitBtn').addEventListener('click', function(){
    if(isSubmitting) return;

    // Aadhaar length validation
    let aadhaarVal = document.getElementsByName('aadhar')[0].value;
    if(aadhaarVal.length !== 12){
        Swal.fire('Error','Please enter a valid 12-digit Aadhaar number','error');
        return;
    }

    Swal.fire({
        title:'Confirm Transaction?',
        text:'₹<?= $fee ?> will be deducted from your wallet.',
        icon:'warning',
        showCancelButton:true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#d33',
        confirmButtonText:'Confirm & Pay',
        cancelButtonText:'Cancel'
    }).then((res)=>{
        if(res.isConfirmed){
            isSubmitting = true;
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('submitBtn').innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';
            document.getElementById('aadhaarForm').submit();
        }
    });
});
</script>

<style>
body { background: #f4f6fb; }
.luxury-card {
    border-radius: 20px;
    background: #ffffff;
    box-shadow: 0 15px 35px rgba(0,0,0,0.1);
    border: none;
    transition: 0.3s;
}
.form-control {
    border-radius: 10px;
    padding: 10px;
    border: 1px solid #ced4da;
}
.form-control:focus {
    box-shadow: 0 0 10px rgba(13, 110, 253, 0.2);
    border-color: #0d6efd;
}
.table td { padding: 15px 20px; vertical-align: middle; border-bottom: 1px solid #f8f9fa; }
.badge { font-weight: 500; border-radius: 8px; }
</style>