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

require_once ROOT_PATH . 'core/db/db.php';
require_once ROOT_PATH . 'core/lib/license.php';
require_once ROOT_PATH . 'core/lib/license_guard.php';
require_once ROOT_PATH . 'core/lib/order_timeout.php';
require_once ROOT_PATH . 'core/lib/refund_service.php';
require_once ROOT_PATH . 'core/lib/product_review_service.php';

$licenseObj = new \Core\Lib\License();
$readonlyMode = !\Core\Lib\LicenseGuard::canUseOrder($licenseObj);

$db = isset($db) && $db instanceof \Core\Db\DB ? $db : \Core\Db\DB::getInstance();
\Core\Lib\OrderTimeout::cancelExpiredPendingOrders($db);
\Core\Lib\RefundService::ensureTable($db);
\Core\Lib\ProductReviewService::ensureTable($db);

$todayStart = strtotime(date('Y-m-d'));
$todayEnd = $todayStart + 86400;

$getCount = function ($sql, $params = []) use ($db) {
    $row = $db->fetch($sql, $params);
    return intval($row['cnt'] ?? 0);
};
$getMoney = function ($sql, $params = []) use ($db) {
    $row = $db->fetch($sql, $params);
    return floatval($row['amount'] ?? 0);
};

$orderTable = $db->table('order');
$productTable = $db->table('product');
$refundTable = $db->table('order_refund');
$reviewTable = $db->table('product_review');
$orderProductTable = $db->table('order_product');

$totalOrders = $getCount("SELECT COUNT(*) AS cnt FROM {$orderTable}");
$todayOrders = $getCount("SELECT COUNT(*) AS cnt FROM {$orderTable} WHERE create_time >= ? AND create_time < ?", [$todayStart, $todayEnd]);
$pendingPay = $getCount("SELECT COUNT(*) AS cnt FROM {$orderTable} WHERE status = 0");
$pendingShip = $getCount("SELECT COUNT(*) AS cnt FROM {$orderTable} WHERE status = 1");
$shipped = $getCount("SELECT COUNT(*) AS cnt FROM {$orderTable} WHERE status = 2");
$completed = $getCount("SELECT COUNT(*) AS cnt FROM {$orderTable} WHERE status = 3");
$totalSales = $getMoney("SELECT SUM(pay_price) AS amount FROM {$orderTable} WHERE status IN (1,2,3)");
$todaySales = $getMoney("SELECT SUM(pay_price) AS amount FROM {$orderTable} WHERE status IN (1,2,3) AND create_time >= ? AND create_time < ?", [$todayStart, $todayEnd]);
$productCount = $getCount("SELECT COUNT(*) AS cnt FROM {$productTable} WHERE status = 1");
$lowStock = $getCount("SELECT COUNT(*) AS cnt FROM {$productTable} WHERE status = 1 AND stock < 10");
$pendingRefund = $getCount("SELECT COUNT(*) AS cnt FROM {$refundTable} WHERE status = 0");
$pendingReview = $getCount("SELECT COUNT(*) AS cnt FROM {$reviewTable} WHERE status = 0");

$recentOrders = $db->fetchAll("SELECT id, order_sn, member_id, pay_price, status, create_time FROM {$orderTable} ORDER BY id DESC LIMIT 8");
$hotProducts = $db->fetchAll("SELECT s.product_id, p.title AS title, s.qty, s.amount FROM (SELECT product_id, SUM(quantity) AS qty, SUM(total_price) AS amount FROM {$orderProductTable} GROUP BY product_id) s LEFT JOIN {$productTable} p ON p.id = s.product_id ORDER BY s.qty DESC, s.amount DESC LIMIT 6");
$statusMap = [-1 => '已取消', 0 => '待付款', 1 => '待发货', 2 => '已发货', 3 => '已完成', 4 => '已取消'];
$maxHotQty = 1;
foreach ($hotProducts as $hot) {
    $maxHotQty = max($maxHotQty, intval($hot['qty'] ?? 0));
}
?>
<div class="page-container fade-in yt-shop-dashboard">
    <?php if ($readonlyMode): ?>
    <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;"><div><div style="font-size:16px;font-weight:700;color:#9a3412;">商城首页当前为只读模式</div><div style="margin-top:6px;font-size:13px;color:#7c2d12;line-height:1.8;">免费版可查看商城数据总览，发货、退款、评价审核、支付配置等操作需升级专业版授权后使用。</div></div><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></div>
    <?php endif; ?>
    <div class="yt-shop-hero">
        <div>
            <div class="yt-shop-kicker">商城数据大屏</div>
            <h1>商城运营总览</h1>
            <p>订单、发货、退款、评价和商品库存集中查看，商品管理继续沿用内容管理里的产品管理。</p>
        </div>
        <div class="yt-shop-hero-actions">
            <a href="?act=order" class="btn btn-primary">订单管理</a>
            <a href="?act=shipping" class="btn btn-secondary">发货管理</a>
            <a href="?act=product" class="btn btn-secondary">商品管理</a>
        </div>
    </div>

    <div class="yt-shop-metrics">
        <a class="yt-shop-card" href="?act=order"><span>订单总数</span><strong><?php echo $totalOrders; ?></strong><em>今日新增 <?php echo $todayOrders; ?></em></a>
        <a class="yt-shop-card" href="?act=order"><span>成交金额</span><strong>￥<?php echo number_format($totalSales, 2); ?></strong><em>今日 ￥<?php echo number_format($todaySales, 2); ?></em></a>
        <a class="yt-shop-card warn" href="?act=shipping"><span>待发货</span><strong><?php echo $pendingShip; ?></strong><em>已发货 <?php echo $shipped; ?> / 已完成 <?php echo $completed; ?></em></a>
        <a class="yt-shop-card danger" href="?act=refund"><span>待处理售后</span><strong><?php echo $pendingRefund; ?></strong><em>待付款订单 <?php echo $pendingPay; ?></em></a>
        <a class="yt-shop-card" href="?act=review"><span>待审核评价</span><strong><?php echo $pendingReview; ?></strong><em>评价开关在商城配置</em></a>
        <a class="yt-shop-card warn" href="?act=product"><span>上架商品</span><strong><?php echo $productCount; ?></strong><em>低库存 <?php echo $lowStock; ?> 个</em></a>
    </div>

    <div class="yt-shop-grid">
        <div class="content-card yt-shop-panel">
            <div class="yt-shop-panel-head"><h2>订单状态</h2><a href="?act=order">查看全部</a></div>
            <div class="yt-shop-flow">
                <div><strong><?php echo $pendingPay; ?></strong><span>待付款</span></div>
                <div><strong><?php echo $pendingShip; ?></strong><span>待发货</span></div>
                <div><strong><?php echo $shipped; ?></strong><span>已发货</span></div>
                <div><strong><?php echo $completed; ?></strong><span>已完成</span></div>
            </div>
        </div>
        <div class="content-card yt-shop-panel">
            <div class="yt-shop-panel-head"><h2>热销商品</h2><a href="?act=product">管理商品</a></div>
            <?php if (empty($hotProducts)): ?>
                <div class="yt-shop-empty">暂无成交商品</div>
            <?php else: ?>
                <div class="yt-hot-list">
                    <?php foreach ($hotProducts as $hot): ?>
                    <?php $percent = max(6, round(intval($hot['qty'] ?? 0) / $maxHotQty * 100)); ?>
                    <div class="yt-hot-row">
                        <div class="yt-hot-title"><?php echo htmlspecialchars($hot['title'] ?: ('商品ID ' . intval($hot['product_id']))); ?><span><?php echo intval($hot['qty']); ?> 件</span></div>
                        <div class="yt-hot-bar"><i style="width:<?php echo $percent; ?>%;"></i></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="content-card yt-shop-panel" style="margin-top:16px;">
        <div class="yt-shop-panel-head"><h2>最新订单</h2><a href="?act=order">进入订单管理</a></div>
        <?php if (empty($recentOrders)): ?>
            <div class="yt-shop-empty">暂无订单</div>
        <?php else: ?>
            <table class="data-table">
                <thead><tr><th>订单号</th><th>会员ID</th><th>金额</th><th>状态</th><th>下单时间</th></tr></thead>
                <tbody>
                    <?php foreach ($recentOrders as $order): ?>
                    <tr>
                        <td><a href="?act=order&keyword=<?php echo urlencode($order['order_sn']); ?>" style="color:#2563eb;"><?php echo htmlspecialchars($order['order_sn']); ?></a></td>
                        <td><?php echo intval($order['member_id']); ?></td>
                        <td style="color:#ef4444;font-weight:700;">￥<?php echo number_format(floatval($order['pay_price']), 2); ?></td>
                        <td><?php echo htmlspecialchars($statusMap[intval($order['status'])] ?? '未知'); ?></td>
                        <td><?php echo !empty($order['create_time']) ? date('Y-m-d H:i', intval($order['create_time'])) : '-'; ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>
<style>
.yt-shop-dashboard{background:#f8fafc;}
.yt-shop-hero{display:flex;justify-content:space-between;align-items:flex-end;gap:24px;padding:28px 30px;margin-bottom:18px;border-radius:22px;background:radial-gradient(circle at top left,#38bdf8 0,#2563eb 32%,#0f172a 100%);color:#fff;box-shadow:0 22px 50px rgba(37,99,235,.22);overflow:hidden;position:relative;}
.yt-shop-hero:after{content:"";position:absolute;right:-80px;top:-80px;width:260px;height:260px;border-radius:50%;background:rgba(255,255,255,.12);}
.yt-shop-kicker{font-size:13px;letter-spacing:4px;opacity:.75;margin-bottom:10px;}
.yt-shop-hero h1{margin:0;font-size:30px;line-height:1.2;}
.yt-shop-hero p{margin:10px 0 0;color:rgba(255,255,255,.76);font-size:14px;line-height:1.8;max-width:620px;}
.yt-shop-hero-actions{display:flex;gap:10px;flex-wrap:wrap;position:relative;z-index:1;}
.yt-shop-metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:16px;}
.yt-shop-card{display:block;padding:20px;border-radius:18px;background:#fff;border:1px solid #e2e8f0;text-decoration:none;box-shadow:0 12px 30px rgba(15,23,42,.05);}
.yt-shop-card span{display:block;color:#64748b;font-size:13px;margin-bottom:10px;}
.yt-shop-card strong{display:block;color:#0f172a;font-size:26px;line-height:1.1;}
.yt-shop-card em{display:block;margin-top:10px;font-style:normal;color:#94a3b8;font-size:12px;}
.yt-shop-card.warn strong{color:#d97706;}.yt-shop-card.danger strong{color:#dc2626;}
.yt-shop-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;}
.yt-shop-panel{padding:20px;border-radius:18px;}
.yt-shop-panel-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;}
.yt-shop-panel-head h2{margin:0;color:#0f172a;font-size:17px;}.yt-shop-panel-head a{color:#2563eb;font-size:13px;text-decoration:none;}
.yt-shop-flow{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;}.yt-shop-flow div{padding:18px 10px;text-align:center;background:#f8fafc;border:1px solid #e2e8f0;border-radius:14px;}.yt-shop-flow strong{display:block;color:#2563eb;font-size:24px;}.yt-shop-flow span{display:block;margin-top:8px;color:#64748b;font-size:12px;}
.yt-hot-list{display:grid;gap:14px;}.yt-hot-title{display:flex;justify-content:space-between;gap:12px;font-size:13px;color:#334155;margin-bottom:7px;}.yt-hot-title span{color:#64748b;}.yt-hot-bar{height:8px;border-radius:999px;background:#e2e8f0;overflow:hidden;}.yt-hot-bar i{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,#2563eb,#38bdf8);}
.yt-shop-empty{padding:36px;text-align:center;color:#94a3b8;background:#f8fafc;border:1px dashed #cbd5e1;border-radius:14px;}
@media(max-width:1100px){.yt-shop-metrics{grid-template-columns:repeat(2,1fr)}.yt-shop-grid{grid-template-columns:1fr}.yt-shop-hero{align-items:flex-start;flex-direction:column}}
@media(max-width:720px){.yt-shop-metrics{grid-template-columns:1fr}.yt-shop-flow{grid-template-columns:repeat(2,1fr)}}
</style>
