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

// Fee and Service Status Check
$fee = $udata['Vehicle_pdf_fee'] ?? 30;
checkServiceStatus($udata, 'Vehicle_pdf_fee_status');

$appliedby = $udata['phone'];
$balance   = $udata['balance'];

/**
 * Dynamic API Call (SQL se API Key & URL fetch karega)
 */
function vehicle_rcpdf_verification_api_run($veh_no) {
    $apiKey = JkL_get('TheNextGenAPI', 'tng_apikey'); 
    $baseUrl = JkL_get('TheNextGenAPI', 'tng_apiurl');
    
    // Naya ApiNexus URL structure
    $url = "https://" . rtrim($baseUrl, "/") . "/serviceApi/TargetApiV1/RC/rc_link1.php?apiKey=$apiKey&vechil_no=$veh_no";

    $resJson = http_get($url); 
    return json_decode($resJson, true) ?? [];
}

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

    $rcno      = strtoupper(trim($_POST['rcno']));
    $debit_fee = $balance - $fee;

    // 1. Balance Check
    if ($balance < $fee) {
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire('Low Balance','Please Recharge Wallet','error').then(()=>{ window.location='wallet.php'; });
        </script>";
        exit;
    }

    // 2. Execute API
    $resdata = vehicle_rcpdf_verification_api_run($rcno);

    // 3. Response Handling (ApiNexus Success Check)
    if (isset($resdata['status']) && ($resdata['status'] == "100" || $resdata['statusMessage'] == "success")) {
        
        date_default_timezone_set('Asia/Kolkata');
        $timestamp = date("Y-m-d H:i:s");
        $parentPhone = $udata['parent'] ?? null;

        /* Commission Update */
        addCommission($tng_conn, $appliedby, $fee, $parentPhone, "Vehicle RC PDF");

        /* 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 RC PDF','1','Debit')");

        /* Save to PDF History Table */
        $pdf_content = mysqli_real_escape_string($tng_conn, $resdata['pdf']);
        $cust_name   = !empty($resdata['name']) ? mysqli_real_escape_string($tng_conn, $resdata['name']) : "RC Holder";
        $veh_num     = mysqli_real_escape_string($tng_conn, $resdata['vehical_number']);

        mysqli_query($tng_conn, "INSERT INTO all_pdf_records (service_name, name, username, number, pdf, date) 
                     VALUES ('vehicle_rc', '$cust_name', '$appliedby', '$veh_num', '$pdf_content', '$timestamp')");

        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'Vehicle RC PDF Generated Successfully',
                timer:1500,
                showConfirmButton:false
            }).then(()=>{ window.location='all_history.php'; });
        </script>";
    } else {
        $errorMsg = $resdata['message'] ?? 'RC Fetch Failed or API Error';
        echo "<script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
        <script>Swal.fire('Error', '$errorMsg', 'error');</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-primary text-center fw-bold">Vehicle RC PDF Verification</div>

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

<div class="mb-3">
    <label class="fw-bold">Vehicle Number</label>
    <input type="text" name="rcno" class="form-control text-uppercase" placeholder="e.g. BR07AW5521" required>
</div>

<div class="mb-3 d-none">
    <label>Vehicle Type</label>
    <select name="rctype" class="form-control">
      <option value="1" selected>Default</option>
    </select>
</div>

<div class="mb-3">
    <label class="small text-muted">Service Charge</label>
    <input class="form-control text-center fw-bold" value="Fee ₹ <?= $fee ?>" readonly style="background:#f8f9fa;">
</div>

<button class="btn btn-primary w-100 fw-bold" id="submitBtn">Generate RC PDF</button>

</form>

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

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

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

<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: 'Confirm Request?',
            text: 'PDF generate hogi aur wallet se ₹<?= $fee ?> deduct honge.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, Proceed',
            cancelButtonText: 'Cancel'
        }).then((result)=>{
            if(result.isConfirmed){
                submitting = true;
                btn.disabled = true;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Processing...';
                form.submit();
            }
        });
    });
});
</script>

<script src="../template/tngweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/tngweb/assets/js/app.js"></script>