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

$host = "localhost";
$user = "kkfxoaad";
$pass = "Bitok@2025";
$db   = "kkfxoaad_bella";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['error' => 'DB connection failed']);
    exit;
}

$user_id = $_SESSION['user_id'] ?? null;
$session_token = session_id();

// Fetch all products
$sql = "SELECT id, name, price, image, slug FROM products";
$result = $conn->query($sql);

if (!$result) {
    http_response_code(500);
    echo json_encode(['error' => 'SQL error: ' . $conn->error]);
    $conn->close();
    exit;
}

$products = [];
while ($row = $result->fetch_assoc()) {
    $row['in_cart'] = false;
    // Check if product is in cart
    if ($user_id) {
        $stmt = $conn->prepare("SELECT id FROM carts WHERE user_id=?");
        $stmt->bind_param("i", $user_id);
    } else {
        $stmt = $conn->prepare("SELECT id FROM carts WHERE session_token=?");
        $stmt->bind_param("s", $session_token);
    }
    $stmt->execute();
    $cart_res = $stmt->get_result();
    $cart = $cart_res->fetch_assoc();
    $stmt->close();

    if ($cart) {
        $cart_id = $cart['id'];
        $stmt = $conn->prepare("SELECT id FROM cart_items WHERE cart_id=? AND product_id=?");
        $stmt->bind_param("ii", $cart_id, $row['id']);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($res->num_rows > 0) {
            $row['in_cart'] = true;
        }
        $stmt->close();
    }

    $products[] = $row;
}

echo json_encode($products);
$conn->close();
?>
