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

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

// Get cart ID
$cart_id = null;
if ($user_id) {
    $stmt = $conn->prepare("SELECT id FROM carts WHERE user_id=:uid LIMIT 1");
    $stmt->execute([':uid' => $user_id]);
} else {
    $stmt = $conn->prepare("SELECT id FROM carts WHERE session_token=:token LIMIT 1");
    $stmt->execute([':token' => $session_token]);
}
$cart = $stmt->fetch(PDO::FETCH_ASSOC);
if ($cart) $cart_id = $cart['id'];

// Products already in cart
$in_cart_ids = [];
if ($cart_id) {
    $stmt = $conn->prepare("SELECT product_id FROM cart_items WHERE cart_id=:cid");
    $stmt->execute([':cid' => $cart_id]);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $in_cart_ids[] = (int)$row['product_id'];
    }
}

// Fetch products - include all necessary fields
$stmt = $conn->prepare("
    SELECT 
        id, name, sku, category, price, brand, gender, sizes, colors, material,
        image, images, description, initial_stock, total_sold, remaining_stock, sold_quantity, stock
    FROM products
    ORDER BY name ASC
");
$stmt->execute();

$products = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Decode JSON fields to arrays
    $row['sizes'] = $row['sizes'] ? json_decode($row['sizes'], true) : [];
    $row['colors'] = $row['colors'] ? json_decode($row['colors'], true) : [];
    $row['images'] = $row['images'] ? json_decode($row['images'], true) : [];
    
    $row['in_cart'] = in_array((int)$row['id'], $in_cart_ids);
    $products[] = $row;
}

echo json_encode($products);
