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

$fee = $udata['challan_fee'];
checkServiceStatus($udata,'challan_fee_status');

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

    $rcno   = strtoupper(trim($_POST['rcno']));
    $user   = $udata['phone'];
    $wallet = $udata['balance'];


    if ($wallet < $fee) {
        echo "<script>
            Swal.fire('Wallet Low','Please recharge wallet','error')
            .then(()=>window.location='wallet.php');
        </script>";
        exit;
    }

 
    $resdata = vehicle_chalan_verification_api_run([
        'rcno' => $rcno
    ]);

    $apiStatus = $resdata['Message'] ?? '';
    $apiError  = $resdata['error'] ?? 'Unable to fetch challan';


    if ($apiStatus !== 'Success') {
        echo "<script>
            Swal.fire('Failed','".addslashes($apiError)."','error');
        </script>";
        exit;
    }


    mysqli_query(
        $tng_conn,
        "UPDATE users SET balance=balance-$fee WHERE phone='$user'"
    );

 
    addCommission(
        $tng_conn,
        $user,
        $fee,
        $udata['parent'] ?? null,
        'VEHICLE CHALLAN FIND'
    );

 
    mysqli_query(
        $tng_conn,
        "INSERT INTO wallethistory
        (userid,amount,balance,purpose,status,type)
        VALUES(
            '$user',
            '$fee',
            '".($wallet-$fee)."',
            'VEHICLE CHALLAN FIND',
            '1',
            'Debit'
        )"
    );

  
    $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(
            'VEHICLE_CHALLAN',
            '".mysqli_real_escape_string($tng_conn,$resdata['vehicle']['registration_number'])."',
            '$user',
            '$rcno',
            '".mysqli_real_escape_string($tng_conn,$base64Json)."',
            NOW()
        )"
    );


    echo "<script>
        Swal.fire({
            icon:'success',
            title:'CHALLAN FOUND',
            text:'Vehicle challan details saved successfully',
            timer:2200,
            showConfirmButton:false
        }).then(()=>window.location='all_history.php');
    </script>";
    exit;
}
?>

<!-- ================= LUXURY UI ================= -->
<style>
body{
  background:linear-gradient(135deg,#fff7ed,#ecfeff);
}
.glass{
  background:#fff;
  border-radius:22px;
  box-shadow:0 25px 55px rgba(0,0,0,.15);
  padding:36px;
}
.title{
  font-weight:700;
  color:#92400e;
}
</style>

<div class="page-wrapper">
<div class="page-content">
<div class="container">

<div class="row justify-content-center align-items-center" style="min-height:80vh;">
<div class="col-lg-5 col-md-7 col-sm-10">

<div class="glass">

<div class="mb-3">
    <a href="javascript:history.back()" class="fw-bold text-primary">
        <i class="bi bi-arrow-left-circle"></i> Back
    </a>
</div>

<h4 class="title text-center mb-2">
🚔 Vehicle Challan Finder
</h4>

<p class="text-center text-muted mb-4">
Check traffic challans using vehicle number
</p>

<form method="post" id="challanForm">

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

<div class="row mt-4 align-items-center">
    <div class="col-6">
        <input class="form-control fw-bold text-success"
               value="Fee ₹ <?= $fee ?>" readonly>
    </div>
    <div class="col-6 text-end">
        <button type="submit"
                id="submitBtn"
                class="btn btn-warning px-4 rounded-pill">
            <i class="fa fa-search"></i> Check
        </button>
    </div>
</div>

</form>

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

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let lock=false;
document.getElementById('challanForm').addEventListener('submit',function(e){
    e.preventDefault();
    if(lock) return;

    Swal.fire({
        title:'Confirm Request?',
        text:'Proceed with Vehicle Challan verification?',
        icon:'question',
        showCancelButton:true,
        confirmButtonText:'Yes',
        cancelButtonText:'Cancel'
    }).then(r=>{
        if(r.isConfirmed){
            lock=true;
            document.getElementById('submitBtn').disabled=true;
            this.submit();
        }
    });
});
</script>

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