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

$fee = $udata['aadhar_pvc_pdf_fee'] ?? 20;
checkServiceStatus($udata, 'aadhar_pvc_pdf_fee_status');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $type      = $_POST['type'];
    $password  = $_POST['password'];
    $phoneOpt  = $_POST['phone'];
    $appliedby = $udata['phone'];
    $balance   = $udata['balance'];
    $debit_fee = $balance - $fee;

   
    if ($balance < $fee) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire('Low Balance','Please Recharge Wallet','error');
            setTimeout(()=>{ window.location='wallet.php'; },1500);
        </script>";
        exit;
    }

   
    if (empty($_FILES['file']['name'])) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>Swal.fire('Error','Please upload UIDAI PDF','error');</script>";
        exit;
    }

    $fileMime = mime_content_type($_FILES['file']['tmp_name']);
    if ($fileMime !== 'application/pdf') {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>Swal.fire('Invalid File','Only PDF allowed','error');</script>";
        exit;
    }


    $uploadDir = __DIR__ . '/uploads/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $fileName = uniqid('aad_') . '.pdf';
    $uploadPath = $uploadDir . $fileName;

    if (!move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>Swal.fire('Upload Failed','Permission issue','error');</script>";
        exit;
    }

    $fileUrl = "https://" . $_SERVER['HTTP_HOST'] . "/admin/uploads/" . $fileName;

    /* ===============================
       API CALL
    ================================ */
    $resdata = downloadAadharPvcPdf(
        $fileUrl,
        $type,
        $phoneOpt,
        $password
    );

    if (($resdata['Message'] ?? '') === 'Failed') {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>Swal.fire('Error','".htmlspecialchars($resdata['error'])."','error');</script>";
        exit;
    }

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

        date_default_timezone_set('Asia/Kolkata');
        $timestamp = date("Y-m-d H:i:s");

    
        $parentPhone = $udata['parent'] ?? null;
        addCommission(
            $tng_conn,
            $appliedby,
            $fee,
            $parentPhone,
            "Aadhar PVC PDF"
        );


        mysqli_query(
            $tng_conn,
            "UPDATE users SET balance=balance-$fee WHERE phone='$appliedby'"
        );

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

      
        mysqli_query(
            $tng_conn,
            "INSERT INTO all_pdf_records
             (service_name,name,username,number,pdf,date)
             VALUES
             (
               'aadhar_pvc_pdf',
               '".mysqli_real_escape_string($tng_conn,$resdata['name'])."',
               '".$udata['phone']."',
               '".mysqli_real_escape_string($tng_conn,$resdata['aadhar'])."',
               '".mysqli_real_escape_string($tng_conn,$resdata['pdf'])."',
               '$timestamp'
             )"
        );

        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
          Swal.fire({
            icon:'success',
            title:'Success',
            text:'Aadhar PVC PDF Generated Successfully',
            timer:1500,
            showConfirmButton:false
          }).then(()=>{
            window.location='all_history.php';
          });
        </script>";
        exit;
    }
}
?>

<!-- ===============================
     LUXURY UI
================================ -->
<style>
.card-shine{
  border-radius:18px;
  box-shadow:0 15px 40px rgba(0,0,0,.18);
  transition:.3s;
}
.card-shine:hover{
  transform:translateY(-4px);
  box-shadow:0 26px 60px rgba(0,0,0,.35);
}
</style>

<div class="content-wrap">
<div class="main">
<div class="page-wrapper">
<div class="page-content d-flex justify-content-center">

<div class="col-lg-5 col-md-7 col-sm-9">
<div class="card card-shine">
<div class="card-body">

<a href="javascript:history.back()" class="btn btn-light w-100 mb-3">
← Go Back
</a>

<div class="alert alert-info text-center fw-bold">
AADHAR PVC CARD PDF
</div>

<form method="POST" enctype="multipart/form-data" id="aadharPvcForm">

<div class="mb-3">
<label>Password</label>
<input type="text" name="password" class="form-control" required>
</div>

<div class="mb-3">
<label>Upload UIDAI PDF</label>
<input type="file" name="file" accept=".pdf" class="form-control" required>
</div>

<div class="mb-3">
<label>PVC Type</label>
<select name="type" class="form-control" required>
  <option value="true">NEW PVC</option>
  <option value="false">OLD PVC</option>
</select>
</div>

<div class="mb-3">
<label>Show Phone Number</label>
<select name="phone" class="form-control" required>
  <option value="true">Yes</option>
  <option value="false">No</option>
</select>
</div>

<div class="mb-3">
<input class="form-control text-center fw-bold"
       value="Fee ₹ <?= $fee ?>" readonly>
</div>

<button class="btn btn-success w-100" id="submitBtn">
Generate PVC PDF
</button>

</form>

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

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

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

<!-- ===============================
     CONFIRM + DOUBLE SUBMIT
================================ -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("DOMContentLoaded",()=>{
 let submitted=false;
 const form=document.getElementById('aadharPvcForm');
 const btn=document.getElementById('submitBtn');

 form.addEventListener('submit',e=>{
   e.preventDefault();
   if(submitted) return;

   Swal.fire({
     title:'Confirm?',
     text:'PDF generate hogi aur wallet se fee deduct hogi',
     icon:'warning',
     showCancelButton:true,
     confirmButtonText:'Proceed',
     cancelButtonText:'Cancel'
   }).then(r=>{
     if(r.isConfirmed){
       submitted=true;
       btn.disabled=true;
       btn.innerText='Processing...';
       form.submit();
     }
   });
 });
});
</script>

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