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


$baseFee = isset($udata['dl_pdf_fee']) ? (int)$udata['dl_pdf_fee'] : 30;
$fee     = $baseFee + 5;

checkServiceStatus($udata, 'dl_pdf_fee_status');

if (isset($_POST['dl_number'], $_POST['dltype'])) {

    $dl_number = trim($_POST['dl_number']);
    $dltype    = trim($_POST['dltype']);
    $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 = [
        'dl_number' => $dl_number,
        'dltype'    => $dltype
    ];

    $resdata = dl_pdf_only_number_api_run($request);


    if (($resdata['Message'] ?? '') === 'Failed') {
        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,
            "DL PDF Only Number (Type $dltype)"
        );

      
        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',
              'DL PDF Only Number (Type $dltype)','1','Debit')"
        );

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

        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'DL 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 36px rgba(0,0,0,.22);
  transition:.3s;
}
.card-shine:hover{
  transform:translateY(-4px);
  box-shadow:0 22px 50px rgba(0,0,0,.35);
}
.btn-shine{
  background:linear-gradient(45deg,#1f618d,#2874a6,#3498db);
  border:none;
  color:#fff;
  font-weight:600;
}
</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-4 col-md-6 col-sm-8">
<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-info text-center fw-bold">
DL PDF (Only DL Number)
</div>

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

<div class="mb-3">
<label class="fw-semibold">Enter DL Number</label>
<input type="text"
       name="dl_number"
       class="form-control"
       placeholder="Enter DL Number"
       required>
</div>

<div class="mb-3">
<label class="fw-semibold">Select DL Type</label>
<select name="dltype" class="form-control" required>
  <option value="">Select DL Type</option>
  <option value="1">Without Chip</option>
  <option value="2">Chip</option>
  <option value="3">Without Chip New</option>
  <option value="4">Without Chip New Blue</option>
</select>
</div>

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

<button class="btn btn-shine 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("dlOnlyForm");
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>
