<?php
include("config.php");

// For CLI or browser output
$isCLI = (php_sapi_name() === 'cli');

// Function to output messages in appropriate format
function output($message) {
    global $isCLI;
    if ($isCLI) {
        echo $message . "\n";
    } else {
        echo $message . "<br>";
    }
}

output("== Direct Database Insertion Test ==");

// Create unique test data
$testHWID = "TEST_DIRECT_" . time();
$testUsername = "vax123_direct";

output("Test HWID: " . $testHWID);
output("Test Username: " . $testUsername);

// Start transaction
mysqli_begin_transaction($condb);

try {
    // Insert directly with prepared statement
    $insertQuery = "INSERT INTO logs (hwid, username, Passwords, CreditCards, Cookies, last_updated) 
                    VALUES (?, ?, 5, 2, 10, NOW())";
    $stmt = mysqli_prepare($condb, $insertQuery);
    mysqli_stmt_bind_param($stmt, "ss", $testHWID, $testUsername);
    
    output("Executing direct SQL insertion...");
    $result = mysqli_stmt_execute($stmt);
    
    if (!$result) {
        throw new Exception("Insertion failed: " . mysqli_error($condb));
    }
    
    $insertedId = mysqli_insert_id($condb);
    output("Inserted record ID: " . $insertedId);
    
    // Check what was actually inserted
    $checkQuery = "SELECT * FROM logs WHERE id_log = ?";
    $stmt = mysqli_prepare($condb, $checkQuery);
    mysqli_stmt_bind_param($stmt, "i", $insertedId);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if ($row = mysqli_fetch_assoc($result)) {
        output("Retrieved record:");
        output("- HWID: " . $row['hwid']);
        output("- Username: " . $row['username']);
        
        if ($row['username'] === $testUsername) {
            output("SUCCESS: Username matches!");
        } else {
            output("ERROR: Username doesn't match! Expected '$testUsername', got '" . $row['username'] . "'");
            
            // Check if there's a trigger
            output("Checking for database triggers that might modify the username...");
            $triggerQuery = "SHOW TRIGGERS";
            $triggerResult = mysqli_query($condb, $triggerQuery);
            
            if (mysqli_num_rows($triggerResult) > 0) {
                output("Found triggers:");
                while ($triggerRow = mysqli_fetch_assoc($triggerResult)) {
                    output("- " . $triggerRow['Trigger'] . " on " . $triggerRow['Table'] . " (" . $triggerRow['Timing'] . " " . $triggerRow['Event'] . ")");
                    output("  Statement: " . $triggerRow['Statement']);
                }
            } else {
                output("No triggers found in the database.");
            }
        }
    } else {
        output("ERROR: Couldn't retrieve the inserted record!");
    }
    
    // Commit transaction
    output("Committing transaction...");
    mysqli_commit($condb);
    
    // Now check if other tables have similar issues
    output("Checking users table...");
    
    // Create a test user
    $testUserQuery = "INSERT INTO users (username, password) VALUES (?, 'test123')";
    $stmt = mysqli_prepare($condb, $testUserQuery);
    mysqli_stmt_bind_param($stmt, "s", $testUsername);
    mysqli_stmt_execute($stmt);
    
    $userId = mysqli_insert_id($condb);
    output("Inserted test user with ID: " . $userId);
    
    // Check what was saved
    $checkUserQuery = "SELECT * FROM users WHERE id_user = ?";
    $stmt = mysqli_prepare($condb, $checkUserQuery);
    mysqli_stmt_bind_param($stmt, "i", $userId);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if ($row = mysqli_fetch_assoc($result)) {
        output("Retrieved user record:");
        output("- ID: " . $row['id_user']);
        output("- Username: " . $row['username']);
        
        if ($row['username'] === $testUsername) {
            output("SUCCESS: User username matches!");
        } else {
            output("ERROR: User username doesn't match! Expected '$testUsername', got '" . $row['username'] . "'");
        }
    }
    
    // Clean up test data
    output("Cleaning up test data...");
    
    $deleteLogQuery = "DELETE FROM logs WHERE hwid = ?";
    $stmt = mysqli_prepare($condb, $deleteLogQuery);
    mysqli_stmt_bind_param($stmt, "s", $testHWID);
    mysqli_stmt_execute($stmt);
    
    $deleteUserQuery = "DELETE FROM users WHERE id_user = ?";
    $stmt = mysqli_prepare($condb, $deleteUserQuery);
    mysqli_stmt_bind_param($stmt, "i", $userId);
    mysqli_stmt_execute($stmt);
    
    output("Test complete.");
    
} catch (Exception $e) {
    // Rollback on error
    mysqli_rollback($condb);
    output("ERROR: " . $e->getMessage());
}
?> 