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

$fee = $udata['uid_to_mask_pan_fee'];
checkServiceStatus($udata, 'uid_to_mask_pan_fee_status');

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

if (!empty($_POST['aadhar'])) {

    $aadhar    = trim($_POST['aadhar']);
    $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];
    $resdata = aadhar_to_pan_mask_verification_api_run($request);

    $sampleCode = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['error'] ?? '';

    /* ❌ ERROR CASE → ONLY SWAL */
    if (!empty($errorMsg)) {
        echo "<script>
            Swal.fire({
                icon:'error',
                title:'Error',
                text:'".addslashes($errorMsg)."'
            });
        </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,
            'UID To Mask PAN'
        );

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

        // SAVE SUCCESS RESPONSE
        mysqli_query(
            $tng_conn,
            "INSERT INTO all_pdf_records
            (service_name,name,username,number,pdf,date)
            VALUES(
                'UID_TO_MASK_PAN',
                '".mysqli_real_escape_string($tng_conn,$resdata['pan_no'] ?? 'MASK PAN')."',
                '$appliedby',
                '$aadhar',
                '".mysqli_real_escape_string($tng_conn,json_encode($resdata))."',
                NOW()
            )"
        );

        // ✅ SUCCESS SWAL + REDIRECT
        echo "<script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'Mask PAN Found 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 p-4 col-lg-6 col-md-8">
<h4 class="text-center fw-bold text-primary mb-4">
🔐 Aadhaar → Mask PAN
</h4>

<form method="POST" id="maskPanForm">

<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="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>

</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('maskPanForm').submit();
        }
    });
});
</script>

<style>
body{background:#f4f6fb}

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