<?php
// Debug script to test order placement
// Generated at: <?php echo time(); ?>

session_start();
header('Content-Type: application/json');

// Log all actions
$log_messages = [];

try {
    // Connect to database
    $conn = new mysqli('localhost', 'zemaraim', '8wwxk]-X3Kx]CJ]5', 'zemaraim_interior');
    if ($conn->connect_error) {
        throw new Exception("DB Connection failed: " . $conn->connect_error);
    }
    $log_messages[] = "✓ Connected to database";
    
    // Set a test user ID
    $test_user_id = 6; // User with cart items
    $_SESSION['user_id'] = $test_user_id;
    $log_messages[] = "✓ Set session user_id = $test_user_id";
    
    // Check if user has cart items
    $cart_check = $conn->prepare("SELECT COUNT(*) as count FROM cart WHERE user_id = ?");
    $cart_check->bind_param("i", $test_user_id);
    $cart_check->execute();
    $result = $cart_check->get_result();
    $row = $result->fetch_assoc();
    $cart_count = $row['count'];
    $log_messages[] = "✓ User has $cart_count cart items";
    
    if ($cart_count == 0) {
        throw new Exception("User has no cart items");
    }
    
    // Now test the order insertion
    $insert_sql = "INSERT INTO orders (
        user_id, first_name, last_name, email, phone,
        billing_country, billing_address, billing_city, billing_postcode,
        shipping_country, shipping_address, shipping_city, shipping_postcode,
        company, order_notes, payment_method, subtotal, tax, shipping, total, status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($insert_sql);
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    $log_messages[] = "✓ Prepared INSERT statement";
    
    // Prepare test data
    $user_id = $test_user_id;
    $first_name = "Test";
    $last_name = "Customer";
    $email = "test@example.com";
    $phone = "1234567890";
    $billing_country = "Pakistan";
    $billing_address = "123 Test Street";
    $billing_city = "Karachi";
    $billing_postcode = "75000";
    $shipping_country = "Pakistan";
    $shipping_address = "123 Test Street";
    $shipping_city = "Karachi";
    $shipping_postcode = "75000";
    $company = "";
    $order_notes = "Test order from debug script";
    $payment_method = "credit_card";
    $subtotal = 5000.00;
    $tax = 500.00;
    $shipping_cost = 500.00;
    $total = 6000.00;
    $status = "pending";
    
    $bind_result = $stmt->bind_param(
        "issssssssssssssdddds",
        $user_id,
        $first_name,
        $last_name,
        $email,
        $phone,
        $billing_country,
        $billing_address,
        $billing_city,
        $billing_postcode,
        $shipping_country,
        $shipping_address,
        $shipping_city,
        $shipping_postcode,
        $company,
        $order_notes,
        $payment_method,
        $subtotal,
        $tax,
        $shipping_cost,
        $total,
        $status
    );
    
    if (!$bind_result) {
        throw new Exception("Bind failed: " . $stmt->error);
    }
    $log_messages[] = "✓ Bound all parameters";
    
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }
    $log_messages[] = "✓ Order insert executed";
    
    $order_id = $conn->insert_id;
    $log_messages[] = "✓ Generated order_id = $order_id";
    
    // Verify the order was actually created
    $verify = $conn->prepare("SELECT id, first_name, total FROM orders WHERE id = ?");
    if (!$verify) {
        throw new Exception("Verify prepare failed: " . $conn->error);
    }
    $verify->bind_param("i", $order_id);
    $verify->execute();
    $verify_result = $verify->get_result();
    
    if ($verify_result->num_rows === 0) {
        throw new Exception("Order was not created in database! order_id = $order_id");
    }
    
    $order_row = $verify_result->fetch_assoc();
    $log_messages[] = "✓ Verified order exists in database: " . $order_row['first_name'] . " - " . $order_row['total'];
    
    // Test clearing cart
    $delete_stmt = $conn->prepare("DELETE FROM cart WHERE user_id = ?");
    if (!$delete_stmt) {
        throw new Exception("Delete prepare failed: " . $conn->error);
    }
    $delete_stmt->bind_param("i", $user_id);
    if (!$delete_stmt->execute()) {
        throw new Exception("Delete execute failed: " . $delete_stmt->error);
    }
    $log_messages[] = "✓ Cart cleared for user";
    
    // Success
    echo json_encode([
        'success' => true,
        'message' => 'All tests passed!',
        'order_id' => $order_id,
        'logs' => $log_messages
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'logs' => $log_messages
    ]);
}
?>
