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

$fee = $udata['rtps_pdf_fee'];
checkServiceStatus($udata, 'rtps_pdf_fee_status');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['appRefNum'], $_POST['name'])) {

    $appRefNum = trim($_POST['appRefNum']);
    $name      = ucwords(trim($_POST['name']));
    $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;
    }


    $request = [
        'appRefNum' => $appRefNum,
        'name'      => $name,
    ];

    $resdata = rtps_pdf_verification_api_run($request);

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

    elseif (($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,
            "Bihar RTPS Certificate 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',
              'Bihar RTPS Certificate PDF','1','Debit')"
        );

     
        mysqli_query(
            $tng_conn,
            "INSERT INTO all_pdf_records
             (service_name, name, username, number, pdf, date)
             VALUES
             (
               'bihar_rtps_pdf',
               '".mysqli_real_escape_string($tng_conn, $resdata['name'])."',
               '".$udata['phone']."',
               '".mysqli_real_escape_string($tng_conn, $resdata['appRefNum'])."',
               '".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:'RTPS Certificate PDF Generated Successfully',
                timer:1500,
                showConfirmButton:false
            }).then(()=>{
                window.location='all_history.php';
            });
        </script>";
    }
}
?>

<!-- ===============================
     SHINE UI
================================ -->
<style>
.card-shine{
  border-radius:16px;
  box-shadow:0 14px 35px rgba(0,0,0,.20);
  transition:.3s;
}
.card-shine:hover{
  transform:translateY(-4px);
  box-shadow:0 22px 48px rgba(0,0,0,.32);
}
</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 mb-3 w-100">
← Go Back
</a>

<div class="alert alert-danger text-center fw-bold">
BIHAR RTPS CERTIFICATE PDF
</div>

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

<div class="mb-3">
<label class="fw-semibold">Application Number</label>
<input type="text" name="appRefNum"
       class="form-control"
       placeholder="BCCCO/2025/XXXXX"
       required>
</div>

<div class="mb-3">
<label class="fw-semibold">Full Name</label>
<input type="text" name="name"
       class="form-control"
       placeholder="Enter Full Name"
       required>
</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 PDF
</button>

</form>

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

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

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

<!-- ===============================
     CONFIRM + DOUBLE SUBMIT SAFE
================================ -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {

let submitting = false;
const form = document.getElementById("rtpsForm");
const btn  = document.getElementById("submitBtn");

form.addEventListener("submit", function(e){
  e.preventDefault();
  if (submitting) return;

  Swal.fire({
    title: 'Are you sure?',
    text: 'PDF generate hogi aur wallet se fee deduct hogi',
    icon: 'warning',
    showCancelButton: true,
    confirmButtonText: 'Yes, Proceed',
    cancelButtonText: 'Cancel'
  }).then((result)=>{
    if(result.isConfirmed){
      submitting = 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>
