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

$fee = $udata['aadhar_validation_fee'];
checkServiceStatus($udata, 'aadhar_validation_fee_status');

$resdata = [];
$sampleCode = '';

$captchaData = fetchAadharCaptcha();

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

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

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

    /* ===== WALLET CHECK ===== */
    if ($wallet < $fee) {
        echo "<script>
            Swal.fire({
                icon:'error',
                title:'Wallet Low',
                text:'Please recharge wallet'
            }).then(()=>window.location='wallet.php');
        </script>";
        exit;
    }

    /* ===== API CALL ===== */
    $request = [
        'aadhar'     => $aadhar,
        'captcha'    => $captcha,
        'captchaSID' => $captchaSID
    ];

    $resdata    = aadhar_validation_api_run($request);
    $sampleCode = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['error'] ?? '';

    /* ❌ ERROR CASE */
    if (!empty($errorMsg) || ($resdata['Message'] ?? '') === 'Failed') {
        echo "<script>
            Swal.fire({
                icon:'error',
                title:'Error',
                text:'".addslashes($errorMsg ?: 'Captcha verification failed')."'
            });
        </script>";
    }

    /* ✅ SUCCESS CASE */
    if ($sampleCode === "200") {

        // Wallet Deduct
        mysqli_query(
            $tng_conn,
            "UPDATE users SET balance = balance - $fee WHERE phone='$appliedby'"
        );

        // Commission
        addCommission(
            $tng_conn,
            $appliedby,
            $fee,
            $udata['parent'] ?? null,
            'Aadhaar Validation'
        );

        // Wallet History
        mysqli_query(
            $tng_conn,
            "INSERT INTO wallethistory
            (userid,amount,balance,purpose,status,type)
            VALUES(
                '$appliedby',
                '$fee',
                '$debit_fee',
                'Aadhaar Validation',
                '1',
                'Debit'
            )"
        );

        // ✅ BASE64 JSON SAVE
        $base64Json = 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_VALIDATION',
                '".mysqli_real_escape_string($tng_conn,$resdata['aadhar'] ?? 'AADHAAR')."',
                '$appliedby',
                '$aadhar',
                '".mysqli_real_escape_string($tng_conn,$base64Json)."',
                NOW()
            )"
        );

        echo "<script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'Aadhaar validated successfully',
                timer:2500,
                showConfirmButton:false
            }).then(()=>{
                window.location='all_history.php';
            });
        </script>";
        exit;
    }
}
?>

<!-- ================= UI ================= -->

<div class="page-wrapper">
<div class="page-content">
<div class="container d-flex justify-content-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"
placeholder="Enter 12 digit Aadhaar">
</div>

<div class="mb-3">
<label class="fw-semibold">Enter Captcha</label><br>
<img src="<?= $captchaData['captcha'] ?? '' ?>" alt="Captcha" class="mb-2">
<input type="text"
name="captcha"
required
class="form-control"
placeholder="Enter Captcha">
<input type="hidden" name="captchaSID" value="<?= $captchaData['captchaTxnId'] ?? '' ?>">
</div>

<div class="d-flex justify-content-between align-items-center mt-4">
<input class="form-control w-50 text-center fw-bold"
value="Fee ₹ <?= $fee ?>" readonly>

<button type="button"
id="submitBtn"
class="btn btn-success rounded-pill px-4">
<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">
⬅️ Back
</a>
</div>

</form>
</div>

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

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

<!-- ================= JS ================= -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
let isSubmitting = false;

document.getElementById('submitBtn').addEventListener('click', function(){

    if(isSubmitting) return;

    Swal.fire({
        title:'Are you sure?',
        text:'Wallet balance will be deducted',
        icon:'question',
        showCancelButton:true,
        confirmButtonText:'Yes, Continue',
        cancelButtonText:'Cancel'
    }).then((res)=>{
        if(res.isConfirmed){
            isSubmitting = true;
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('aadhaarForm').submit();
        }
    });
});
</script>

<style>
body{background:#f4f6fb}

.luxury-card{
  border-radius:20px;
  background:linear-gradient(145deg,#ffffff,#eef2ff);
  box-shadow:0 25px 50px rgba(0,0,0,.12);
}
</style>
