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


$price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='aadhar_print_pdf_a' "));
$fee = $price['price'] ?? "40";
$resdata = null;
$pdfData = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['aadhar']) && isset($_POST['bioenc'])) {
    $aadhar = $_POST['aadhar'];
    $bio = $_POST['bioenc'];
    $appliedby = $udata['phone'];
    $parentPhone = $udata['parent'] ?? null;
    $wallet = $udata['balance'];
    $debit_fee = $udata['balance'] - $fee;
    if ($wallet >= $fee) {
        $tng_url="$tng_apiurl/aadhar_org_verification";
        $curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => $tng_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => array(
        'bioenc' => $bio,
        'aadhar' => $aadhar,
        'apikey' => $tng_apikey
    ),
    CURLOPT_TIMEOUT => 30, 
    CURLOPT_CONNECTTIMEOUT => 30 
));

$response = curl_exec($curl);

        $resdata = json_decode($response, true) ?? '';
        $sampleCode = $resdata['sampleCode'] ?? '';
        $errore = $resdata['error'] ?? '';

        if ($errore) {
            echo '
            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
            <script>
                $(function(){
                    Swal.fire({
                        icon: "error",
                        title: "Error",
                        text: "' . $errore . '",
                        timer: 5000,
                        timerProgressBar: true
                    });
                    setTimeout(() => { window.location = ""; }, 5000);
                });
            </script>';
        } elseif ($resdata['sampleCode'] === "200") {
            date_default_timezone_set('Asia/Kolkata');
                $timestamp = date("Y-m-d H:i:s");
           $debit = mysqli_query($ahk_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
           $database = mysqli_query($ahk_conn, "INSERT INTO `aadhar_org_pdf`(`name`, `username`, `aadhar`, `token`, `date`) VALUES ('{$resdata['name']}','{$udata['phone']}','{$resdata['aadhar']}','{$resdata['token']}','$timestamp')");
           $updatehistory = mysqli_query($ahk_conn, "INSERT INTO `wallethistory`(`userid`, `amount`, `balance`, `purpose`, `status`, `type`) VALUES ('$appliedby','$fee','$debit_fee','Aadhar ORG  pDF','1','Debit')");
           addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "Aadhar Org Pdf Verification");
     echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({ icon: 'success', title: 'Success!', text: 'Pdf Generate Sucessfull Redirecting To List!', timer: 2000 });
            setTimeout(() => { window.location = 'aadhar_org_pdf_list.php'; }, 1200);
        </script>";
        }
    } else {
         echo '
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>
            $(function(){
                Swal.fire({
                    icon: "error",
                    title: "Wallet Balance is Low!",
                    text: "Please Recharge Now!",
                    timer: 2000,
                    timerProgressBar: true
                });
                setTimeout(() => { window.location = "wallet.php"; }, 1200);
            });
        </script>';
    }
}


// Step 2: When type is selected -> Download PDF API
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['type']) && isset($_POST['token'])) {
    $type = $_POST['type'];
    $token = $_POST['token'];

    $url = "$tng_apiurl/aadhar_org_pdf_downoad?token=$token&type=$type&apikey=$tng_apikey";

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
    ]);
    $resp = curl_exec($curl);
    curl_close($curl);

    $pdfResp = json_decode($resp, true);

    if ($pdfResp['Message'] === 'Success' && !empty($pdfResp['pdf'])) {
        $pdfData = $pdfResp['pdf']; // base64 pdf
    } else {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>Swal.fire({ icon:'error', title:'PDF Error', text:'Unable to generate PDF' });</script>";
    }
}
?>

<div class="content-wrap">
 <div class="main">
  <div class="page-wrapper">
   <div class="page-content">
    <div class="main-container">
     <div class="col-lg-12">
      <div class="card" style="margin:20px; padding:20px; box-shadow: 1px 5px 10px rgba(0,0,0,0.2)">
       <div class="card-body">
        <h4 class="mb-3">Aadhaar Bio Print </h4>

        <!-- Step 1 Form -->
        <form action="" method="POST" name="f1" class="row g-3">
          <input type="hidden" id="hdnPIDData" name="bioenc">
          <div class="form-group col-md-6">
              <label for="txtUID">Enter Aadhaar Number</label>
              <input type="text" name="aadhar" id="txtUID" class="form-control" maxlength="12" required>
          </div>
           <hr>
                                                                <div class="row mt-3">
                                                                  <div class="col-md-6">
                                                                       <input class="form-control" value="Fee ₹ <?php echo $fee; ?>" readonly>
                                                                   </div>
          <div class="col-md-12">
              <button type="button" id="capture" class="btn btn-primary">
                 <i class="fa fa-fingerprint"></i> Capture & Verify
              </button>
          </div>
        </form>

        <?php if($resdata && $resdata['Message']==='Success'){ ?>
        <hr>
        <h5>Details</h5>
        <table class="table table-bordered">
          <tr><th>Aadhaar</th><td><?php echo htmlspecialchars($resdata['aadhar']); ?></td></tr>
          <tr><th>Name</th><td><?php echo htmlspecialchars($resdata['name']); ?></td></tr>
        </table>

        <!-- Step 2: Type Selection -->
        <form method="POST" action="">
            <input type="hidden" name="token" value="<?php echo $resdata['token']; ?>">
            <div class="form-group col-md-6">
                <label for="type">Select Type</label>
                <select name="type" id="type" class="form-control" required>
                    <option value="">-- Select --</option>
                    <option value="e_print">E Print</option>
                    <option value="pvc_pdf">PVC PDF</option>
                    <option value="uid_pdf">UID PDF</option>
                </select>
            </div>
            <div class="col-md-12 mt-3">
                <button type="submit" class="btn btn-success">Download PDF</button>
            </div>
        </form>
        <?php } ?>

        <?php if($pdfData){ ?>
        <hr>
        <h5>Download</h5>
        <a href="<?php echo $pdfData; ?>" download="aadhaar.pdf" class="btn btn-success">Click to Download PDF</a>
        <iframe src="<?php echo $pdfData; ?>" style="width:100%;height:500px;" frameborder="0"></iframe>
        <?php } ?>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div>
 </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
    $("#capture").on('click', function () {
        var aadharVal = $("#txtUID").val().trim();
        if (aadharVal === '' || aadharVal.length !== 12 || isNaN(aadharVal)) {
            alert('Please enter valid 12 digit Aadhaar number');
            return;
        }
        var hdnPIDData = $("#hdnPIDData");
        var ssoauth_ver = $.now();
        $.getScript("<?php echo $tng_apiurl; ?>/printcapturepdf.js?v=" + ssoauth_ver)
            .done(function () {
                startCaptureRD(
                    { authType: "AUTH", fpDevice: "bio", env: "P", isHttpsService: "false" },
                    function (data) {
                        hdnPIDData.val(data.data);
                        document.f1.submit();
                    }
                );
            });
    });
});
</script>
<?php include('../template/ahkweb/footer.php'); ?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
</html>
