<?php
// debug_bid.php - Direct Bid Test
// File location: /bidwheels.net/debug_bid.php

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

echo "<h1>Bid Debugger</h1>";

// Test database connection
echo "<h3>1. Testing Database Connection...</h3>";
if ($conn) {
    echo "<span style='color:green'>✅ Database connected successfully</span><br>";
} else {
    echo "<span style='color:red'>❌ Database connection failed: " . mysqli_connect_error() . "</span><br>";
    exit();
}

// Test tables exist
echo "<h3>2. Checking Tables...</h3>";
$tables = ['users', 'products', 'bids', 'payment_methods', 'user_payment_methods', 'bid_payments'];
foreach ($tables as $table) {
    $check = mysqli_query($conn, "SHOW TABLES LIKE '$table'");
    if (mysqli_num_rows($check) > 0) {
        echo "<span style='color:green'>✅ Table '$table' exists</span><br>";
    } else {
        echo "<span style='color:red'>❌ Table '$table' MISSING - Run the SQL file</span><br>";
    }
}

// Test product exists
echo "<h3>3. Checking Product ID=2...</h3>";
$product_id = 2;
$product = fetchOne("SELECT * FROM products WHERE id = $product_id");
if ($product) {
    echo "<span style='color:green'>✅ Product found: " . htmlspecialchars($product['name']) . "</span><br>";
    echo "Starting Price: $" . $product['starting_price'] . "<br>";
    echo "Current Highest Bid: $" . ($product['current_highest_bid'] ?? $product['starting_price']) . "<br>";
} else {
    echo "<span style='color:red'>❌ Product ID $product_id not found</span><br>";
}

// Test dummy users exist
echo "<h3>4. Checking Dummy Users...</h3>";
$dummy_count = getCount('users', "is_dummy = 1");
echo "Total dummy users: $dummy_count<br>";
if ($dummy_count == 0) {
    echo "<span style='color:orange'>⚠️ No dummy users. Run dummy/create_accounts.php first.</span><br>";
}

// Test payment methods
echo "<h3>5. Checking Payment Methods...</h3>";
$payment_methods = fetchAll("SELECT * FROM payment_methods");
if (count($payment_methods) > 0) {
    echo "<span style='color:green'>✅ Payment methods found:</span><br>";
    foreach ($payment_methods as $pm) {
        echo " - " . $pm['method_name'] . " (" . ($pm['is_active'] ? 'Active' : 'Inactive') . ")<br>";
    }
} else {
    echo "<span style='color:red'>❌ No payment methods. Run the SQL file first.</span><br>";
}

// Simulate a bid submission
echo "<h3>6. Testing Bid Submission (Manual Test)...</h3>";

// Test data
$test_email = 'debug_test_' . time() . '@test.com';
$test_bid_amount = $product['starting_price'] + 100;
$test_full_name = 'Debug Tester';
$test_phone = '555-123-4567';
$test_address = '123 Test Street';

echo "Test Email: $test_email<br>";
echo "Test Bid Amount: $" . $test_bid_amount . "<br>";

// Check if user exists
$user = fetchOne("SELECT id FROM users WHERE email = '$test_email'");
if (!$user) {
    echo "Creating test user...<br>";
    $user_id = insert('users', [
        'name' => $test_full_name,
        'email' => $test_email,
        'password' => md5('test123'),
        'phone' => $test_phone,
        'address' => $test_address,
        'role' => 'user',
        'is_dummy' => 0
    ]);
    if ($user_id) {
        echo "<span style='color:green'>✅ Test user created with ID: $user_id</span><br>";
    } else {
        echo "<span style='color:red'>❌ Failed to create test user. MySQL Error: " . mysqli_error($conn) . "</span><br>";
        exit();
    }
} else {
    $user_id = $user['id'];
    echo "Using existing user ID: $user_id<br>";
}

// Insert a test bid
echo "Attempting to insert bid...<br>";
$bid_id = insert('bids', [
    'product_id' => $product_id,
    'user_id' => $user_id,
    'amount' => $test_bid_amount,
    'is_system_bid' => 0
]);

if ($bid_id) {
    echo "<span style='color:green'>✅ Bid inserted successfully! Bid ID: $bid_id</span><br>";
    
    // Update product current highest bid
    update('products', ['current_highest_bid' => $test_bid_amount], "id = $product_id");
    echo "<span style='color:green'>✅ Product highest bid updated to $" . $test_bid_amount . "</span><br>";
} else {
    echo "<span style='color:red'>❌ Failed to insert bid. MySQL Error: " . mysqli_error($conn) . "</span><br>";
}

// Check if bid appears in database
echo "<h3>7. Verifying Bid in Database...</h3>";
$check_bid = fetchOne("SELECT * FROM bids WHERE product_id = $product_id ORDER BY id DESC LIMIT 1");
if ($check_bid) {
    echo "<span style='color:green'>✅ Latest bid in database:</span><br>";
    echo "Bid ID: " . $check_bid['id'] . "<br>";
    echo "Amount: $" . $check_bid['amount'] . "<br>";
    echo "User ID: " . $check_bid['user_id'] . "<br>";
    echo "Time: " . $check_bid['created_at'] . "<br>";
} else {
    echo "<span style='color:red'>❌ No bids found in database!</span><br>";
}

// Check if POST data is being received
echo "<h3>8. Testing POST Data Reception...</h3>";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    echo "<span style='color:green'>✅ POST request detected!</span><br>";
    echo "<strong>Received POST data:</strong><br>";
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";
} else {
    echo "<span style='color:orange'>⚠️ No POST data. This is a GET request.</span><br>";
    echo "To test POST, use the form below.<br>";
}

// Test POST form for bid submission
echo "<h3>9. Manual Test Form (Direct POST to detail.php)</h3>";
?>

<form method="POST" action="product/detail.php?id=2" style="background: #f0f0f0; padding: 20px; border-radius: 10px; margin-top: 10px;">
    <h4>Submit a Test Bid</h4>
    <input type="hidden" name="place_bid" value="1">
    
    <label>Bid Amount:</label>
    <input type="number" name="bid_amount" value="<?php echo $product['starting_price'] + 100; ?>" required><br><br>
    
    <label>Email:</label>
    <input type="email" name="email" value="<?php echo $test_email; ?>" required><br><br>
    
    <label>Full Name:</label>
    <input type="text" name="full_name" value="Test User" required><br><br>
    
    <label>Phone:</label>
    <input type="text" name="phone" value="1234567890" required><br><br>
    
    <label>Address:</label>
    <input type="text" name="address" value="123 Test St"><br><br>
    
    <label>Payment Method:</label>
    <select name="payment_method" required>
        <option value="Credit Card">Credit Card</option>
        <option value="Bank Transfer">Bank Transfer</option>
    </select><br><br>
    
    <div id="cardFields">
        <label>Card Name:</label>
        <input type="text" name="card_name" value="Test Card"><br><br>
        
        <label>Card Number:</label>
        <input type="text" name="card_number" value="4111111111111111"><br><br>
        
        <label>Expiry (MM/YY):</label>
        <input type="text" name="expiry" value="12/28"><br><br>
        
        <label>CVC:</label>
        <input type="text" name="cvc" value="123"><br><br>
        
        <label>Zip Code:</label>
        <input type="text" name="zip_code" value="90210"><br><br>
    </div>
    
    <button type="submit" style="background: #FF8C3E; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">
        Submit Test Bid
    </button>
</form>

<script>
// Show/hide card fields based on payment method
document.querySelector('select[name="payment_method"]')?.addEventListener('change', function() {
    const cardFields = document.getElementById('cardFields');
    if (this.value === 'Bank Transfer') {
        cardFields.innerHTML = `
            <label>Account Name:</label>
            <input type="text" name="account_name" value="Test Account"><br><br>
            <label>Account Number:</label>
            <input type="text" name="account_number" value="123456789"><br><br>
            <label>Bank Name:</label>
            <input type="text" name="bank_name" value="Test Bank"><br><br>
            <label>Routing Number:</label>
            <input type="text" name="routing_number" value="987654321"><br><br>
        `;
    } else {
        cardFields.innerHTML = `
            <label>Card Name:</label>
            <input type="text" name="card_name" value="Test Card"><br><br>
            <label>Card Number:</label>
            <input type="text" name="card_number" value="4111111111111111"><br><br>
            <label>Expiry (MM/YY):</label>
            <input type="text" name="expiry" value="12/28"><br><br>
            <label>CVC:</label>
            <input type="text" name="cvc" value="123"><br><br>
            <label>Zip Code:</label>
            <input type="text" name="zip_code" value="90210"><br><br>
        `;
    }
});
</script>

<?php
echo "<h3>10. PHP Configuration</h3>";
echo "post_max_size: " . ini_get('post_max_size') . "<br>";
echo "upload_max_filesize: " . ini_get('upload_max_filesize') . "<br>";
echo "max_input_vars: " . ini_get('max_input_vars') . "<br>";
echo "display_errors: " . (ini_get('display_errors') ? 'On' : 'Off') . "<br>";
?>