<?php
// /api/protected/cart.php  — GET list | POST add | DELETE remove | PUT update qty
require_once __DIR__ . '/../init.php';

$user   = AuthMiddleware::verifyToken();
$userId = (int)$user['id'];
$db     = DB::conn();
$method = $_SERVER['REQUEST_METHOD'];

// ── Cart stored in user_sessions table via a helper ──────────
// We use a simple JSON cart in a dedicated cart_items table.
// Create it on-the-fly if not exists (safe, idempotent).
$db->exec("CREATE TABLE IF NOT EXISTS `cart_items` (
  `id`         INT AUTO_INCREMENT PRIMARY KEY,
  `user_id`    INT NOT NULL,
  `product_id` INT NOT NULL,
  `qty`        INT NOT NULL DEFAULT 1,
  `added_at`   TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY `uq_user_product` (`user_id`, `product_id`),
  FOREIGN KEY (`user_id`)    REFERENCES `users`(`id`)    ON DELETE CASCADE,
  FOREIGN KEY (`product_id`) REFERENCES `products`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// ── GET — list cart ───────────────────────────────────────────
if ($method === 'GET') {
    $stmt = $db->prepare("
        SELECT c.id, c.qty, c.product_id,
               p.name, p.price, p.image_url, p.stock, p.is_active
        FROM cart_items c
        JOIN products p ON p.id = c.product_id
        WHERE c.user_id = ?
        ORDER BY c.added_at DESC
    ");
    $stmt->execute([$userId]);
    $items = $stmt->fetchAll();

    foreach ($items as &$i) {
        $i['id']         = (int)$i['id'];
        $i['qty']        = (int)$i['qty'];
        $i['product_id'] = (int)$i['product_id'];
        $i['price']      = (float)$i['price'];
        $i['stock']      = (int)$i['stock'];
        $i['is_active']  = (bool)$i['is_active'];
        $i['subtotal']   = round($i['price'] * $i['qty'], 2);
    }

    $total = array_sum(array_column($items, 'subtotal'));
    Response::success('Cart fetched.', ['items' => $items, 'total' => $total, 'count' => count($items)]);
}

// ── POST — add item ────────────────────────────────────────────
if ($method === 'POST') {
    $body      = getBody();
    $productId = (int)($body['product_id'] ?? 0);
    $qty       = max(1, (int)($body['qty'] ?? 1));
    if (!$productId) Response::error('product_id required.');

    // Verify product exists
    $stmt = $db->prepare('SELECT id, stock FROM products WHERE id = ? AND is_active = 1');
    $stmt->execute([$productId]);
    $prod = $stmt->fetch();
    if (!$prod) Response::error('ไม่พบสินค้า', 404);
    if ($prod['stock'] < $qty) Response::error("สินค้าเหลือ {$prod['stock']} ชิ้น", 400);

    // Upsert
    $db->prepare("
        INSERT INTO cart_items (user_id, product_id, qty) VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE qty = LEAST(qty + VALUES(qty), ?)
    ")->execute([$userId, $productId, $qty, $prod['stock']]);

    Response::success('เพิ่มลงตะกร้าแล้ว!', [], 201);
}

// ── PUT — update qty ──────────────────────────────────────────
if ($method === 'PUT') {
    $body      = getBody();
    $productId = (int)($body['product_id'] ?? 0);
    $qty       = max(1, (int)($body['qty'] ?? 1));

    $stmt = $db->prepare('SELECT stock FROM products WHERE id = ? AND is_active = 1');
    $stmt->execute([$productId]);
    $prod = $stmt->fetch();
    if (!$prod) Response::error('ไม่พบสินค้า', 404);
    $qty = min($qty, $prod['stock']);

    $db->prepare('UPDATE cart_items SET qty = ? WHERE user_id = ? AND product_id = ?')
       ->execute([$qty, $userId, $productId]);
    Response::success('อัปเดตแล้ว', ['qty' => $qty]);
}

// ── DELETE — remove item ──────────────────────────────────────
if ($method === 'DELETE') {
    $body      = getBody();
    $productId = (int)($body['product_id'] ?? 0);
    if (!$productId) Response::error('product_id required.');

    $db->prepare('DELETE FROM cart_items WHERE user_id = ? AND product_id = ?')
       ->execute([$userId, $productId]);
    Response::success('ลบออกจากตะกร้าแล้ว');
}

Response::error('Method not allowed.', 405);
