<?php
/**
 * اختبار مباشر للـ Cart API
 */

echo "<h1>اختبار مباشر - إضافة للسلة</h1>";

// Test 1: Direct API call
echo "<h2>Test 1: استدعاء مباشر للـ API</h2>";

$url = 'http://localhost/KL/backend/api/cart/add.php';
$data = array(
    'product_id' => 1,
    'quantity' => 1
);

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded/r/n" .
                     "X-Requested-With: XMLHttpRequest/r/n" .
                     "Cookie: " . (isset($_SERVER['HTTP_COOKIE']) ? $_SERVER['HTTP_COOKIE'] : '') . "/r/n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);

$context  = stream_context_create($options);
$result = @file_get_contents($url, false, $context);

if ($result === FALSE) {
    echo "<p style='color: red;'>❌ فشل الاتصال بالـ API</p>";
    echo "<pre>";
    print_r(error_get_last());
    echo "</pre>";
} else {
    echo "<p style='color: green;'>✅ نجح الاتصال</p>";
    echo "<h3>Response:</h3>";
    echo "<pre>" . htmlspecialchars($result) . "</pre>";
    
    $json = json_decode($result, true);
    if ($json) {
        echo "<h3>Parsed JSON:</h3>";
        echo "<pre>";
        print_r($json);
        echo "</pre>";
    }
}

// Test 2: Check if products exist
echo "<hr><h2>Test 2: فحص المنتجات</h2>";

require_once 'config/database.php';
$database = new Database();
$conn = $database->getConnection();

try {
    $query = "SELECT id, name, price, stock_quantity FROM products LIMIT 5";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (count($products) > 0) {
        echo "<p style='color: green;'>✅ يوجد " . count($products) . " منتجات</p>";
        echo "<table border='1' cellpadding='5'>";
        echo "<tr><th>ID</th><th>Name</th><th>Price</th><th>Stock</th></tr>";
        foreach ($products as $p) {
            echo "<tr>";
            echo "<td>{$p['id']}</td>";
            echo "<td>{$p['name']}</td>";
            echo "<td>{$p['price']}</td>";
            echo "<td>{$p['stock_quantity']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p style='color: red;'>❌ لا توجد منتجات!</p>";
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>خطأ: " . $e->getMessage() . "</p>";
}

// Test 3: Check cart table
echo "<hr><h2>Test 3: فحص جدول السلة</h2>";

try {
    $query = "SELECT COUNT(*) FROM cart";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $count = $stmt->fetchColumn();
    
    echo "<p>عدد العناصر في جدول cart: <strong>$count</strong></p>";
    
    if ($count > 0) {
        $query = "SELECT c.*, p.name FROM cart c LEFT JOIN products p ON c.product_id = p.id LIMIT 10";
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo "<table border='1' cellpadding='5'>";
        echo "<tr><th>ID</th><th>User ID</th><th>Product</th><th>Quantity</th><th>Created</th></tr>";
        foreach ($items as $item) {
            echo "<tr>";
            echo "<td>{$item['id']}</td>";
            echo "<td>{$item['user_id']}</td>";
            echo "<td>{$item['name']}</td>";
            echo "<td>{$item['quantity']}</td>";
            echo "<td>{$item['created_at']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
} catch (Exception $e) {
    echo "<p style='color: red;'>خطأ: " . $e->getMessage() . "</p>";
}

// Test 4: Session info
echo "<hr><h2>Test 4: معلومات الجلسة</h2>";
session_start();
echo "<pre>";
print_r($_SESSION);
echo "</pre>";

if (!isset($_SESSION['user_id'])) {
    echo "<p style='color: orange;'>⚠️ لم تسجل الدخول - سيتم استخدام guest cart</p>";
}
?>

<hr>
<h2>اختبار يدوي</h2>
<button onclick="testAddToCart()" style="padding: 15px 30px; font-size: 16px; background: #E57393; color: white; border: none; border-radius: 8px; cursor: pointer;">
    اختبر إضافة منتج للسلة
</button>

<div id="result" style="margin-top: 20px; padding: 15px; border-radius: 8px; display: none;"></div>

<script>
function testAddToCart() {
    const resultDiv = document.getElementById('result');
    resultDiv.style.display = 'block';
    resultDiv.style.background = '#e7f3ff';
    resultDiv.innerHTML = '⏳ جاري الإضافة...';
    
    fetch('api/cart/add.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: 'product_id=1&quantity=1'
    })
    .then(response => {
        console.log('Response status:', response.status);
        return response.text();
    })
    .then(text => {
        console.log('Response text:', text);
        resultDiv.innerHTML = '<h3>Response:</h3><pre>' + text + '</pre>';
        
        try {
            const data = JSON.parse(text);
            if (data.success) {
                resultDiv.style.background = '#d4edda';
                resultDiv.innerHTML += '<p style="color: green; font-weight: bold;">✅ نجح!</p>';
                resultDiv.innerHTML += '<p>Cart Count: ' + (data.cart_count || 'N/A') + '</p>';
            } else {
                resultDiv.style.background = '#f8d7da';
                resultDiv.innerHTML += '<p style="color: red; font-weight: bold;">❌ فشل!</p>';
                resultDiv.innerHTML += '<p>Message: ' + (data.message || 'N/A') + '</p>';
            }
        } catch (e) {
            resultDiv.style.background = '#fff3cd';
            resultDiv.innerHTML += '<p style="color: orange;">⚠️ Response is not valid JSON</p>';
        }
    })
    .catch(error => {
        console.error('Error:', error);
        resultDiv.style.background = '#f8d7da';
        resultDiv.innerHTML = '<p style="color: red;">❌ خطأ: ' + error.message + '</p>';
    });
}
</script>
