<?php
require_once("../layouts/members/head.php");
if ($user_data['challan_Check_Service'] == "YES") {
    if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
?>
<div class="row">
    <!-- Form Section (Left) -->
    <div class="col-md-4 mb-2">
        <div class="card text-danger">
            <div class="card-header bg-primary text-white py-2">
                <div class="d-flex align-items-center">
                    <span class="mr-auto"><?= file_name() ?></span>
                    <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()">
                        <i class="fas fa-arrow-left"></i> Back
                    </button>
                </div>
            </div>
            <div class="p-3 text-dark">
                <?php
                $apiResponseData = null;
                if (isset($_POST['submit'])) {
                    $vehicalNumber = strtoupper(trim($_POST['vehicalNumber']));
                    if (!empty($vehicalNumber)) {
                        $amount = $user_data['challan_fee'];
                        $old_balance = $user_data['balance'];
                        $new_balance = $old_balance - $amount;
                        if ($old_balance >= $amount) {
                            $order_id = order_txn_id();
                            $request = ['vehicalNumber' => $vehicalNumber, 'order_id' => $order_id];
                            $responseApi = Challanfind_api_run($request);
                            $response = json_decode($responseApi, true) ?? '';
                            $vehicalinfo = $response['vehicle'] ?? '';
                            $challans = $response['challans'] ?? [];
                            $name = $vehicalinfo['owner_name'] ?? ($challans[0]['owner_name'] ?? '');
                            if ($response['status'] == '100') {
                                $updateSuccess = db_update("members", ["balance" => $new_balance], "user_id='{$user_data['user_id']}'");
                                if ($updateSuccess) {
                                    $insData = [
                                        'site_id'       => $site_data['site_id'],
                                        'user_id'       => $user_data['user_id'],
                                        'username'      => $user_data['username'],
                                        'name'          => $user_data['name'],
                                        'operator'      => $user_data['usertype'],
                                        'parent_id'     => $user_data['parent_id'],
                                        'order_id'      => $order_id,
                                        'service'       => "CHALLAN",
                                        'type'          => "Debit",
                                        'account_number'=> $vehicalinfo['registration_number'],
                                        'app_type'      => "CHALLAN",
                                        'amount'        => $amount,
                                        'main_amount'   => $amount,
                                        'old_balance'   => $old_balance,
                                        'new_balance'   => $new_balance,
                                        'txn_id'        => $order_id,
                                        'ref_id'        => $vehicalinfo['registration_number'],
                                        'description'   => "Rs.{$amount} Has Been Debit From Wallet for Name {$name} Vehical Number",
                                        'date_time'     => current_timestamp(),
                                        'status'        => "Success"
                                    ];
                                    $insertId = db_insert("reports", $insData);
                                    if ($insertId) {
                                        $fields = [
                                            'registration_number' => 'Vehical No',
                                            'owner_name' => 'Name',
                                            'model_name' => 'Model',
                                            'vehicle_name' => 'Vehicle',
                                            'vehicle_model' => 'Model',
                                            'fuel_type' => 'Fuel Type',
                                        ];
                                        $whamessage = "Dear {$user_data['name']},\nYour Request for Vehical Number *{$vehicalNumber}* TO Challan Find has been Complete.\n\n";
                                        foreach ($fields as $key => $label) {
                                            if (!empty($challans[0][$key])) {
                                                $whamessage .= "*$label*: {$challans[0][$key]}\n";
                                            } elseif (!empty($vehicalinfo[$key])) {
                                                $whamessage .= "*$label*: {$vehicalinfo[$key]}\n";
                                            }
                                        }
                                        $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";
                                        send_sms($user_data['mobile'], $whamessage);
                                    } else {
                                        awal_alert_msg("Insert Server Error!", 'error');
                                    }
                                } else {
                                    awal_alert_msg("Balance debited but not updated in DB!", 'error');
                                }
                            } else {
                                awal_alert_msg($response['error'] ?? 'Wrong Rc Details', 'error');
                            }
                        } else {
                            awal_alert_msg("Insufficient Wallet Balance!", 'error');
                        }
                    } else {
                        awal_alert_msg("Please Fill All Valid Details!", 'error');
                    }
                }
                ?>
                <form action="" method="POST" class="row">
                    <div class="col-md-12 mb-3">
                        <label>Vehical Number</label>
                        <input type="text" name="vehicalNumber" placeholder="Enter Vehical Number" maxlength="15" oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" required>
                    </div>
                    <div class="col-md-12 mb-3 d-flex justify-content-between">
                        <button type="button" class="btn btn-secondary">
                            <i class="fas fa-inr"></i> <?= $user_data['challan_fee']; ?>
                        </button>
                        <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Result Section (Right) -->
    <div class="col-md-8">
        <?php if (!empty($challans)) { ?>
        <div class="card text-danger">
            <div class="card-header bg-primary text-white py-2">
                <span class="mr-auto">Challan Details</span>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr style="text-align: center;">
                            <th>Challan Number</th>
                            <th>Name</th>
                            <th>Location</th>
                            <th>Source</th>
                            <th>Date</th>
                            <th>Penalty</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($challans as $challan) { ?>
                        <tr>
                            <td><?= $challan['challan_number']; ?></td>
                            <td><?= $challan['owner_name']; ?></td>
                            <td><?= $challan['location']; ?></td>
                            <td><?= $challan['challan_search_source']; ?></td>
                            <td><?= $challan['date']; ?></td>
                            <td><?= $challan['penalty']; ?></td>
                            <td><button class="btn btn-primary"><b><?= $challan['amount']; ?></b></button></td>
                            <td>
                                <?php if ($challan['challan_status'] == 'PAID') { ?>
                                <button class="btn btn-success"><b>PAID</b></button>
                                <?php } else { ?>
                                <button class="btn btn-danger"><b>UNPAID</b></button>
                                <?php } ?>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php } elseif (!empty($vehicalinfo)) { ?>
        <div class="card text-danger">
            <div class="card-header bg-danger text-white py-2">
                <span class="mr-auto">No challans found for Vehicle Number: <strong><?= $vehicalinfo['registration_number']; ?></strong></span>
            </div>
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr style="text-align: center;">
                            <th>Field</th>
                            <th>Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr><td><strong>Owner Name</strong></td><td><?= htmlspecialchars($vehicalinfo['owner_name'] ?? 'N/A'); ?></td></tr>
                        <tr><td><strong>Model Name</strong></td><td><?= htmlspecialchars($vehicalinfo['model_name'] ?? 'N/A'); ?></td></tr>
                        <tr><td><strong>Fuel Type</strong></td><td><?= htmlspecialchars($vehicalinfo['fuel_type'] ?? 'N/A'); ?></td></tr>
                        <tr><td><strong>Vehicle Type</strong></td><td><?= htmlspecialchars($vehicalinfo['vehicle_type_v2'] ?? 'N/A'); ?></td></tr>
                        <tr><td><strong>Vehicle Model</strong></td><td><?= htmlspecialchars($vehicalinfo['vehicle_model'] ?? 'N/A'); ?></td></tr>
                        <tr><td><strong>Vehicle Name</strong></td><td><?= htmlspecialchars($vehicalinfo['vehicle_name'] ?? 'N/A'); ?></td></tr>
                    </tbody>
                </table>
            </div>
        </div>
        <?php } ?>
    </div>
</div>
<?php
    } else {
        require_once("404.php");
    }
} else {
    awal_alert_msg('You Do Not Have Any Challan Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>
