<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('con.php');
include('config_api.php');
include('header.php');

if (!isset($_SESSION['phone'])) {
    header("Location: login.php");
    exit;
}

$username   = $_SESSION['phone'];
$errorMsg   = null;
$successMsg = null;
$popupData  = [];

/* ================= USER DATA ================= */

$udata = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT * FROM users WHERE phone='$username'")
);

$wallet = (float)$udata['balance'];
$parent = $udata['parent'];

/* ================= SERVICE RATE ================= */

$feeRow = mysqli_fetch_assoc(
    mysqli_query($ahk_conn, "SELECT rate FROM price WHERE service='vehicle_challan_verify'")
);

$fee = (float)($feeRow['rate'] ?? 0);

/* ================= VERIFY VEHICLE ================= */

if (isset($_POST['verify_vehicle'])) {

    $rc_no = strtoupper(
        preg_replace('/[^A-Z0-9]/', '', $_POST['rc_no'])
    );

    if (empty($rc_no)) {

        $errorMsg = "Enter Vehicle Registration Number.";

    } elseif ($wallet < $fee) {

        $errorMsg = "Insufficient wallet balance.";

    } else {

        /* ================= API ================= */

        $api_url = "https://maxxapi.site/challan_verify?api_key=".$apikey."&vehicle_no=".urlencode($rc_no);

        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false
        ]);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {
            $errorMsg = curl_error($ch);
        }

        curl_close($ch);

        $data = json_decode($response, true);

        if (!$data) {

            $errorMsg = "Invalid API Response";

        } elseif (

            (isset($data['status']) && strtolower($data['status']) == "success")
            ||

            (isset($data['Status']) && strtolower($data['Status']) == "success")

            ||

            (
                isset($data['message']) &&
                strtolower(trim($data['message'])) == 'challan data retrieved from cache'
            )

        ) {

            $popupData = $data;

            $tracking_id = mysqli_real_escape_string(
                $ahk_conn,
                $data['tracking_id'] ?? ''
            );

            $date = date("Y-m-d H:i:s");

            /* ================= SAVE HISTORY ================= */

            mysqli_query($ahk_conn, "
                INSERT INTO vehicle_challan_history
                (
                    username,
                    registration_no,
                    vehicle_name,
                    model_name,
                    fuel_type,
                    vehicle_type,
                    date
                )
                VALUES
                (
                    '$username',
                    '$rc_no',
                    '',
                    '',
                    '',
                    '',
                    '$date'
                )
            ");

            /* ================= SAVE CHALLANS ================= */

            if (!empty($data['challans']) && is_array($data['challans'])) {

                foreach ($data['challans'] as $c) {

                    $owner_name = mysqli_real_escape_string(
                        $ahk_conn,
                        $c['owner_name']
                        ?? $c['accused_name']
                        ?? ''
                    );

                    $location = mysqli_real_escape_string(
                        $ahk_conn,
                        $c['location']
                        ?? $c['offence_location']
                        ?? ''
                    );

                    $challan_no = mysqli_real_escape_string(
                        $ahk_conn,
                        $c['challan_no']
                        ?? $c['challan_number']
                        ?? ''
                    );

                    $penalty = mysqli_real_escape_string(
                        $ahk_conn,
                        $c['offence']
                        ?? $c['offence_name']
                        ?? ''
                    );

                    $amount = mysqli_real_escape_string(
                        $ahk_conn,
                        $c['amount'] ?? '0'
                    );

                    $status = mysqli_real_escape_string(
                        $ahk_conn,
                        $c['status']
                        ?? $c['challan_status']
                        ?? ''
                    );

                    $challan_date = mysqli_real_escape_string(
                        $ahk_conn,
                        $c['date']
                        ?? $c['challan_date']
                        ?? date('Y-m-d H:i:s')
                    );

                    mysqli_query($ahk_conn, "
                        INSERT INTO vehicle_challans
                        (
                            username,
                            registration_no,
                            owner_name,
                            location,
                            challan_number,
                            penalty,
                            amount,
                            challan_status,
                            challan_date
                        )
                        VALUES
                        (
                            '$username',
                            '$rc_no',
                            '$owner_name',
                            '$location',
                            '$challan_no',
                            '$penalty',
                            '$amount',
                            '$status',
                            '$challan_date'
                        )
                    ");
                }
            }

            /* ================= WALLET DEDUCT ================= */

            $new_balance = $wallet - $fee;

            mysqli_query(
                $ahk_conn,
                "UPDATE users SET balance='$new_balance' WHERE phone='$username'"
            );

            /* ================= WALLET HISTORY ================= */

            mysqli_query($ahk_conn, "
                INSERT INTO wallethistory
                (
                    userid,
                    amount,
                    balance,
                    purpose,
                    status,
                    type
                )
                VALUES
                (
                    '$username',
                    '$fee',
                    '$new_balance',
                    'Vehicle Challan Verification',
                    '1',
                    'Debit'
                )
            ");

            /* ================= PARENT COMMISSION ================= */

            if (!empty($parent) && strtolower($parent) != 'admin') {

                $commission = round(($fee * 15) / 100, 2);

                if ($commission > 0) {

                    $pRes = mysqli_query(
                        $ahk_conn,
                        "SELECT balance FROM users WHERE phone='$parent' LIMIT 1"
                    );

                    if (mysqli_num_rows($pRes) > 0) {

                        $pData = mysqli_fetch_assoc($pRes);

                        $parent_balance = (float)$pData['balance'];

                        $parent_newbalance =
                            $parent_balance + $commission;

                        mysqli_query(
                            $ahk_conn,
                            "UPDATE users
                             SET balance='$parent_newbalance'
                             WHERE phone='$parent'"
                        );

                        mysqli_query($ahk_conn, "
                            INSERT INTO wallethistory
                            (
                                userid,
                                amount,
                                balance,
                                purpose,
                                status,
                                type
                            )
                            VALUES
                            (
                                '$parent',
                                '$commission',
                                '$parent_newbalance',
                                'Commission from $username',
                                '1',
                                'Credit'
                            )
                        ");
                    }
                }
            }

            $successMsg = "Vehicle Challan Verified Successfully";

        } else {

            $errorMsg = $data['message'] ?? 'API Error';
        }
    }
}

/* ================= HISTORY ================= */

$history = mysqli_query($ahk_conn, "
    SELECT *
    FROM vehicle_challan_history
    WHERE username='$username'
    ORDER BY id DESC
");

?>

<!DOCTYPE html>
<html>

<head>

<title>Vehicle Challan Verification</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">

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

<style>

.card-box{
    background:#fff;
    padding:25px;
    border-radius:15px;
    box-shadow:0 8px 25px rgba(0,0,0,.1)
}

</style>

</head>

<body class="bg-light">

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

<div class="row g-4">

<!-- FORM -->
<div class="col-lg-4">

<div class="card-box">

<h5 class="text-primary mb-3">
🚗 Vehicle Challan Verification
</h5>

<form method="POST">

<input
type="text"
name="rc_no"
maxlength="15"
required
class="form-control text-center mb-3"
placeholder="PB55D2166"
oninput="this.value=this.value.toUpperCase().replace(/[^A-Z0-9]/g,'')"
>

<div class="alert alert-warning text-center py-1">
Fee: ₹<?= number_format($fee,2) ?>
</div>

<button
class="btn btn-primary w-100"
name="verify_vehicle"
>
Verify Vehicle
</button>

</form>

</div>
</div>

<!-- HISTORY -->
<div class="col-lg-8">

<div class="card-box">

<table
id="vehicleTable"
class="table table-bordered align-middle text-center"
>

<thead class="table-dark">

<tr>
<th>ID</th>
<th>Date</th>
<th>RC Number</th>
</tr>

</thead>

<tbody>

<?php while ($r = mysqli_fetch_assoc($history)): ?>

<tr>

<td>#<?= $r['id'] ?></td>

<td>
<?= date('d M Y h:i A', strtotime($r['date'])) ?>
</td>

<td class="fw-bold text-primary">
<?= htmlspecialchars($r['registration_no']) ?>
</td>

</tr>

<?php endwhile; ?>

</tbody>
</table>

</div>
</div>

</div>
</div>

<!-- ERROR POPUP -->

<?php if ($errorMsg): ?>

<script>

Swal.fire({
    icon:'error',
    title:'Error',
    text:<?= json_encode($errorMsg) ?>
});

</script>

<?php endif; ?>

<!-- SUCCESS POPUP -->

<?php if ($successMsg): ?>

<?php

$popup_rc = htmlspecialchars(
    $popupData['vehicle_no']
    ?? $popupData['rcNumber']
    ?? $rc_no
    ?? '-'
);

$popup_tracking = htmlspecialchars(
    $popupData['tracking_id']
    ?? '-'
);

?>

<script>

let challans = <?= json_encode($popupData['challans'] ?? []) ?>;

let html = `

<div class="text-start">

<p>
<b>RC Number:</b>
<?= $popup_rc ?>
</p>

<p>
<b>Tracking ID:</b>
<?= $popup_tracking ?>
</p>

<hr>

`;

if(challans.length > 0){

challans.forEach((c,index)=>{

html += `

<div class="border rounded p-2 mb-2">

<b>Challan #${index+1}</b><br>

<b>Challan No:</b>
${c.challan_no || c.challan_number || '-'}
<br>

<b>Date:</b>
${c.date || c.challan_date || '-'}
<br>

<b>Status:</b>

<span class="badge bg-danger">
${c.status || c.challan_status || '-'}
</span>

<br>

<b>Amount:</b>
₹${c.amount || '0'}
<br>

<b>Offence:</b>
${c.offence || c.offence_name || '-'}
<br>

<b>Location:</b>
${c.location || c.offence_location || '-'}
<br>

</div>

`;

});

}else{

html += `
<div class="alert alert-warning">
No Challan Found
</div>
`;

}

html += `</div>`;

Swal.fire({
    icon:'success',
    title:'Vehicle Challan Result',
    html:html,
    width:'700px'
});

</script>

<?php endif; ?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<script>

$('#vehicleTable').DataTable({
    order:[[0,'desc']]
});

</script>

<?php include('footer.php'); ?>

</body>
</html>