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

$fee = $udata['chassis_2_rc'];
checkServiceStatus($udata, 'chassis_2_rc_status');

$resdata = [];
$sampleCode = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['chassisNumber'])) {

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

    /* ===== WALLET CHECK ===== */
    if ($wallet < $fee) {
        echo "<script>
            Swal.fire({
                icon:'error',
                title:'Wallet Balance Low',
                text:'Please recharge wallet'
            }).then(()=>window.location='wallet.php');
        </script>";
        exit;
    }

    /* ===== API CALL ===== */
    $request = [
        'chassisNumber' => $chassisNumber
    ];

    $resdata     = chassis_to_rc_verification_api_run($request);
    $sampleCode  = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['error'] ?? '';

    /* ❌ ERROR CASE */
    if (!empty($errorMsg)) {
        echo "<script>
            Swal.fire({
                icon:'error',
                title:'Error',
                text:'".addslashes($errorMsg)."'
            });
        </script>";
    }

    /* ✅ SUCCESS CASE */
    if ($sampleCode === "200") {

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

        // ===== COMMISSION =====
        addCommission(
            $tng_conn,
            $appliedby,
            $fee,
            $udata['parent'] ?? null,
            'Chassis to RC Verification'
        );

        // ===== WALLET HISTORY =====
        mysqli_query(
            $tng_conn,
            "INSERT INTO wallethistory
            (userid, amount, balance, purpose, status, type)
            VALUES(
                '$appliedby',
                '$fee',
                '$debit_fee',
                'Chassis to RC Verification',
                '1',
                'Debit'
            )"
        );

        // ===== BASE64 JSON SAVE =====
        $base64Json = base64_encode(
            json_encode($resdata, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
        );

        mysqli_query(
            $tng_conn,
            "INSERT INTO all_pdf_records
            (service_name, name, username, number, pdf, date)
            VALUES(
                'CHASSIS_TO_RC',
                '".mysqli_real_escape_string($tng_conn, $resdata['vehicle_num'] ?? 'RC')."',
                '$appliedby',
                '".mysqli_real_escape_string($tng_conn, $chassisNumber)."',
                '".mysqli_real_escape_string($tng_conn, $base64Json)."',
                NOW()
            )"
        );

        echo "<script>
            Swal.fire({
                icon:'success',
                title:'Success',
                text:'Chassis to RC verification completed',
                timer:2500,
                showConfirmButton:false
            }).then(()=>{
                window.location='all_history.php';
            });
        </script>";
        exit;
    }
}
?>

<!-- ================= UI ================= -->

<div class="page-wrapper">
<div class="page-content">
<div class="container d-flex justify-content-center">

<div class="card luxury-card col-lg-6 col-md-8 p-4">

<h4 class="text-center fw-bold text-primary mb-4">
🚘 Chassis to RC Verification
</h4>

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

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

<div class="d-flex justify-content-between align-items-center mt-4">
<input class="form-control w-50 text-center fw-bold"
       value="Fee ₹ <?= $fee ?>"
       readonly>

<button type="button"
        id="submitBtn"
        class="btn btn-success rounded-pill px-4">
<i class="fa fa-check-circle me-1"></i> Submit
</button>
</div>

<div class="text-center mt-3">
<a href="javascript:history.back()" class="text-decoration-none">
⬅️ Back
</a>
</div>

</form>
</div>

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

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

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

<script>
let isSubmitting = false;

document.getElementById('submitBtn').addEventListener('click', function(){

    if(isSubmitting) return;

    Swal.fire({
        title:'Are you sure?',
        text:'Wallet balance will be deducted',
        icon:'question',
        showCancelButton:true,
        confirmButtonText:'Yes, Continue',
        cancelButtonText:'Cancel'
    }).then((res)=>{
        if(res.isConfirmed){
            isSubmitting = true;
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('chassisForm').submit();
        }
    });
});
</script>

<style>
body{background:#f4f6fb}

.luxury-card{
  border-radius:20px;
  background:linear-gradient(145deg,#ffffff,#eef2ff);
  box-shadow:0 25px 50px rgba(0,0,0,.12);
}
</style>
