<?php
if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(__DIR__, 2) . '/');
}

require_once ROOT_PATH . 'core/lib/license.php';
require_once ROOT_PATH . 'core/lib/module_loader.php';

$licenseObj = new \Core\Lib\License();
$readonlyMode = !$licenseObj->canUseOrder();
$premiumFile = ROOT_PATH . 'modules-premium/pro/order/index.php';

function ytOrderPayTypeName($payType, $payPrice)
{
    $payType = intval($payType);
    if ($payType === 1) {
        return ['微信', 'badge-primary'];
    }
    if ($payType === 2) {
        return ['支付宝', 'badge-primary'];
    }
    if ($payType === 3) {
        return ['余额', 'badge-primary'];
    }
    return [floatval($payPrice) > 0 ? '未支付' : '-', 'badge-gray'];
}

function ytNormalizeOrderImageUrl($image)
{
    $image = trim((string) $image);
    if ($image === '') {
        return '';
    }

    $image = str_replace('\\', '/', $image);
    if (preg_match('#^(?:https?:)?//#i', $image) || strpos($image, 'data:') === 0) {
        return $image;
    }

    return '/' . ltrim($image, '/');
}

function ytRenderOrderReadonlyBanner($readonlyMode = false)
{
    echo '<div style="margin-bottom:20px;padding:18px 20px;border:1px solid #fdba74;background:linear-gradient(135deg,#fff7ed 0%,#ffffff 100%);border-radius:14px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;">';
    echo '<div>';
    if ($readonlyMode) {
        echo '<div style="font-size:16px;font-weight:700;color:#9a3412;">订单管理当前为只读模式</div>'; 
        echo '<div style="margin-top:6px;font-size:13px;color:#7c2d12;line-height:1.8;">免费版可查看订单和商品摘要，删除、发货、退款等操作需升级专业版授权后使用。</div>'; 
    } else {
        echo '<div style="font-size:16px;font-weight:700;color:#9a3412;">商业订单模块未安装</div>'; 
        echo '<div style="margin-top:6px;font-size:13px;color:#7c2d12;line-height:1.8;">当前授权已满足专业版要求，但订单商业模块文件未安装或未同步，请在授权信息中同步商业模块。</div>'; 
    }
    echo '</div>';
    echo '<a href="?act=auth" style="display:inline-flex;align-items:center;justify-content:center;padding:11px 18px;border-radius:10px;background:linear-gradient(135deg,#ea580c 0%,#dc2626 100%);color:#fff;text-decoration:none;font-weight:700;white-space:nowrap;">升级授权</a>';
    echo '</div>';
}

function ytBuildOrderProductSummaryMap($db, array $orders)
{
    $orderIds = [];
    foreach ($orders as $order) {
        $orderId = intval($order['id'] ?? 0);
        if ($orderId > 0) {
            $orderIds[$orderId] = $orderId;
        }
    }

    if (empty($orderIds)) {
        return [];
    }

    $orderPlaceholders = implode(',', array_fill(0, count($orderIds), '?'));
    $items = $db->fetchAll(
        "SELECT * FROM {$db->table('order_product')} WHERE order_id IN ({$orderPlaceholders}) ORDER BY order_id ASC, id ASC",
        array_values($orderIds)
    );

    $productIds = [];
    foreach ($items as $item) {
        $productId = intval($item['product_id'] ?? 0);
        if ($productId > 0) {
            $productIds[$productId] = $productId;
        }
    }

    $productsById = [];
    if (!empty($productIds)) {
        $productPlaceholders = implode(',', array_fill(0, count($productIds), '?'));
        $productRows = $db->fetchAll(
            "SELECT id, title, litpic FROM {$db->table('product')} WHERE id IN ({$productPlaceholders})",
            array_values($productIds)
        );
        foreach ($productRows as $productRow) {
            $productsById[intval($productRow['id'])] = $productRow;
        }
    }

    $summaryMap = [];
    foreach ($items as $item) {
        $orderId = intval($item['order_id'] ?? 0);
        if ($orderId <= 0) {
            continue;
        }

        $productId = intval($item['product_id'] ?? 0);
        $productRow = $productsById[$productId] ?? [];
        $title = trim((string) (($item['product_title'] ?? '') !== ''
            ? $item['product_title']
            : (($item['product_name'] ?? '') !== '' ? $item['product_name'] : ($productRow['title'] ?? ''))));
        if ($title === '') {
            $title = '未命名商品';
        }

        $image = trim((string) (($item['litpic'] ?? '') !== ''
            ? $item['litpic']
            : (($item['product_image'] ?? '') !== ''
                ? $item['product_image']
                : (($item['pic_path'] ?? '') !== '' ? $item['pic_path'] : ($productRow['litpic'] ?? '')))));
        $image = ytNormalizeOrderImageUrl($image);

        if (!isset($summaryMap[$orderId])) {
            $summaryMap[$orderId] = [
                'count' => 0,
                'primary_title' => '',
                'primary_image' => '',
                'primary_product_id' => 0,
                'titles' => [],
            ];
        }

        $summaryMap[$orderId]['count']++;
        if ($summaryMap[$orderId]['primary_title'] === '') {
            $summaryMap[$orderId]['primary_title'] = $title;
            $summaryMap[$orderId]['primary_product_id'] = $productId;
        }
        if ($summaryMap[$orderId]['primary_image'] === '' && $image !== '') {
            $summaryMap[$orderId]['primary_image'] = $image;
        }
        if (!in_array($title, $summaryMap[$orderId]['titles'], true) && count($summaryMap[$orderId]['titles']) < 3) {
            $summaryMap[$orderId]['titles'][] = $title;
        }
    }

    return $summaryMap;
}

$premiumAvailable = is_file($premiumFile);
if (!$premiumAvailable) {
    if ($licenseObj->getLevel() > \Core\Lib\License::LEVEL_FREE) {
        $loader = new \Core\Lib\ModuleLoader($licenseObj);
        $loader->syncAuthorizedModules();
        $premiumAvailable = is_file($premiumFile);
    }
}

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

if (!$readonlyMode && $premiumAvailable && $licenseObj->getLevel() > \Core\Lib\License::LEVEL_FREE) {
    require $premiumFile;
    return;
}

$action = isset($_GET['action']) ? trim((string) $_GET['action']) : 'list';
$statusMap = [
    0 => ['待支付', 'badge-warning'],
    1 => ['待发货', 'badge-primary'],
    2 => ['已发货', 'badge-success'],
    3 => ['已完成', 'badge-gray'],
    4 => ['已取消', 'badge-danger'],
];

if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    echo '<div class="alert alert-warning">商业订单模块未安装，暂不支持删除订单。</div>'; 
    ytRenderOrderReadonlyBanner($readonlyMode);
    $action = 'list';
}

if ($action === 'detail') {
    $id = intval($_GET['id'] ?? 0);
    $order = $db->fetch("SELECT * FROM {$db->table('order')} WHERE id = ?", [$id]);
    if (!$order) {
        echo '<div class="alert alert-danger">订单不存在</div>';
        return;
    }

    $items = $db->fetchAll("SELECT * FROM {$db->table('order_product')} WHERE order_id = ? ORDER BY id ASC", [$id]);
    ?>
    <div class="page-header">
        <div>
            <h1>订单详情</h1>
            <p>商业订单模块未安装，当前仅显示基础订单信息。</p>
        </div>
        <div class="header-actions">
            <a class="btn btn-secondary" href="?act=order">返回列表</a>
        </div>
    </div>
    <?php ytRenderOrderReadonlyBanner(); ?>
    <div class="card-grid" style="grid-template-columns:repeat(auto-fit,minmax(280px,1fr));margin-bottom:18px;">
        <div class="stat-card"><div class="stat-card-label">订单号</div><div class="stat-card-value" style="font-size:20px;"><?php echo htmlspecialchars($order['order_sn'] ?? '-'); ?></div></div>
        <div class="stat-card"><div class="stat-card-label">会员ID</div><div class="stat-card-value"><?php echo intval($order['member_id'] ?? 0) ?: '-'; ?></div></div>
        <div class="stat-card"><div class="stat-card-label">订单金额</div><div class="stat-card-value">¥<?php echo number_format(floatval($order['pay_price'] ?? ($order['total_amount'] ?? 0)), 2); ?></div></div>
        <div class="stat-card"><div class="stat-card-label">订单状态</div><div class="stat-card-value" style="font-size:20px;"><?php echo ($statusMap[intval($order['status'] ?? 0)] ?? ['未知'])[0]; ?></div></div>
    </div>
    <div class="content-card" style="margin-bottom:18px;">
        <h3 style="margin:0 0 12px;font-size:16px;">收货信息</h3>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px;font-size:13px;color:#475569;">
            <div><strong>收货人：</strong><?php echo htmlspecialchars($order['name'] ?? '-'); ?></div>
            <div><strong>联系电话：</strong><?php echo htmlspecialchars($order['mobile'] ?? '-'); ?></div>
            <div style="grid-column:1 / -1;"><strong>收货地址：</strong><?php echo htmlspecialchars($order['address'] ?? '-'); ?></div>
            <div style="grid-column:1 / -1;"><strong>订单备注：</strong><?php echo htmlspecialchars($order['remark'] ?? '-'); ?></div>
        </div>
    </div>
    <div class="content-card">
        <h3 style="margin:0 0 12px;font-size:16px;">商品明细</h3>
        <table class="data-table">
            <thead>
                <tr><th style="width:70px;">ID</th><th>商品名称</th><th style="width:90px;">数量</th><th style="width:120px;">单价</th><th style="width:120px;">小计</th></tr>
            </thead>
            <tbody>
            <?php if (empty($items)): ?>
                <tr><td colspan="5" style="text-align:center;color:#94a3b8;">暂无商品信息</td></tr>
            <?php else: ?>
                <?php foreach ($items as $item): ?>
                <tr>
                    <td class="id-cell"><?php echo intval($item['product_id'] ?? 0); ?></td>
                    <td><?php echo htmlspecialchars(($item['product_title'] ?? '') !== '' ? $item['product_title'] : ($item['product_name'] ?? '未命名商品')); ?></td>
                    <td><?php echo intval($item['quantity'] ?? 0); ?></td>
                    <td>¥<?php echo number_format(floatval($item['price'] ?? 0), 2); ?></td>
                    <td style="font-weight:600;">¥<?php echo number_format(floatval($item['price'] ?? 0) * intval($item['quantity'] ?? 0), 2); ?></td>
                </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php
    return;
}

$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = 15;
$offset = ($page - 1) * $pageSize;
$status = isset($_GET['status']) ? trim((string) $_GET['status']) : '';
$keyword = trim((string) ($_GET['keyword'] ?? ''));
$where = [];
$params = [];
if ($status !== '' && is_numeric($status)) {
    $where[] = 'status = ?';
    $params[] = intval($status);
}
if ($keyword !== '') {
    $where[] = '(order_sn LIKE ? OR name LIKE ? OR mobile LIKE ?)';
    $kw = '%' . $keyword . '%';
    array_push($params, $kw, $kw, $kw);
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
$totalRow = $db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('order')} {$whereSql}", $params);
$total = intval($totalRow['cnt'] ?? 0);
$lists = $db->fetchAll(
    "SELECT * FROM {$db->table('order')} {$whereSql} ORDER BY id DESC LIMIT {$offset}, {$pageSize}",
    $params
);
$productSummaryMap = ytBuildOrderProductSummaryMap($db, $lists);
$totalPages = max(1, (int) ceil($total / $pageSize));
?>
<div class="page-header">
    <div>
        <h1>订单管理</h1>
        <p>商业订单模块未安装，当前仅显示基础订单列表与商品摘要。</p>
    </div>
    <div class="header-actions">
        <a class="btn btn-secondary" href="?act=auth">升级授权</a>
    </div>
</div>
<?php ytRenderOrderReadonlyBanner($readonlyMode); ?>
<div class="content-card" style="margin-bottom:18px;">
    <form method="get" class="filter-bar" style="display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
        <input type="hidden" name="act" value="order">
        <select name="status" class="form-control" style="width:180px;">
            <option value="">全部状态</option>
            <?php foreach ($statusMap as $statusKey => $statusInfo): ?>
                <option value="<?php echo $statusKey; ?>" <?php echo ($status !== '' && intval($status) === $statusKey) ? 'selected' : ''; ?>><?php echo $statusInfo[0]; ?></option>
            <?php endforeach; ?>
        </select>
        <input type="text" name="keyword" class="form-control" style="width:240px;" placeholder="搜索订单号/收货人/手机" value="<?php echo htmlspecialchars($keyword); ?>">
        <button type="submit" class="btn btn-primary">筛选</button>
        <a class="btn btn-secondary" href="?act=order">重置</a>
    </form>
</div>
<div class="content-card">
    <div class="table-meta" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;gap:12px;flex-wrap:wrap;">
        <div style="font-size:13px;color:#64748b;">共 <?php echo $total; ?> 条订单</div>
        <div style="font-size:12px;color:#94a3b8;">商业订单模块未同步，当前仅支持查看</div>
    </div>
    <table class="data-table">
        <thead>
            <tr><th style="width:70px;">ID</th><th style="width:80px;">图片</th><th>订单号</th><th style="min-width:260px;">商品信息</th><th style="width:90px;">会员ID</th><th>金额</th><th style="width:100px;">支付方式</th><th style="width:100px;">状态</th><th style="width:140px;">下单时间</th><th style="width:260px;">操作</th></tr>
        </thead>
        <tbody>
            <?php if (empty($lists)): ?>
                <tr><td colspan="10" style="text-align:center;color:#94a3b8;">暂无订单数据</td></tr>
            <?php endif; ?>
            <?php foreach ($lists as $row): ?>
                <?php
                $statusInfo = $statusMap[intval($row['status'])] ?? ['未知', 'badge-gray'];
                $payPrice = isset($row['pay_price']) ? floatval($row['pay_price']) : floatval($row['total_amount'] ?? 0);
                $payTypeInfo = ytOrderPayTypeName($row['pay_type'] ?? 0, $payPrice);
                $summary = $productSummaryMap[intval($row['id'])] ?? [];
                $summaryImage = trim((string) ($summary['primary_image'] ?? ''));
                $summaryTitle = trim((string) ($summary['primary_title'] ?? ''));
                $summaryProductId = intval($summary['primary_product_id'] ?? 0);
                if ($summaryTitle === '') {
                    $summaryTitle = '暂无商品信息';
                }
                $summaryTitles = isset($summary['titles']) && is_array($summary['titles']) ? $summary['titles'] : [];
                ?>
                <tr>
                    <td class="id-cell"><?php echo intval($row['id']); ?></td>
                    <td>
                        <?php if ($summaryImage !== ''): ?>
                        <img src="<?php echo htmlspecialchars($summaryImage); ?>" style="width:48px;height:48px;object-fit:cover;border-radius:8px;border:1px solid #e2e8f0;background:#f8fafc;display:block;">
                        <?php else: ?>
                        <div style="width:48px;height:48px;border-radius:8px;border:1px dashed #cbd5e1;background:#f8fafc;color:#94a3b8;display:flex;align-items:center;justify-content:center;font-size:12px;">暂无图</div>
                        <?php endif; ?>
                    </td>
                    <td style="font-family:monospace;font-size:12px;"><?php echo htmlspecialchars($row['order_sn'] ?? '-'); ?></td>
                    <td>
                        <div style="min-width:220px;">
                            <div style="font-weight:600;color:#111827;line-height:1.5;word-break:break-word;">
                                <?php if ($summaryProductId > 0): ?>
                                    <a href="/public/index.php?m=product&id=<?php echo $summaryProductId; ?>" target="_blank" style="color:#111827;text-decoration:none;"><?php echo htmlspecialchars($summaryTitle); ?></a>
                                <?php else: ?>
                                    <?php echo htmlspecialchars($summaryTitle); ?>
                                <?php endif; ?>
                            </div>
                            <div style="margin-top:4px;font-size:12px;color:#64748b;">共 <?php echo intval($summary['count'] ?? 0); ?> 件商品</div>
                            <?php if (count($summaryTitles) > 1): ?>
                            <div style="margin-top:2px;font-size:12px;color:#94a3b8;line-height:1.4;word-break:break-word;"><?php echo htmlspecialchars(implode(' / ', array_slice($summaryTitles, 1))); ?></div>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td><?php echo intval($row['member_id'] ?? 0) ?: '-'; ?></td>
                    <td style="font-weight:600;color:#2563eb;">¥<?php echo number_format($payPrice, 2); ?></td>
                    <td><span class="badge <?php echo $payTypeInfo[1]; ?>"><?php echo $payTypeInfo[0]; ?></span></td>
                    <td><span class="badge <?php echo $statusInfo[1]; ?>"><?php echo $statusInfo[0]; ?></span></td>
                    <td style="font-size:12px;color:#64748b;"><?php echo !empty($row['create_time']) ? date('Y-m-d H:i', intval($row['create_time'])) : '-'; ?></td>
                    <td>
                        <div class="btn-group" style="gap:6px;flex-wrap:wrap;">
                            <a href="?act=order&action=detail&id=<?php echo intval($row['id']); ?>" class="btn btn-secondary" style="padding:4px 10px;font-size:12px;">详情</a>
                            <span style="display:inline-flex;align-items:center;padding:4px 10px;border-radius:8px;background:#f8fafc;border:1px dashed #cbd5e1;color:#94a3b8;font-size:12px;font-weight:600;">模块未安装</span>
                            <span style="display:inline-flex;align-items:center;padding:4px 10px;border-radius:8px;background:#f8fafc;border:1px dashed #cbd5e1;color:#94a3b8;font-size:12px;font-weight:600;">模块未安装</span>
                            <span style="display:inline-flex;align-items:center;padding:4px 10px;border-radius:8px;background:#f8fafc;border:1px dashed #cbd5e1;color:#94a3b8;font-size:12px;font-weight:600;">模块未安装</span>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php if ($totalPages > 1): ?>
    <div class="pagination" style="margin-top:18px;display:flex;gap:8px;justify-content:flex-end;align-items:center;">
        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <a class="page-link <?php echo $i === $page ? 'active' : ''; ?>" href="?act=order&page=<?php echo $i; ?>&status=<?php echo urlencode($status); ?>&keyword=<?php echo urlencode($keyword); ?>" style="padding:8px 12px;border-radius:8px;border:1px solid <?php echo $i === $page ? '#2563eb' : '#e2e8f0'; ?>;background:<?php echo $i === $page ? '#2563eb' : '#fff'; ?>;color:<?php echo $i === $page ? '#fff' : '#475569'; ?>;text-decoration:none;"><?php echo $i; ?></a>
        <?php endfor; ?>
    </div>
    <?php endif; ?>
</div>
