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

// Fetch fee
$price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='Chassic_rc_find'"));
$fee   = $price['price'] ?? 0;

$resdata = [];
$status  = '';
$message = '';
$error   = '';

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

    $chassisNumber = mysqli_real_escape_string($ahk_conn, $_POST['chassisNumber']);
    $appliedby     = $udata['phone'];
    $debit_fee     = $udata['balance'] - $fee;

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

        $apikey = urlencode($flexsecure_key);
        $url = "https://" . htmlspecialchars($flexsecureapiurl) . "/api/v1/chassis_to_Rc?apiKey=$apikey&chassisNumber=" . urlencode($chassisNumber);

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 60,
            CURLOPT_FOLLOWLOCATION => true
        ]);

        $response = curl_exec($curl);
        $curl_err = curl_error($curl);
        curl_close($curl);

        if (!$response) {
            $error = $curl_err ?: 'No response from RC API.';
            echo "<script>Swal.fire('Error', '$error', 'error');</script>";
        } else {

            $resdata = json_decode($response, true);
            $status  = $resdata['status'] ?? '';
            $message = $resdata['statusMessage'] ?? '';
            $error   = $resdata['error'] ?? 'RC Data Not Found';

            if ($status === "100" && strtolower($message) === "success") {

                // Deduct balance
                mysqli_query($ahk_conn, "UPDATE users SET balance = balance - $fee WHERE phone = '$appliedby'");
                mysqli_query($ahk_conn, "
                    INSERT INTO wallethistory(userid,amount,balance,purpose,status,type)
                    VALUES('$appliedby','$fee','$debit_fee','RC Details Find $chassisNumber','1','Debit')
                ");

            } else {
                echo "<script>Swal.fire('Error', '" . addslashes($error) . "', 'error');</script>";
                $resdata = [];
            }
        }
    } else {
        echo "<script>Swal.fire('Low Balance', 'Please recharge your wallet!', 'error'); setTimeout(() => { window.location='wallet.php'; }, 1200);</script>";
    }
}
?>

<style>
.result-card {
    background: #f3f9ff;
    border-left: 6px solid #007bff;
}
.icon-box {
    font-size: 40px;
    color: #007bff;
}
.label-title {
    font-weight: 600;
    color: #444;
}
.value-text {
    font-weight: 700;
    color: #000;
}
</style>

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

        <div class="page-breadcrumb d-flex align-items-center justify-content-between mb-4 p-3 bg-white rounded shadow-sm">
            <div class="d-flex align-items-center">
                <div class="breadcrumb-title pe-3">Services</div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 ps-2">
                        <li class="breadcrumb-item active">RC Details Find</li>
                    </ol>
                </nav>
            </div>
            <a href="javascript:history.back()" class="btn btn-outline-primary">
                <i class="bi bi-arrow-left"></i> Back
            </a>
        </div>

        <div class="container-fluid px-4">
            <div class="row">

                <!-- Left: Search Form -->
                <div class="col-lg-5 mb-4">
                    <div class="card shadow-sm">
                        <div class="card-header bg-primary text-white text-center">
                            <h4 class="mb-0">RC Details Finder</h4>
                        </div>
                        <div class="card-body">

                            <form method="POST" class="row g-3">

                                <div class="col-md-12">
                                    <label class="form-label">Enter Chassis Number</label>
                                    <input 
                                        name="chassisNumber" 
                                        type="text" 
                                        class="form-control form-control-lg" 
                                        placeholder="Example: MBLHA11EWD9KXXXXX"
                                        required>
                                </div>

                                <div class="col-md-12">
                                    <label class="form-label">Vehicle Type (Optional)</label>
                                    <select name="vehicleType" class="form-select">
                                        <option value="">Select Vehicle Type</option>
                                        <option value="Bike">Bike</option>
                                        <option value="Scooter">Scooter</option>
                                        <option value="Moped">Moped</option>
                                        <option value="Car">Car</option>
                                        <option value="Commercial">Commercial</option>
                                    </select>
                                </div>

                                <hr>

                                <div class="d-flex justify-content-between">
                                    <input class="form-control w-50" value="Fee: ₹<?php echo $fee; ?>" readonly>
                                    <button class="btn btn-success btn-lg" type="submit">
                                        <i class="fa fa-search"></i> Search
                                    </button>
                                </div>

                            </form>

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

                <!-- Right: API Response -->
                <?php if (!empty($resdata) && $status === "100") { ?>
                <div class="col-lg-7">
                    <div class="card result-card shadow-sm" id="printSection">

                        <div class="card-header text-center bg-white">
                            <h4 class="text-primary"><strong>RC Details</strong></h4>
                        </div>

                        <div class="card-body">

                            <div class="row text-center mb-4">
                                <div class="col">
                                    <i class="bi bi-car-front-fill icon-box"></i>
                                    <div class="label-title mt-2">Registration</div>
                                    <div class="value-text"><?php echo $resdata['regNo']; ?></div>
                                </div>

                                <div class="col">
                                    <i class="bi bi-person-fill icon-box"></i>
                                    <div class="label-title mt-2">Owner</div>
                                    <div class="value-text"><?php echo $resdata['owner']; ?></div>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-bordered table-striped">
                                    <tbody>
                                        <tr>
                                            <th>Chassis No</th>
                                            <td><?php echo $resdata['chassis']; ?></td>
                                        </tr>
                                        <tr>
                                            <th>Engine No</th>
                                            <td><?php echo $resdata['engine']; ?></td>
                                        </tr>
                                        <?php if (!empty($_POST['vehicleType'])) { ?>
                                        <tr>
                                            <th>Vehicle Type</th>
                                            <td><?php echo htmlspecialchars($_POST['vehicleType']); ?></td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>

                            <div class="text-center mt-3">
                                <button onclick="window.print()" class="btn btn-primary">
                                    <i class="bi bi-printer"></i> Print
                                </button>
                            </div>

                        </div>
                    </div>
                </div>
                <?php } ?>

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




<?php include('footer.php'); ?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
</html>
