<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */
require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();

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

require_once CORE_PATH . 'db/db.php';
require_once CORE_PATH . 'lib/common.php';
require_once CORE_PATH . 'lib/product_spec.php';
$db = \Core\Db\DB::getInstance();
\Core\Lib\ProductSpec::ensureCartColumn($db);

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;
}

if (in_array($action, ['add', 'update', 'remove', 'clear'], true)) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['code' => 405, 'msg' => '该操作只允许 POST 请求'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    requireMemberCsrfToken(true);
}

switch ($action) {
    case 'add':
        $productId = intval($_POST['product_id'] ?? 0);
        $quantity = max(1, min(999, intval($_POST['quantity'] ?? 1)));
        $specSelection = $_POST['spec_selection'] ?? ($_POST['specs'] ?? '');
        if ($productId <= 0) {
            echo json_encode(['code' => 400, 'msg' => '产品ID无效']);
            exit;
        }

        $product = $db->fetch(
            "SELECT id, title, price, stock, status, specs FROM {$db->table('product')} WHERE id = ?",
            [$productId]
        );
        if (!$product || intval($product['status']) !== 1) {
            echo json_encode(['code' => 404, 'msg' => '产品不存在或已下架']);
            exit;
        }
        if (intval($product['stock']) < $quantity) {
            echo json_encode(['code' => 400, 'msg' => '库存不足']);
            exit;
        }
        $specText = \Core\Lib\ProductSpec::selectionText($product['specs'] ?? '', $specSelection);
        if (\Core\Lib\ProductSpec::requiredMessage($product['specs'] ?? '') !== '' && $specText === '') {
            echo json_encode(['code' => 400, 'msg' => '请选择商品规格'], JSON_UNESCAPED_UNICODE);
            exit;
        }

        $exist = $db->fetch(
            "SELECT id, quantity FROM {$db->table('cart')} WHERE member_id = ? AND product_id = ? AND specs = ?",
            [$memberId, $productId, $specText]
        );
        if ($exist) {
            $newQty = intval($exist['quantity']) + $quantity;
            if ($newQty > intval($product['stock'])) {
                $newQty = intval($product['stock']);
            }
            $db->update(
                'cart',
                [
                    'quantity' => $newQty,
                    'price' => $product['price'],
                ],
                'id = ?',
                [intval($exist['id'])]
            );
        } else {
            $db->insert('cart', [
                'member_id' => $memberId,
                'product_id' => $productId,
                'specs' => $specText,
                'quantity' => $quantity,
                'price' => $product['price'],
                'create_time' => time(),
            ]);
        }

        $countRow = $db->fetch(
            "SELECT SUM(quantity) AS cnt FROM {$db->table('cart')} WHERE member_id = ?",
            [$memberId]
        );
        echo json_encode([
            'code' => 200,
            'msg' => '加入购物车成功',
            'data' => ['count' => intval($countRow['cnt'] ?? 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) {
            $unitPrice = isset($item['product_price']) ? floatval($item['product_price']) : floatval($item['price'] ?? 0);
            $item['subtotal'] = $unitPrice * intval($item['quantity']);
            $total += $item['subtotal'];
        }
        unset($item);
        echo json_encode(['code' => 200, 'data' => ['items' => $items, 'total' => $total]]);
        break;

    case 'update':
        $cartId = intval($_POST['cart_id'] ?? 0);
        $quantity = max(1, min(999, intval($_POST['quantity'] ?? 1)));
        if ($cartId <= 0) {
            echo json_encode(['code' => 400, 'msg' => '购物车ID无效']);
            exit;
        }

        $cart = $db->fetch(
            "SELECT c.id, c.product_id, p.stock, p.price
             FROM {$db->table('cart')} c
             LEFT JOIN {$db->table('product')} p ON c.product_id = p.id
             WHERE c.id = ? AND c.member_id = ?",
            [$cartId, $memberId]
        );
        if (!$cart) {
            echo json_encode(['code' => 404, 'msg' => '购物车记录不存在']);
            exit;
        }
        if (intval($cart['stock']) <= 0) {
            echo json_encode(['code' => 409, 'msg' => '商品库存不足'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        if ($quantity > intval($cart['stock'])) {
            $quantity = intval($cart['stock']);
        }

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

    case 'remove':
        $cartId = intval($_POST['cart_id'] ?? 0);
        if ($cartId <= 0) {
            echo json_encode(['code' => 400, 'msg' => '购物车ID无效']);
            exit;
        }
        $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':
        $countRow = $db->fetch(
            "SELECT SUM(quantity) AS cnt FROM {$db->table('cart')} WHERE member_id = ?",
            [$memberId]
        );
        echo json_encode(['code' => 200, 'data' => ['count' => intval($countRow['cnt'] ?? 0)]]);
        break;

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