<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');
$fee    = $udata['aadhar_print_pdf_a'] ?? 40;
checkServiceStatus($udata, 'aadhar_print_pdf_a_status');
$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) {
       $resdata = callAadharOrgApi($_POST['bioenc'], $_POST['aadhar']);
        $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($tng_conn, "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'");
           $database = mysqli_query($tng_conn, "INSERT INTO `aadhar_org_pdf`(`name`, `username`, `aadhar`, `token`, `date`) VALUES ('{$resdata['name']}','{$udata['phone']}','{$resdata['aadhar']}','{$resdata['token']}','$timestamp')");
           $updatehistory = mysqli_query($tng_conn, "INSERT INTO `wallethistory`(`userid`, `amount`, `balance`, `purpose`, `status`, `type`) VALUES ('$appliedby','$fee','$debit_fee','Aadhar ORG  pDF','1','Debit')");
           addCommission($tng_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>';
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['type']) && isset($_POST['token'])) {
      $type = $_POST['type'];
      $token = $_POST['token'];
      $pdfResp = downloadAadharOrgPdf($token, $type);

    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">
           <div class="mb-4">
        <a href="javascript:history.back()" class="back-btn">
            <i class="bi bi-arrow-left-circle"></i> Go Back
        </a>
    </div>
        <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();

        // Validate 12-digit Aadhaar
        if (aadharVal === '' || aadharVal.length !== 12 || isNaN(aadharVal)) {
            alert('Please enter valid 12 digit Aadhaar number');
            return;
        }

        var hdnPIDData = $("#hdnPIDData");
        var ssoauth_ver = $.now();

        
        var tngUrl = "<?php echo 'https://' . JkL_get('TheNextGenAPI','tng_apiurl'); ?>";

        $.getScript(tngUrl + "/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();
                    }
                );
            })
            .fail(function () {
                alert('Failed to load fingerprint capture script. Please try again.');
            });
    });
});
</script>

<?php include('../template/tngweb/footer.php'); ?>
<script src="../template/tngweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/tngweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/tngweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/tngweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>
</html>
