<?php
ob_start();
// 1. Session & Auth Control
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

require_once('../titancore/titanconfig.php');

// Fix Database Encoding
mysqli_set_charset($conn, "utf8mb4");
mysqli_query($conn, "SET NAMES 'utf8mb4'");
mysqli_query($conn, "SET CHARACTER SET 'utf8mb4'");

require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$u_name = $_SESSION['user_name'] ?? 'User';
$swal_msg = "";

// 2. Pricing Fetch from engine pricing matrix database schema modules
$price_check = $conn->query("SELECT price FROM pricing WHERE service_name = 'vehicle_challan_verify'");
$service_price = ($price_check && $price_check->num_rows > 0) ? $price_check->fetch_assoc()['price'] : 5.00;

// 3. API Config Parameter Values Extraction From Engine Control Settings Database Tables
$api_settings = $conn->query("SELECT titanurl, titan_api_key FROM TitanPayment WHERE id = 1")->fetch_assoc();
$TitanApi_Url = $api_settings['titanurl'] ?? '';
$api_key = $api_settings['titan_api_key'] ?? '';

if (empty($TitanApi_Url) || empty($api_key)) {
    echo "<script>alert('System Error: Configuration options inside table TitanPayment are missing.'); window.location.href='titanhome.php';</script>";
    exit();
}

// 4. Handle Verification Logic Execution Block
if (isset($_POST['find_details_btn'])) {
    $rc_no = strtoupper(preg_replace('/[^A-Z0-9]/', '', $_POST['rc_no']));
    
    // --- SAFE WALLET CHECK REWRITE (FIXES LINE 36 CRASH) ---
    $user_wallet = 0;
    $wallet_column = 'wallet';
    
    $wallet_query = $conn->query("SELECT * FROM users WHERE id = '$uid' LIMIT 1");
    if (!$wallet_query) {
        $wallet_query = $conn->query("SELECT * FROM users WHERE username = '$u_name' OR phone = '$u_name' LIMIT 1");
    }

    if ($wallet_query && $wallet_query->num_rows > 0) {
        $user_row = $wallet_query->fetch_assoc();
        if (isset($user_row['wallet'])) {
            $user_wallet = (float)$user_row['wallet'];
            $wallet_column = 'wallet';
        } elseif (isset($user_row['balance'])) {
            $user_wallet = (float)$user_row['balance'];
            $wallet_column = 'balance';
        }
    }
    // --- END OF SAFE WALLET CHECK REWRITE ---
    
    if (empty($rc_no)) {
        $swal_msg = "Swal.fire('Invalid Input!', 'Please enter a valid Registration Number.', 'error');";
    } elseif ($user_wallet < $service_price) {
        $swal_msg = "Swal.fire('Low Balance!', 'Your wallet balance (₹" . number_format($user_wallet, 2) . ") is insufficient.', 'warning');";
    } else {
        // Enforce safe dynamic routing mapping schema
        $endpoint = "https://maxxapi.site/S1challan.php?api_key=demooo&vehicle_no=" . urlencode($rc_no);
        
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 55);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $api_response = curl_exec($ch);
        $http_response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $api_response_trimmed = trim($api_response);
        
        if (!empty($api_response_trimmed)) {
            $data = json_decode($api_response_trimmed, true);
            
            if (!$data) {
                $raw_output = htmlspecialchars(substr($api_response_trimmed, 0, 350));
                $swal_msg = "Swal.fire('Payload Format Warning!', 'HTTP Code: " . $http_response_code . " <br> Response String: <br><code>" . addslashes($raw_output) . "</code>', 'warning');";
            } else {
                $status = ucfirst(strtolower($data['Status'] ?? $data['status'] ?? ''));
                
                if ($status === 'Success') {
                    // Deduct wallet balance dynamically using identified field type
                    $conn->query("UPDATE users SET $wallet_column = $wallet_column - $service_price WHERE id = '$uid'");
                    
                    $provider = mysqli_real_escape_string($conn, $data['data_source'] ?? 'TitanApi');
                    $txn_id = mysqli_real_escape_string($conn, $data['transaction_id'] ?? uniqid('TXN'));
                    $full_data = mysqli_real_escape_string($conn, json_encode($data, JSON_UNESCAPED_UNICODE));
                    $date_time = date('Y-m-d H:i:s');
                    
                    // Main layout storage execution logic
                    $insert = "INSERT INTO vehicle_challan_history (user_id, username, registration_no, txn_id, provider, full_data, date) 
                               VALUES ('$uid', '$u_name', '$rc_no', '$txn_id', '$provider', '$full_data', '$date_time')";
                    
                    if ($conn->query($insert)) {
                        $conn->query("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
                                      VALUES ('$u_name', '$service_price', (SELECT $wallet_column FROM users WHERE id='$uid'), 'Vehicle Challan Verification', '1', 'Debit')");
                        
                        $total_found = $data['total_challans'] ?? 0;
                        $swal_msg = "Swal.fire('Success!', 'Challan details verified. Total Found: " . $total_found . "', 'success').then(() => { window.location.href='S1challan.php'; });";
                    } else {
                        $swal_msg = "Swal.fire('Database Execution Error!', 'Failed to save entries inside dashboard history tracking tables.', 'warning');";
                    }
                } else {
                    $err = $data['message'] ?? 'The server API returned an explicit negative status validation.';
                    $swal_msg = "Swal.fire('API Error!', '" . addslashes($err) . "', 'error');";
                }
            }
        } else {
            $swal_msg = "Swal.fire('Empty Response Trace!', 'The API file returned nothing. HTTP Status Code: " . $http_response_code . "<br><small>Check challan_api_debug.log inside your API directory for details.</small>', 'error');";
        }
    }
}

// 5. Fetch account verification logs for active dashboard user session
$history = $conn->query("SELECT * FROM vehicle_challan_history WHERE user_id='$uid' ORDER BY id DESC");
?>

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

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <div class="icon-item bg-info-subtle shadow-none me-3">
                        <span class="fas fa-car text-info fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-info fs-10 mb-0">RTO Services</h6>
                        <h4 class="text-primary fw-bold mb-0">Vehicle <span class="text-info fw-medium">Challan Check</span></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-lg-4">
        <div class="card h-100 border shadow-none">
            <div class="card-header bg-light border-bottom">
                <h5 class="mb-0 text-primary fw-bold text-center"><i class="fas fa-search-location me-2"></i>Find Linked Challans</h5>
            </div>
            <div class="card-body bg-body-tertiary p-4">
                <div class="alert alert-info border-0 d-flex align-items-center mb-4">
                    <i class="fas fa-rupee-sign fs-3 me-3 text-info"></i>
                    <p class="mb-0 fs-11">Search charge: <strong>₹<?php echo number_format($service_price, 2); ?></strong> will be deducted from your wallet upon success.</p>
                </div>
                
                <form method="POST">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-900">Vehicle RC Number <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="fas fa-id-card"></i></span>
                            <input type="text" class="form-control shadow-none text-center fw-bold text-uppercase" name="rc_no" placeholder="e.g. PB55E2166" maxlength="15" oninput="this.value=this.value.toUpperCase().replace(/[^A-Z0-9]/g,'')" required>
                        </div>
                    </div>
                    
                    <button class="btn btn-info w-100 fw-bold shadow-none py-2" type="submit" name="find_details_btn">
                        <i class="fas fa-search me-2"></i> Find Details & View
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card h-100 border shadow-none">
            <div class="card-header bg-light border-bottom">
                <h5 class="mb-0 text-primary fw-bold"><i class="fas fa-history me-2"></i>Recent Verifications Log</h5>
            </div>
            <div class="card-body p-3">
                <div class="table-responsive">
                    <table id="vehicleTable" class="table table-bordered table-hover text-center align-middle m-0">
                        <thead class="table-dark">
                            <tr>
                                <th>ID</th>
                                <th>Timestamp Log</th>
                                <th>Registration Number</th>
                                <th>Transaction ID</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($history && $history->num_rows > 0) { 
                                while ($r = $history->fetch_assoc()) { ?>
                                <tr>
                                    <td>#<?= $r['id'] ?></td>
                                    <td><?= date('d M Y h:i A', strtotime($r['date'])) ?></td>
                                    <td class="fw-bold text-primary text-uppercase"><?= htmlspecialchars($r['registration_no']) ?></td>
                                    <td><span class="badge bg-secondary px-2 font-monospace"><?= htmlspecialchars($r['txn_id']) ?></span></td>
                                </tr>
                                <?php } 
                            } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<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 src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        $('#vehicleTable').DataTable({
            "order": [[ 0, "desc" ]]
        });
    });
    <?php echo $swal_msg; ?>
</script>

<?php 
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>