<?php
/**
 * Cart AJAX Handler API
 * CMTC Shopping
 */
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../functions/helpers.php';

if (!isset($_SESSION['user_id'])) {
    api_response(false, "กรุณาเข้าสู่ระบบก่อนทำรายการ", [], 401);
}

$database = new Database();
$db = $database->getConnection();

$action = $_POST['action'] ?? '';

// Get or Create Cart ID for this user
$stmt_cart = $db->prepare("SELECT id FROM carts WHERE user_id = ? LIMIT 1");
$stmt_cart->execute([$_SESSION['user_id']]);
$cart = $stmt_cart->fetch();

if (!$cart) {
    $stmt_new_cart = $db->prepare("INSERT INTO carts (user_id) VALUES (?)");
    $stmt_new_cart->execute([$_SESSION['user_id']]);
    $cart_id = $db->lastInsertId();
} else {
    $cart_id = $cart['id'];
}

if ($action === 'add') {
    $product_id = intval($_POST['product_id'] ?? 0);
    $color_id = !empty($_POST['color_id']) ? intval($_POST['color_id']) : null;
    $size_id = !empty($_POST['size_id']) ? intval($_POST['size_id']) : null;
    $qty = intval($_POST['quantity'] ?? 1);

    if ($product_id <= 0 || $qty <= 0) {
        api_response(false, "ข้อมูลไม่ถูกต้อง");
    }

    // Verify stock availability (Bypassed for testing/always allow adding to cart)
    $stmt_stock = $db->prepare("
        SELECT quantity FROM product_stock 
        WHERE product_id = ? AND (color_id = ? OR (color_id IS NULL AND ? IS NULL)) AND (size_id = ? OR (size_id IS NULL AND ? IS NULL)) 
        LIMIT 1
    ");
    $stmt_stock->execute([$product_id, $color_id, $color_id, $size_id, $size_id]);
    $stock_qty = $stmt_stock->fetchColumn();

    // Check if item already exists in cart
    $stmt_item = $db->prepare("
        SELECT id, quantity FROM cart_items 
        WHERE cart_id = ? AND product_id = ? AND (color_id = ? OR (color_id IS NULL AND ? IS NULL)) AND (size_id = ? OR (size_id IS NULL AND ? IS NULL))
        LIMIT 1
    ");
    $stmt_item->execute([$cart_id, $product_id, $color_id, $color_id, $size_id, $size_id]);
    $existing = $stmt_item->fetch();

    if ($existing) {
        $new_qty = $existing['quantity'] + $qty;
        $stmt_upd = $db->prepare("UPDATE cart_items SET quantity = ? WHERE id = ?");
        $stmt_upd->execute([$new_qty, $existing['id']]);
    } else {
        $stmt_ins = $db->prepare("
            INSERT INTO cart_items (cart_id, product_id, color_id, size_id, quantity) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt_ins->execute([$cart_id, $product_id, $color_id, $size_id, $qty]);
    }

    api_response(true, "เพิ่มสินค้าลงตะกร้าสินค้าสำเร็จ");
}

if ($action === 'remove') {
    $item_id = intval($_POST['item_id'] ?? 0);
    $stmt_del = $db->prepare("DELETE FROM cart_items WHERE id = ? AND cart_id = ?");
    $stmt_del->execute([$item_id, $cart_id]);
    api_response(true, "ลบสินค้าสำเร็จ");
}

if ($action === 'update_qty') {
    $item_id = intval($_POST['item_id'] ?? 0);
    $qty = intval($_POST['quantity'] ?? 1);

    if ($qty <= 0) {
        api_response(false, "จำนวนต้องมากกว่า 0");
    }

    // Check stock level first (Bypassed for testing)
    $stmt_item = $db->prepare("SELECT product_id, color_id, size_id FROM cart_items WHERE id = ? AND cart_id = ? LIMIT 1");
    $stmt_item->execute([$item_id, $cart_id]);
    $item = $stmt_item->fetch();

    if (!$item) {
        api_response(false, "ไม่พบรายการสินค้าในตะกร้า");
    }

    $stmt_upd = $db->prepare("UPDATE cart_items SET quantity = ? WHERE id = ? AND cart_id = ?");
    $stmt_upd->execute([$qty, $item_id, $cart_id]);
    api_response(true, "อัปเดตจำนวนสินค้าสำเร็จ");
}

api_response(false, "การร้องขอไม่ถูกต้อง");
?>
