<?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();
$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 ytRenderOrderReadonlyBanner()
{
    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>';
    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 ytRenderOrderReadonlyList($db)
{
    $statusMap = [
        -1 => ['已取消', 'badge-danger'],
        0 => ['待付款', 'badge-warning'],
        1 => ['已付款', 'badge-primary'],
        2 => ['已发货', 'badge-warning'],
        3 => ['已完成', 'badge-success'],
    ];

    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $pageSize = 15;
    $statusFilter = isset($_GET['status']) ? trim($_GET['status']) : 'all';
    $offset = ($page - 1) * $pageSize;

    $where = '';
    $params = [];
    if ($statusFilter !== '' && $statusFilter !== 'all') {
        $where = ' WHERE status = ?';
        $params[] = intval($statusFilter);
    }

    $total = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('order')}" . $where, $params)['cnt'] ?? 0);
    $totalPages = max(1, (int) ceil($total / $pageSize));
    $lists = $db->fetchAll("SELECT * FROM {$db->table('order')}" . $where . " ORDER BY id DESC LIMIT {$offset}, {$pageSize}", $params);

    $totalOrders = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('order')}")['cnt'] ?? 0);
    $pendingOrders = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('order')} WHERE status = 0")['cnt'] ?? 0);
    $paidOrders = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('order')} WHERE status = 1")['cnt'] ?? 0);
    $shippedOrders = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('order')} WHERE status = 2")['cnt'] ?? 0);
    $completedOrders = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('order')} WHERE status = 3")['cnt'] ?? 0);
    $cancelledOrders = intval($db->fetch("SELECT COUNT(*) AS cnt FROM {$db->table('order')} WHERE status = -1")['cnt'] ?? 0);

    ytRenderOrderReadonlyBanner();
    ?>
    <div class="stats-grid" style="grid-template-columns:repeat(6, 1fr);">
        <div class="stat-card" onclick="window.location.href='?act=order&status=all'" style="cursor:pointer;">
            <div class="stat-icon" style="background:#f0f7ec;color:#5a8f3e;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $totalOrders; ?></div><div class="stat-label">全部订单</div></div>
        </div>
        <div class="stat-card" onclick="window.location.href='?act=order&status=0'" style="cursor:pointer;">
            <div class="stat-icon" style="background:#fff7ed;color:#f97316;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $pendingOrders; ?></div><div class="stat-label">待付款</div></div>
        </div>
        <div class="stat-card" onclick="window.location.href='?act=order&status=1'" style="cursor:pointer;">
            <div class="stat-icon" style="background:#eff6ff;color:#2563eb;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $paidOrders; ?></div><div class="stat-label">已付款</div></div>
        </div>
        <div class="stat-card" onclick="window.location.href='?act=order&status=2'" style="cursor:pointer;">
            <div class="stat-icon" style="background:#fef3c7;color:#d97706;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="3" width="15" height="13"/><polygon points="16 8 20 8 23 11 23 16 16 16 16 8"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $shippedOrders; ?></div><div class="stat-label">已发货</div></div>
        </div>
        <div class="stat-card" onclick="window.location.href='?act=order&status=3'" style="cursor:pointer;">
            <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $completedOrders; ?></div><div class="stat-label">已完成</div></div>
        </div>
        <div class="stat-card" onclick="window.location.href='?act=order&status=-1'" style="cursor:pointer;">
            <div class="stat-icon" style="background:#fee2e2;color:#ef4444;"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg></div>
            <div class="stat-info"><div class="stat-value"><?php echo $cancelledOrders; ?></div><div class="stat-label">已取消</div></div>
        </div>
    </div>

    <div class="content-card" style="margin-top:20px;">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;padding:18px 18px 15px;border-bottom:1px solid #eee;gap:12px;flex-wrap:wrap;">
            <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a href="?act=order&status=all" class="tab-btn <?php echo $statusFilter === '' || $statusFilter === 'all' ? 'active' : ''; ?>">全部</a>
                <a href="?act=order&status=0" class="tab-btn <?php echo $statusFilter === '0' ? 'active' : ''; ?>">待付款<span class="tab-count"><?php echo $pendingOrders; ?></span></a>
                <a href="?act=order&status=1" class="tab-btn <?php echo $statusFilter === '1' ? 'active' : ''; ?>">已付款<span class="tab-count"><?php echo $paidOrders; ?></span></a>
                <a href="?act=order&status=2" class="tab-btn <?php echo $statusFilter === '2' ? 'active' : ''; ?>">已发货<span class="tab-count"><?php echo $shippedOrders; ?></span></a>
                <a href="?act=order&status=3" class="tab-btn <?php echo $statusFilter === '3' ? 'active' : ''; ?>">已完成<span class="tab-count"><?php echo $completedOrders; ?></span></a>
                <a href="?act=order&status=-1" class="tab-btn <?php echo $statusFilter === '-1' ? 'active' : ''; ?>">已取消</a>
            </div>
            <div style="display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:999px;background:#fff7ed;border:1px solid #fdba74;color:#9a3412;font-size:12px;font-weight:700;">
                当前仅开放查看
            </div>
        </div>

        <?php if (empty($lists)): ?>
        <div class="empty-state">
            <div class="empty-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg></div>
            <h3>暂无订单</h3>
            <p>当前没有可展示的订单记录</p>
        </div>
        <?php else: ?>
        <table class="data-table">
            <thead>
                <tr><th style="width:70px;">ID</th><th>订单号</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 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);
                ?>
                <tr>
                    <td class="id-cell"><?php echo intval($row['id']); ?></td>
                    <td style="font-family:monospace;font-size:12px;"><?php echo htmlspecialchars($row['order_sn'] ?? '-'); ?></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:20px;">
            <?php
            $start = max(1, $page - 2);
            $end = min($totalPages, $page + 2);
            if ($start > 1) {
                echo '<a href="?act=order&status=' . urlencode($statusFilter) . '&page=1">1</a>';
                if ($start > 2) {
                    echo '<span>...</span>';
                }
            }
            for ($i = $start; $i <= $end; $i++) {
                echo '<a href="?act=order&status=' . urlencode($statusFilter) . '&page=' . $i . '"' . ($i === $page ? ' class="active"' : '') . '>' . $i . '</a>';
            }
            if ($end < $totalPages) {
                if ($end < $totalPages - 1) {
                    echo '<span>...</span>';
                }
                echo '<a href="?act=order&status=' . urlencode($statusFilter) . '&page=' . $totalPages . '">' . $totalPages . '</a>';
            }
            ?>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
    <?php
}

function ytRenderOrderReadonlyDetail($db)
{
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    $order = $db->fetch("SELECT * FROM {$db->table('order')} WHERE id = ?", [$id]);
    if (!$order) {
        echo '<div class="empty-state"><h3>订单不存在</h3><p>请返回列表重新查看</p></div>';
        return;
    }

    $items = $db->fetchAll("SELECT * FROM {$db->table('order_product')} WHERE order_id = ? ORDER BY id ASC", [$id]);
    $statusMap = [
        -1 => ['已取消', 'badge-danger'],
        0 => ['待付款', 'badge-warning'],
        1 => ['已付款', 'badge-primary'],
        2 => ['已发货', 'badge-warning'],
        3 => ['已完成', 'badge-success'],
    ];
    $statusInfo = $statusMap[intval($order['status'] ?? 0)] ?? ['未知', 'badge-gray'];
    $payPrice = isset($order['pay_price']) ? floatval($order['pay_price']) : floatval($order['total_amount'] ?? 0);
    $payTypeInfo = ytOrderPayTypeName($order['pay_type'] ?? 0, $payPrice);
    ytRenderOrderReadonlyBanner();
    ?>
    <div class="page-header">
        <div>
            <h2 style="font-size:18px;font-weight:700;color:#111827;margin:0;">订单详情</h2>
            <p style="font-size:13px;color:#6b7280;margin:6px 0 0 0;">当前为只读查看模式</p>
        </div>
        <div class="page-actions">
            <a href="?act=order" class="btn btn-secondary">返回列表</a>
        </div>
    </div>

    <div class="content-card" style="padding:22px;">
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;margin-bottom:20px;">
            <div><div style="font-size:12px;color:#94a3b8;">订单号</div><div style="margin-top:6px;font-family:monospace;color:#111827;"><?php echo htmlspecialchars($order['order_sn'] ?? '-'); ?></div></div>
            <div><div style="font-size:12px;color:#94a3b8;">状态</div><div style="margin-top:6px;"><span class="badge <?php echo $statusInfo[1]; ?>"><?php echo $statusInfo[0]; ?></span></div></div>
            <div><div style="font-size:12px;color:#94a3b8;">支付方式</div><div style="margin-top:6px;"><span class="badge <?php echo $payTypeInfo[1]; ?>"><?php echo $payTypeInfo[0]; ?></span></div></div>
            <div><div style="font-size:12px;color:#94a3b8;">实付金额</div><div style="margin-top:6px;font-size:18px;font-weight:700;color:#2563eb;">￥<?php echo number_format($payPrice, 2); ?></div></div>
        </div>

        <table class="data-table" style="margin-bottom:20px;">
            <tbody>
                <tr><td style="width:140px;color:#64748b;">会员ID</td><td><?php echo intval($order['member_id'] ?? 0) ?: '-'; ?></td></tr>
                <tr><td style="color:#64748b;">收货人</td><td><?php echo htmlspecialchars($order['consignee'] ?: ($order['name'] ?? '-')); ?></td></tr>
                <tr><td style="color:#64748b;">联系电话</td><td><?php echo htmlspecialchars($order['mobile'] ?? '-'); ?></td></tr>
                <tr><td style="color:#64748b;">收货地址</td><td><?php echo htmlspecialchars($order['address'] ?? '-'); ?></td></tr>
                <tr><td style="color:#64748b;">快递单号</td><td><?php echo htmlspecialchars(($order['ship_no'] ?? '') !== '' ? $order['ship_no'] : ($order['express_no'] ?? '-')); ?></td></tr>
                <tr><td style="color:#64748b;">订单备注</td><td><?php echo htmlspecialchars(($order['remark'] ?? '') !== '' ? $order['remark'] : '-'); ?></td></tr>
                <tr><td style="color:#64748b;">下单时间</td><td><?php echo !empty($order['create_time']) ? date('Y-m-d H:i:s', intval($order['create_time'])) : '-'; ?></td></tr>
            </tbody>
        </table>

        <div style="font-size:15px;font-weight:700;color:#111827;margin-bottom:12px;">订单商品</div>
        <?php if (empty($items)): ?>
        <div style="padding:18px;border:1px dashed #cbd5e1;border-radius:10px;color:#64748b;">暂无商品明细</div>
        <?php else: ?>
        <table class="data-table">
            <thead>
                <tr><th>商品</th><th style="width:100px;">数量</th><th style="width:120px;">单价</th><th style="width:120px;">小计</th></tr>
            </thead>
            <tbody>
            <?php foreach ($items as $item): ?>
                <tr>
                    <td>
                        <div style="font-weight:600;color:#111827;"><?php echo htmlspecialchars(($item['product_title'] ?? '') !== '' ? $item['product_title'] : ($item['product_name'] ?? '未命名商品')); ?></div>
                        <?php if (!empty($item['specs'])): ?>
                        <div style="margin-top:4px;font-size:12px;color:#94a3b8;"><?php echo htmlspecialchars($item['specs']); ?></div>
                        <?php endif; ?>
                    </td>
                    <td><?php echo intval($item['quantity'] ?? 0); ?></td>
                    <td>￥<?php echo number_format(floatval($item['price'] ?? 0), 2); ?></td>
                    <td>￥<?php echo number_format(floatval($item['total_price'] ?? 0), 2); ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
    <?php
}

if (!$licenseObj->hasFeature('order_manage')) {
    $action = isset($_GET['action']) ? $_GET['action'] : 'list';
    if ($action === 'detail') {
        ytRenderOrderReadonlyDetail($db);
    } else {
        ytRenderOrderReadonlyList($db);
    }
    return;
}

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

if (is_file($premiumFile)) {
    require $premiumFile;
    return;
}
?>
<div class="page-container fade-in">
    <div class="page-header">
        <div>
            <h2>产品订单</h2>
            <p style="font-size:13px;color:var(--text-light);margin:4px 0 0 0;">当前安装包未包含订单模块文件</p>
        </div>
    </div>
    <div class="content-card" style="padding:28px;">
        <div style="padding:18px;border:1px solid #fdba74;background:#fff7ed;border-radius:12px;color:#9a3412;line-height:1.8;">
            当前站点尚未安装订单管理模块。授权后可自动同步安装。
        </div>
    </div>
</div>
