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

$fee = $udata['aadhar_to_ration_find_fee'];
checkServiceStatus($udata, 'aadhar_to_ration_find_fee_status');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !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:'Low Wallet Balance',
                text:'Please recharge wallet'
            }).then(()=>window.location='wallet.php');
        </script>";
        exit;
    }

    /* ===== API CALL ===== */
    $request = ['uid' => $aadhar];
    $resdata = uid_to_ration_details_verification_api_run($request);

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

    /* ❌ ERROR → ONLY SWAL */
    if (!empty($errorMsg)) {
        echo "<script>
            Swal.fire({
                icon:'error',
                title:'Failed',
                text:'".addslashes($errorMsg)."'
            });
        </script>";
    }

    /* ✅ SUCCESS */
    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 To Ration Details'
        );

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

       // ✅ Convert API response to BASE64 JSON
$base64Json = base64_encode(
    json_encode($resdata, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
);

// ✅ Save ONLY SUCCESS to history table
mysqli_query(
    $tng_conn,
    "INSERT INTO all_pdf_records
    (service_name, name, username, number, pdf, date)
    VALUES (
        'AADHAAR_TO_RATION',
        '".mysqli_real_escape_string($tng_conn, $resdata['rcId'] ?? 'RATION')."',
        '$appliedby',
        '$aadhar',
        '".mysqli_real_escape_string($tng_conn, $base64Json)."',
        NOW()
    )"
);


        // SUCCESS SWAL + REDIRECT
        echo "<script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'Ration details fetched 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 → Ration Details
</h4>

<div class="mb-3 text-start">
<a href="javascript:history.back()" class="btn btn-outline-primary btn-sm rounded-pill">
⬅️ Back
</a>
</div>

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

<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('rationForm').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>
