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

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

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

// Validate product ID
if (!isset($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'No product specified']);
    exit;
}
$product_id = intval($_GET['id']);
$qty = isset($_GET['qty']) ? max(1, intval($_GET['qty'])) : 1;

// Ensure product exists
$stmt = $conn->prepare("SELECT id, price, name FROM products WHERE id = ?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$result = $stmt->get_result();
$product = $result->fetch_assoc();
$stmt->close();

if (!$product) {
    echo json_encode(['success' => false, 'message' => 'Invalid product']);
    exit;
}
$price = $product['price'];

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

if ($cart) {
    $cart_id = $cart['id'];
} else {
    if ($user_id) {
        $stmt = $conn->prepare("INSERT INTO carts (user_id, session_token) VALUES (?, ?)");
        $stmt->bind_param("is", $user_id, $session_token);
    } else {
        $stmt = $conn->prepare("INSERT INTO carts (session_token) VALUES (?)");
        $stmt->bind_param("s", $session_token);
    }
    $stmt->execute();
    $cart_id = $stmt->insert_id;
    $stmt->close();
}

// Check if item already in cart
$stmt = $conn->prepare("SELECT id, qty FROM cart_items WHERE cart_id = ? AND product_id = ?");
$stmt->bind_param("ii", $cart_id, $product_id);
$stmt->execute();
$res = $stmt->get_result();
$item = $res->fetch_assoc();
$stmt->close();

if ($item) {
    // Update quantity
    $new_qty = $item['qty'] + $qty;
    $stmt = $conn->prepare("UPDATE cart_items SET qty = ? WHERE id = ?");
    $stmt->bind_param("ii", $new_qty, $item['id']);
    $stmt->execute();
    $stmt->close();
} else {
    // Insert new item
    $stmt = $conn->prepare("INSERT INTO cart_items (cart_id, product_id, qty, price) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("iiid", $cart_id, $product_id, $qty, $price);
    $stmt->execute();
    $stmt->close();
}

// Return success JSON with product info
echo json_encode([
    'success' => true,
    'message' => $product['name'] . ' added to cart',
    'product_id' => $product['id'],
    'in_cart' => true
]);
exit;
