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

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

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

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

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

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

        $resdata = vehicle_rcpdf_verification_v2_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 V2 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 V2 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>";
    }
}
?>

<!-- ===============================
     CLEAN UI - WITH FATHER NAME
================================ -->

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

<style>
.card-shine {
    border-radius: 20px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    transition: .3s;
    border: none;
}
.card-shine:hover {
    transform: translateY(-3px);
    box-shadow: 0 18px 40px rgba(0,0,0,0.15);
}
.container-center {
    min-height: 85vh;
    display: flex;
    align-items: center;
    justify-content: center;
}
.form-label {
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 8px;
    color: #333;
}
.placeholder-small::placeholder {
    font-size: 13px;
    color: #aaa;
}
.single-line {
    width: 100%;
    height: 1px;
    background: linear-gradient(90deg, transparent, #e2e8f0, #e2e8f0, #e2e8f0, transparent);
    margin: 20px 0;
}
</style>

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

<div class="col-lg-4 col-md-6 col-sm-10">
<div class="card card-shine">
<div class="card-body p-4">

<!-- Back Button -->
<a href="javascript:history.back()" class="btn btn-light mb-4 w-100 py-2" style="border-radius: 12px;">
    ← Go Back
</a>

<!-- Title -->
<div class="text-center mb-4">
    <h5 class="fw-bold mb-1" style="color: #1e293b;">🚗 Vehicle PDF Verification</h5>
    <p class="text-muted small">Get your vehicle registration certificate PDF</p>
</div>

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

<!-- Vehicle Number -->
<div class="mb-3">
    <label class="form-label">VEHICLE NUMBER *</label>
    <input type="text" name="rcno" class="form-control placeholder-small"
           placeholder="Enter Vehicle Number (e.g., DL01AB1234)" 
           style="border-radius: 12px; padding: 12px;" required>
</div>

<!-- Father Name -->
<div class="mb-3">
    <label class="form-label">FATHER'S NAME *</label>
    <input type="text" name="fathername" class="form-control placeholder-small"
           placeholder="Enter Father's Name" 
           style="border-radius: 12px; padding: 12px;" required>
</div>

<!-- Vehicle Type -->
<div class="mb-3">
    <label class="form-label">VEHICLE TYPE *</label>
    <select name="rctype" class="form-select" style="border-radius: 12px; padding: 12px;" 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>

<!-- Ek Line Left se Right tak -->
<div class="single-line"></div>

<!-- Service Charge -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <span class="fw-semibold" style="color: #475569;">💰 SERVICE CHARGE</span>
    <span class="fw-bold fs-5" style="color: #1e293b;">₹ <?= number_format($fee, 2) ?></span>
</div>

<!-- Submit Button -->
<button class="btn btn-success w-100 py-2" id="submitBtn" style="border-radius: 12px; font-weight: 600; font-size: 16px;">
    📄 GENERATE PDF
</button>

</form>

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

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

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

<!-- ===============================
     CONFIRMATION SCRIPT
================================ -->
<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',
    confirmButtonColor: '#10b981'
  }).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>