<?php
/**
 * 订单API接口
 */
session_start();
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/license.php';
require_once __DIR__ . '/../core/lib/license_guard.php';
$db = Core\Db\DB::getInstance();
$license = new \Core\Lib\License();

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

if (!\Core\Lib\LicenseGuard::hasFeature('order_product', $license)) {
    echo json_encode([
        'code' => 403,
        'msg' => \Core\Lib\LicenseGuard::getDeniedMessage('order_product', $license, '当前授权不支持订单功能'),
        'data' => []
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

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

switch ($action) {
    // 创建订单
    case 'create':
        $productIds = $_POST['product_ids'] ?? [];
        $quantities = $_POST['quantities'] ?? [];
        $addressId = intval($_POST['address_id'] ?? 0);
        $remark = trim($_POST['remark'] ?? '');

        if (empty($productIds) || empty($quantities) || $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);
            $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);

                // 扣减库存
                $db->query("UPDATE {$db->table('product')} SET stock = stock - ? WHERE id = ?", [$p['quantity'], $p['id']]);
            }

            // 清空购物车中已下单的商品
            $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();

            // 发送站内消息通知管理员
            $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']}";
            require_once CORE_PATH . 'lib/common.php';
            sendAdminMessage('📦 新订单：' . $orderSn, $msgContent, $memberInfo['username'] ?? '会员');

            echo json_encode([
                'code' => 200,
                'msg' => '订单创建成功',
                'data' => [
                    'order_id' => $orderId,
                    'order_sn' => $orderSn
                ]
            ]);
        } catch (Exception $e) {
            // 回滚事务
            $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);

        foreach ($list as &$order) {
            // 获取订单商品
            $order['products'] = $db->fetchAll("SELECT * FROM {$db->table('order_product')} WHERE order_id = ?", [$order['id']]);
            // 状态文本
            $statusText = ['待付款', '已付款', '已发货', '已完成', '已取消'];
            $order['status_text'] = $statusText[$order['status']] ?? '未知状态';
        }

        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 = ['待付款', '已付款', '已发货', '已完成', '已取消'];
        $order['status_text'] = $statusText[$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;
        }

        // 开启事务
        $db->beginTransaction();
        try {
            // 更新订单状态
            $db->update('order', ['status' => 4, 'update_time' => time()], 'id = ?', [$orderId]);

            // 恢复库存
            $products = $db->fetchAll("SELECT product_id, quantity FROM {$db->table('order_product')} WHERE order_id = ?", [$orderId]);
            foreach ($products as $p) {
                $db->query("UPDATE {$db->table('product')} SET stock = stock + ? WHERE id = ?", [$p['quantity'], $p['product_id']]);
            }

            // 提交事务
            $db->commit();

            echo json_encode(['code' => 200, 'msg' => '取消成功']);
        } catch (Exception $e) {
            $db->rollBack();
            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, 'finish_time' => time(), 'update_time' => time()], 'id = ?', [$orderId]);
        echo json_encode(['code' => 200, 'msg' => '确认成功']);
        break;

    // 支付回调（由payment.php内部处理后跳转调用）
    case 'pay_notify':
        $orderId = intval($_POST['order_id'] ?? 0);
        $tradeNo = trim($_POST['trade_no'] ?? '');
        
        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;
        }
        
        if ($order['status'] != 0) {
            echo json_encode(['code' => 200, 'msg' => '订单已支付']);
            exit;
        }
        
        $db->update('order', [
            'status' => 1,
            'pay_time' => time(),
            'update_time' => time()
        ], 'id = ?', [$orderId]);
        
        echo json_encode(['code' => 200, 'msg' => '支付成功']);
        break;

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