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

$fee = $udata['ayushman_pdf_fee'] ?? 20;
checkServiceStatus($udata, 'ayushman_pdf_fee_status');

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

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

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

    $resdata = ayushman_verification_api_run([
        'aadhar'    => $aadhar,
        'stateCode' => $stateCode
    ]);


    if (!empty($resdata['error'])) {
        echo "<script>
            Swal.fire('Error','".addslashes($resdata['error'])."','error');
        </script>";
        exit;
    }


    if (($resdata['sampleCode'] ?? '') === "200") {

        // Wallet + Commission
        mysqli_query($tng_conn,"UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
        addCommission($tng_conn,$appliedby,$fee,$udata['parent'] ?? null,'Ayushman PMJAY');

        mysqli_query($tng_conn,"
            INSERT INTO wallethistory(userid,amount,balance,purpose,status,type)
            VALUES('$appliedby','$fee','$debit_fee','Ayushman PMJAY','1','Debit')
        ");

        $imageData = $resdata['image'] ?? '';

        

        mysqli_query($tng_conn,"
            INSERT INTO all_pdf_records
            (service_name,name,username,number,pdf,date)
            VALUES(
                'ayushman_card',
                '{$resdata['card_no']}',
                '$appliedby',
                '$aadhar',
                '".mysqli_real_escape_string($tng_conn,$imageData)."',
                NOW()
            )
        ");

        // Redirect to history
        echo "<script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'Ayushman Card saved successfully'
            }).then(()=>{
                window.location='all_history.php';
            });
        </script>";
        exit;
    }

    // ❌ Unexpected
    echo "<script>
        Swal.fire('Failed','Unexpected API response','error');
    </script>";
}
?>

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

<style>
body{
  background:linear-gradient(135deg,#a3cef1,#f6f9fc);
  font-family:'Poppins',sans-serif;
}
.card-glass{
  background:rgba(255,255,255,.75);
  backdrop-filter:blur(12px);
  border-radius:20px;
  box-shadow:0 10px 30px rgba(0,0,0,.15);
}
.btn-modern{border-radius:50px;font-weight:600}
</style>

<div class="page-wrapper">
<div class="page-content">
<div class="container py-5">

<div class="text-center mb-4">
  <h4 class="fw-bold text-primary">
    <i class="fa fa-id-card me-2"></i> Ayushman Card Finder
  </h4>
  <p class="text-muted mb-0">Find Ayushman PMJAY card using Aadhaar</p>
</div>

<div class="row justify-content-center">
<div class="col-lg-4">

<div class="card card-glass p-4">
<div class="alert alert-primary text-center fw-bold">
AYUSHMAN CARD – ALL STATES
</div>

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

<div class="mb-3">
<label>Select State</label>
<select name="stateCode" id="stateCode" class="form-select" required>
<option value="">Select State</option>
</select>
</div>

<div class="mb-3">
<label>Aadhaar Number</label>
<input type="text" name="aadhar" maxlength="12"
class="form-control" required>
</div>

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

<button type="submit" id="submitBtn"
class="btn btn-success btn-modern px-4">
Submit
</button>
</div>

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

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

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

<!-- ======================= STATES ======================= -->
<script>
document.addEventListener("DOMContentLoaded",()=>{
const states=[
["35","ANDAMAN AND NICOBAR ISLANDS"],["28","ANDHRA PRADESH"],["12","ARUNACHAL PRADESH"],
["18","ASSAM"],["10","BIHAR"],["4","CHANDIGARH"],["22","CHHATTISGARH"],
["7","DELHI"],["30","GOA"],["24","GUJARAT"],["6","HARYANA"],
["2","HIMACHAL PRADESH"],["20","JHARKHAND"],["29","KARNATAKA"],
["32","KERALA"],["23","MADHYA PRADESH"],["27","MAHARASHTRA"],
["3","PUNJAB"],["8","RAJASTHAN"],["33","TAMIL NADU"],
["36","TELANGANA"],["9","UTTAR PRADESH"],["5","UTTARAKHAND"]
];
const s=document.getElementById('stateCode');
states.forEach(i=>{
let o=document.createElement('option');
o.value=i[0]; o.textContent=i[1]; s.appendChild(o);
});
});
</script>

<!-- ======================= CONFIRM + DOUBLE SUBMIT BLOCK ======================= -->
<script>
let submitting = false;
document.getElementById('ayushmanForm').addEventListener('submit',function(e){
e.preventDefault();
if(submitting) return;

Swal.fire({
 title:'Are you sure?',
 text:'Ayushman Card fee will be deducted',
 icon:'question',
 showCancelButton:true,
 confirmButtonText:'Yes, Continue'
}).then(res=>{
 if(res.isConfirmed){
   submitting=true;
   document.getElementById('submitBtn').disabled=true;
   this.submit();
 }
});
});
</script>

<script src="../template/tngweb/assets/js/app.js"></script>
</html>
