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

$fee = $udata['Vehicle_pdf_fee'] ?? 30;
checkServiceStatus($udata, 'Vehicle_pdf_fee_status');

/* ===============================
   FORM SUBMIT HANDLER
================================ */
if (isset($_POST['rcno'], $_POST['rctype'])) {

    $rcno      = trim($_POST['rcno']);
    $rctype    = $_POST['rctype'];
    $appliedby = $udata['phone'];
    $debit_fee = $udata['balance'] - $fee;

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

        $request = [
            'rcno'   => $rcno,
            'rctype' => $rctype
        ];

        $resdata = vehicle_rcpdf_verification_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'] ?? 'Failed')."', 'error');
            </script>";
        }
        elseif (($resdata['sampleCode'] ?? '') === "200") {

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

            /* Commission */
            $parentPhone = $udata['parent'] ?? null;
            addCommission(
                $tng_conn,
                $appliedby,
                $fee,
                $parentPhone,
                "Vehicle PDF Verification"
            );

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

            /* Wallet History */
            mysqli_query(
                $tng_conn,
                "INSERT INTO wallethistory
                 (userid, amount, balance, purpose, status, type)
                 VALUES
                 ('$appliedby','$fee','$debit_fee',
                  'Vehicle PDF Verification','1','Debit')"
            );

            /* ✅ MAIN PDF HISTORY TABLE (ONLY THIS) */
            mysqli_query(
                $tng_conn,
                "INSERT INTO all_pdf_records
                 (service_name, name, username, number, pdf, date)
                 VALUES
                 (
                    'vehicle_rc',
                    '".mysqli_real_escape_string($tng_conn, $resdata['fullname'])."',
                    '".$udata['phone']."',
                    '".mysqli_real_escape_string($tng_conn, $resdata['rcno'])."',
                    '".mysqli_real_escape_string($tng_conn, $resdata['Rc_Pdf'])."',
                    '$timestamp'
                 )"
            );

            echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
            <script>
                Swal.fire({
                    icon:'success',
                    title:'Success',
                    text:'Vehicle 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>";
    }
}
?>

<!-- ===============================
     SHINE UI + FORM
================================ -->

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

<style>
.card-shine{
  border-radius:15px;
  box-shadow:0 10px 30px rgba(0,0,0,0.15);
  transition:.3s;
}
.card-shine:hover{
  transform:translateY(-3px);
  box-shadow:0 18px 40px rgba(0,0,0,0.25);
}
</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">
Vehicle PDF Verification
</div>

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

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

<div class="mb-3">
<label>Vehicle Type</label>
<select name="rctype" class="form-control" required>
  <option value="">Select Type</option>
  <option value="1">Chip</option>
  <option value="2">Without Chip</option>
  <option value="4">Chip New</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 CLICK SAFE
================================ -->
<script>
document.addEventListener("DOMContentLoaded", function () {

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