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

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

checkServiceStatus($udata, 'dl_pdf_fee_status');

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

    $dl_number = trim($_POST['dl_number']);
    $dob       = trim($_POST['dob']);
    $dltype    = $_POST['dltype'];

    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;

    if ($udata['balance'] >= $fee) {

     
        $request = [
            'dl_number' => $dl_number,
            'dob'       => $dob,
            'dltype'    => $dltype,
        ];

        $resdata = dl_pdf_verification_v1_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 Verification"
            );

        
            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 Verification','1','Debit')"
            );

           
            mysqli_query(
                $tng_conn,
                "INSERT INTO all_pdf_records
                 (service_name, name, username, number, pdf, date)
                 VALUES
                 (
                    'dl_pdf',
                    '".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>";
        }

    } else {
        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>";
    }
}
?>


<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
.card-shine{
  border-radius:16px;
  box-shadow:0 12px 32px rgba(0,0,0,.18);
  transition:.3s;
}
.card-shine:hover{
  transform:translateY(-4px);
  box-shadow:0 20px 45px rgba(0,0,0,.3);
}
</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 Verification
</div>

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

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

<div class="mb-3">
<label>Date of Birth (DD-MM-YYYY)</label>
<input type="text" name="dob" class="form-control"
       placeholder="DD-MM-YYYY" required>
</div>

<div class="mb-3">
<label>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>
</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 PDF
</button>

</form>

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

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

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

<!-- ===============================
     CONFIRM + DOUBLE SUBMIT SAFE
================================ -->
<script>
document.addEventListener("DOMContentLoaded", function () {

let submitting = false;
const form = document.getElementById("dlForm");
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>
