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

// DB connection
$conn = new mysqli("localhost", "kkfxoaad", "Bitok@2025", "kkfxoaad_bella");
if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "DB connection failed"]);
    exit;
}

// ✅ Identify cart (user or guest)
$user_id = $_SESSION['user_id'] ?? null;
$session_token = session_id();

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();
$res = $stmt->get_result();
$cart = $res->fetch_assoc();
$stmt->close();

if (!$cart) {
    echo json_encode([
        "status" => "success",
        "items" => [],
        "cart_count" => 0,
        "cart_total" => 0
    ]);
    exit;
}

$cart_id = $cart['id'];

// ✅ Fetch items in cart
$stmt = $conn->prepare("
    SELECT ci.id, ci.product_id, ci.qty, ci.price,
           p.name, p.image
    FROM cart_items ci
    JOIN products p ON ci.product_id = p.id
    WHERE ci.cart_id = ?
");
$stmt->bind_param("i", $cart_id);
$stmt->execute();
$res = $stmt->get_result();

$items = [];
$total = 0;
$count = 0;

while ($row = $res->fetch_assoc()) {
    $row['subtotal'] = $row['qty'] * $row['price'];
    $total += $row['subtotal'];
    $count += $row['qty'];
    $items[] = $row;
}
$stmt->close();

echo json_encode([
    "status" => "success",
    "items" => $items,
    "cart_count" => $count,
    "cart_total" => $total
]);
