<?php
/**
 * 芋头CMS - 购物车API
 */
session_start();

if (!defined('ROOT_PATH')) define('ROOT_PATH', dirname(__DIR__) . '/');
define('CORE_PATH', ROOT_PATH . 'core/');

require_once CORE_PATH . 'db/db.php';
$db = \Core\Db\DB::getInstance();

header('Content-Type: application/json; charset=utf-8');

$action = isset($_POST['action']) ? trim($_POST['action']) : (isset($_GET['action']) ? trim($_GET['action']) : '');

// 登录检查
$memberId = isset($_SESSION['member_id']) ? intval($_SESSION['member_id']) : 0;
if ($memberId <= 0) {
    echo json_encode(['code' => 401, 'msg' => '请先登录']);
    exit;
}

switch ($action) {
    case 'add':
        $productId = intval($_POST['product_id'] ?? 0);
        $quantity = max(1, intval($_POST['quantity'] ?? 1));
        if ($productId <= 0) { echo json_encode(['code' => 400, 'msg' => '产品ID无效']); exit; }
        $product = $db->fetch("SELECT id, title, price, stock, status FROM {$db->table('product')} WHERE id = ?", [$productId]);
        if (!$product || $product['status'] != 1) { echo json_encode(['code' => 404, 'msg' => '产品不存在或已下架']); exit; }
        if ($product['stock'] < $quantity) { echo json_encode(['code' => 400, 'msg' => '库存不足']); exit; }
        // 检查购物车已有
        $exist = $db->fetch("SELECT id, quantity FROM {$db->table('cart')} WHERE member_id = ? AND product_id = ?", [$memberId, $productId]);
        if ($exist) {
            $newQty = $exist['quantity'] + $quantity;
            if ($newQty > $product['stock']) $newQty = $product['stock'];
            $db->update('cart', ['quantity' => $newQty], 'id = ?', [$exist['id']]);
        } else {
            $db->insert('cart', [
                'member_id' => $memberId,
                'product_id' => $productId,
                'quantity' => $quantity,
                'create_time' => time()
            ]);
        }
        $count = $db->fetch("SELECT SUM(quantity) as cnt FROM {$db->table('cart')} WHERE member_id = ?", [$memberId])['cnt'];
        echo json_encode(['code' => 200, 'msg' => '加入购物车成功', 'data' => ['count' => intval($count ?: 0)]]);
        break;

    case 'list':
        $items = $db->fetchAll("SELECT c.*, p.title, p.litpic, p.price as product_price, p.stock FROM {$db->table('cart')} c LEFT JOIN {$db->table('product')} p ON c.product_id = p.id WHERE c.member_id = ? ORDER BY c.create_time DESC", [$memberId]);
        $total = 0;
        foreach ($items as &$item) {
            $item['subtotal'] = $item['product_price'] * $item['quantity'];
            $total += $item['subtotal'];
        }
        echo json_encode(['code' => 200, 'data' => ['items' => $items, 'total' => $total]]);
        break;

    case 'update':
        $cartId = intval($_POST['cart_id'] ?? 0);
        $quantity = max(1, intval($_POST['quantity'] ?? 1));
        $db->update('cart', ['quantity' => $quantity], 'id = ? AND member_id = ?', [$cartId, $memberId]);
        echo json_encode(['code' => 200, 'msg' => '更新成功']);
        break;

    case 'remove':
        $cartId = intval($_POST['cart_id'] ?? 0);
        $db->query("DELETE FROM {$db->table('cart')} WHERE id = ? AND member_id = ?", [$cartId, $memberId]);
        echo json_encode(['code' => 200, 'msg' => '已移除']);
        break;

    case 'clear':
        $db->query("DELETE FROM {$db->table('cart')} WHERE member_id = ?", [$memberId]);
        echo json_encode(['code' => 200, 'msg' => '已清空']);
        break;

    case 'count':
        $count = $db->fetch("SELECT SUM(quantity) as cnt FROM {$db->table('cart')} WHERE member_id = ?", [$memberId])['cnt'];
        echo json_encode(['code' => 200, 'data' => ['count' => intval($count ?: 0)]]);
        break;

    default:
        echo json_encode(['code' => 400, 'msg' => '未知操作']);
}