<?php
/**
 * 订单API接口
 */
require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

require_once __DIR__ . '/../core/db/db.php';
require_once __DIR__ . '/../core/lib/common.php';
require_once __DIR__ . '/../core/lib/order_timeout.php';
$db = Core\Db\DB::getInstance();

$action = $_POST['action'] ?? $_GET['action'] ?? '';
$memberId = $_SESSION['member_id'] ?? 0;

\Core\Lib\OrderTimeout::cancelExpiredPendingOrders($db);

if ($memberId <= 0) {
    echo json_encode([
        'code' => 401,
        'msg' => '请先登录',
        'data' => []
    ]);
    exit;
}

if (in_array($action, ['create', 'cancel', 'confirm'], 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 'create':
        $productIds = $_POST['product_ids'] ?? [];
        $quantities = $_POST['quantities'] ?? [];
        $addressId = intval($_POST['address_id'] ?? 0);
        $remark = mb_substr(trim((string) ($_POST['remark'] ?? '')), 0, 500, 'UTF-8');

        if (!is_array($productIds) || !is_array($quantities) || empty($productIds) || count($productIds) !== count($quantities) || count($productIds) > 50 || $addressId <= 0) {
            echo json_encode(['code' => 400, 'msg' => '参数错误']);
            exit;
        }

        $address = $db->fetch("SELECT * FROM {$db->table('address')} WHERE id = ? AND member_id = ?", [$addressId, $memberId]);
        if (!$address) {
            echo json_encode(['code' => 400, 'msg' => '收货地址不存在']);
            exit;
        }

        $products = [];
        $totalPrice = 0;
        foreach ($productIds as $key => $pid) {
            $pid = intval($pid);
            $quantity = intval($quantities[$key] ?? 1);
            if ($pid <= 0 || $quantity <= 0 || $quantity > 999) {
                echo json_encode(['code' => 400, 'msg' => '商品或购买数量不合法'], JSON_UNESCAPED_UNICODE);
                exit;
            }
            $product = $db->fetch("SELECT id, title, litpic, price, stock FROM {$db->table('product')} WHERE id = ? AND status = 1", [$pid]);
            if (!$product) {
                echo json_encode(['code' => 400, 'msg' => "商品ID:{$pid} 不存在或已下架"]);
                exit;
            }
            if ($product['stock'] < $quantity) {
                echo json_encode(['code' => 400, 'msg' => "商品【{$product['title']}】库存不足"]);
                exit;
            }
            $product['quantity'] = $quantity;
            $product['total_price'] = $product['price'] * $quantity;
            $totalPrice += $product['total_price'];
            $products[] = $product;
        }

        if (empty($products)) {
            echo json_encode(['code' => 400, 'msg' => '请选择商品']);
            exit;
        }

        $orderSn = date('YmdHis') . str_pad(mt_rand(1000, 9999), 4, '0', STR_PAD_LEFT);

        $db->beginTransaction();
        try {
            $orderData = [
                'order_sn' => $orderSn,
                'member_id' => $memberId,
                'total_price' => $totalPrice,
                'pay_price' => $totalPrice,
                'status' => 0,
                'name' => $address['name'],
                'mobile' => $address['mobile'],
                'address' => $address['province'] . $address['city'] . $address['district'] . $address['address'],
                'remark' => $remark,
                'create_time' => time(),
                'update_time' => time()
            ];
            $db->insert('order', $orderData);
            $orderId = $db->lastInsertId();

            foreach ($products as $p) {
                $orderProductData = [
                    'order_id' => $orderId,
                    'product_id' => $p['id'],
                    'product_name' => $p['title'],
                    'product_image' => $p['litpic'],
                    'price' => $p['price'],
                    'quantity' => $p['quantity'],
                    'total_price' => $p['total_price']
                ];
                $db->insert('order_product', $orderProductData);
                $stockUpdate = $db->query(
                    "UPDATE {$db->table('product')} SET stock = stock - ? WHERE id = ? AND status = 1 AND stock >= ?",
                    [$p['quantity'], $p['id'], $p['quantity']]
                );
                if ($stockUpdate->rowCount() !== 1) {
                    throw new UnexpectedValueException('商品库存不足，请刷新后重试');
                }
            }

            $pidPlaceholders = implode(',', array_fill(0, count($productIds), '?'));
            $db->query("DELETE FROM {$db->table('cart')} WHERE member_id = ? AND product_id IN ($pidPlaceholders)", array_merge([$memberId], $productIds));

            $db->commit();

            try {
            sendMemberMessage($memberId, '订单提交成功', '您的订单 ' . $orderSn . ' 已提交，订单金额：￥' . number_format($totalPrice, 2) . '。', '订单通知');
            $productNames = array_column($products, 'title');
            $productSummary = implode('、', array_slice($productNames, 0, 3));
            if (count($productNames) > 3) $productSummary .= '...';
            $memberInfo = $db->fetch("SELECT username FROM {$db->table('member')} WHERE id = ?", [$memberId]);
            $msgContent = "用户 {$memberInfo['username']} 提交了订单\n订单号：{$orderSn}\n商品：{$productSummary}\n订单金额：¥{$totalPrice}\n收货人：{$address['name']} {$address['mobile']}\n地址：{$address['province']}{$address['city']}{$address['district']}{$address['address']}";
            sendAdminMessage('📦 新订单：' . $orderSn, $msgContent, $memberInfo['username'] ?? '会员');

            } catch (Throwable $notifyError) {
                error_log('EnterpriseCMS order notification failed: ' . $notifyError->getMessage());
            }

            echo json_encode([
                'code' => 200,
                'msg' => '订单创建成功',
                'data' => [
                    'order_id' => $orderId,
                    'order_sn' => $orderSn
                ]
            ]);
        } catch (UnexpectedValueException $e) {
            if ($db->getPdo()->inTransaction()) { $db->rollBack(); }
            echo json_encode(['code' => 409, 'msg' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
        } catch (Exception $e) {
            if ($db->getPdo()->inTransaction()) { $db->rollBack(); }
            echo json_encode(['code' => 500, 'msg' => '订单创建失败：' . $e->getMessage()]);
        }
        break;

    case 'list':
        $status = intval($_GET['status'] ?? -1);
        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = 10;
        $offset = ($page - 1) * $pageSize;

        $where = " WHERE member_id = ?";
        $params = [$memberId];
        if ($status >= 0) {
            $where .= " AND status = ?";
            $params[] = $status;
        }

        $total = $db->fetch("SELECT COUNT(*) as cnt FROM {$db->table('order')}$where", $params)['cnt'] ?? 0;
        $list = $db->fetchAll("SELECT * FROM {$db->table('order')}$where ORDER BY create_time DESC LIMIT $offset, $pageSize", $params);

        $productsByOrder = [];
        $orderIds = array_map('intval', array_column($list, 'id'));
        if ($orderIds) {
            $placeholders = implode(',', array_fill(0, count($orderIds), '?'));
            $products = $db->fetchAll("SELECT * FROM {$db->table('order_product')} WHERE order_id IN ($placeholders) ORDER BY order_id ASC, id ASC", $orderIds);
            foreach ($products as $product) {
                $productsByOrder[intval($product['order_id'])][] = $product;
            }
        }

        foreach ($list as &$order) {
            $order['products'] = $productsByOrder[intval($order['id'])] ?? [];
            $statusText = [-1 => '已取消', 0 => '待付款', 1 => '已付款', 2 => '已发货', 3 => '已完成', 4 => '已取消'];
            $order['status_text'] = $statusText[intval($order['status'])] ?? '未知状态';
        }
        unset($order);

        echo json_encode(['code' => 200,'msg' => '获取成功','data' => ['list' => $list,'total' => $total,'page' => $page,'page_size' => $pageSize,'total_page' => ceil($total / $pageSize)]]);
        break;

    case 'detail':
        $orderId = intval($_GET['order_id'] ?? 0);
        if ($orderId <= 0) { echo json_encode(['code' => 400, 'msg' => '参数错误']); exit; }
        $order = $db->fetch("SELECT * FROM {$db->table('order')} WHERE id = ? AND member_id = ?", [$orderId, $memberId]);
        if (!$order) { echo json_encode(['code' => 400, 'msg' => '订单不存在']); exit; }
        $order['products'] = $db->fetchAll("SELECT * FROM {$db->table('order_product')} WHERE order_id = ?", [$orderId]);
        $statusText = [-1 => '已取消', 0 => '待付款', 1 => '已付款', 2 => '已发货', 3 => '已完成', 4 => '已取消'];
        $order['status_text'] = $statusText[intval($order['status'])] ?? '未知状态';
        echo json_encode(['code' => 200,'msg' => '获取成功','data' => $order]);
        break;

    case 'cancel':
        $orderId = intval($_POST['order_id'] ?? 0);
        if ($orderId <= 0) { echo json_encode(['code' => 400, 'msg' => '参数错误']); exit; }
        $order = $db->fetch("SELECT id, status FROM {$db->table('order')} WHERE id = ? AND member_id = ?", [$orderId, $memberId]);
        if (!$order) { echo json_encode(['code' => 400, 'msg' => '订单不存在']); exit; }
        if ($order['status'] != 0) { echo json_encode(['code' => 400, 'msg' => '订单状态不允许取消']); exit; }
        try {
            if (!\Core\Lib\OrderTimeout::cancelPendingOrder($db, $orderId)) {
                echo json_encode(['code' => 400, 'msg' => '订单状态不允许取消']);
                exit;
            }
            echo json_encode(['code' => 200, 'msg' => '取消成功']);
        } catch (Exception $e) {
            echo json_encode(['code' => 500, 'msg' => '取消失败：' . $e->getMessage()]);
        }
        break;

    case 'confirm':
        $orderId = intval($_POST['order_id'] ?? 0);
        if ($orderId <= 0) { echo json_encode(['code' => 400, 'msg' => '参数错误']); exit; }
        $order = $db->fetch("SELECT id, status FROM {$db->table('order')} WHERE id = ? AND member_id = ?", [$orderId, $memberId]);
        if (!$order) { echo json_encode(['code' => 400, 'msg' => '订单不存在']); exit; }
        if ($order['status'] != 2) { echo json_encode(['code' => 400, 'msg' => '订单状态不允许确认收货']); exit; }
        $db->update('order', ['status' => 3, 'complete_time' => time(), 'finish_time' => time(), 'update_time' => time()], 'id = ?', [$orderId]);
        echo json_encode(['code' => 200, 'msg' => '确认收货成功']);
        break;

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