<?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/recharge/index.php';

function ytRenderRechargeReadonlyBanner()
{
    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 ytRenderRechargeReadonlyDetail($db)
{
    $id = intval($_GET['id'] ?? 0);
    $row = $db->fetch("SELECT * FROM {$db->table('recharge')} WHERE id = ?", [$id]);
    if (!$row) {
        echo '<div class="empty-state"><h3>记录不存在</h3><p>请返回列表重新查看</p></div>';
        return;
    }

    $member = intval($row['member_id']) > 0 ? $db->fetch("SELECT username, nickname FROM {$db->table('member')} WHERE id = ?", [$row['member_id']]) : null;
    $statusMap = [0 => '待支付', 1 => '已充值'];

    ytRenderRechargeReadonlyBanner();
    ?>
    <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=recharge" class="btn btn-secondary">返回列表</a>
        </div>
    </div>
    <div class="content-card" style="padding:20px;">
        <table class="data-table" style="width:100%;">
            <tr><td style="width:120px;color:var(--gray-500);">ID</td><td><?php echo intval($row['id']); ?></td></tr>
            <tr><td style="color:var(--gray-500);">会员</td><td><?php echo htmlspecialchars($member['username'] ?? ('用户' . intval($row['member_id']))); ?> (ID: <?php echo intval($row['member_id']); ?>)</td></tr>
            <tr><td style="color:var(--gray-500);">充值金额</td><td style="color:var(--primary);font-weight:600;">￥<?php echo number_format(floatval($row['amount']), 2); ?></td></tr>
            <tr><td style="color:var(--gray-500);">支付方式</td><td><?php echo htmlspecialchars($row['pay_type'] ?? '-'); ?></td></tr>
            <tr><td style="color:var(--gray-500);">交易单号</td><td><?php echo htmlspecialchars($row['trade_no'] ?? '-'); ?></td></tr>
            <tr><td style="color:var(--gray-500);">状态</td><td><span class="badge <?php echo intval($row['status']) === 1 ? 'badge-success' : 'badge-warning'; ?>"><?php echo $statusMap[intval($row['status'])] ?? '未知'; ?></span></td></tr>
            <tr><td style="color:var(--gray-500);">充值时间</td><td><?php echo !empty($row['add_time']) ? date('Y-m-d H:i:s', intval($row['add_time'])) : '-'; ?></td></tr>
        </table>
    </div>
    <?php
}

function ytRenderRechargeReadonlyList($db)
{
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    $pageSize = 15;
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
    $status = isset($_GET['status']) ? intval($_GET['status']) : -999;

    $where = '1=1';
    $params = [];
    if ($keyword !== '') {
        $where .= ' AND (trade_no LIKE ? OR member_id = ?)';
        $params[] = '%' . $keyword . '%';
        $params[] = is_numeric($keyword) ? intval($keyword) : -1;
    }
    if ($status > -999) {
        $where .= ' AND status = ?';
        $params[] = $status;
    }

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

    $statusMap = [
        0 => ['text' => '待支付', 'class' => 'badge-warning'],
        1 => ['text' => '已充值', 'class' => 'badge-success'],
    ];

    $totalAmount = floatval($db->fetch("SELECT COALESCE(SUM(amount), 0) AS total FROM {$db->table('recharge')} WHERE status = 1")['total'] ?? 0);
    $pendingAmount = floatval($db->fetch("SELECT COALESCE(SUM(amount), 0) AS total FROM {$db->table('recharge')} WHERE status = 0")['total'] ?? 0);

    ytRenderRechargeReadonlyBanner();
    ?>
    <div class="page-header">
        <div class="page-title">
            <div class="page-icon"><svg style="width:22px;height:22px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg></div>
            <div>
                <h1>充值记录</h1>
                <p style="font-size:12px;color:var(--gray-500);margin:0;">当前仅开放查看</p>
            </div>
        </div>
    </div>
    <div class="page-context-bar">
        <div class="page-context-item"><span class="page-context-label">总记录数</span><span class="page-context-value"><?php echo $total; ?> 条</span></div>
        <div class="page-context-item"><span class="page-context-label">已充值金额</span><span class="page-context-value">￥<?php echo number_format($totalAmount, 2); ?></span></div>
        <div class="page-context-item"><span class="page-context-label">待支付金额</span><span class="page-context-value">￥<?php echo number_format($pendingAmount, 2); ?></span></div>
        <div class="page-context-item"><span class="page-context-label">当前模式</span><span class="page-context-value page-context-muted">只读查看</span></div>
    </div>
    <div class="filter-bar">
        <form method="get" style="display:flex;gap:12px;flex-wrap:wrap;">
            <input type="hidden" name="act" value="recharge">
            <input type="text" name="keyword" value="<?php echo htmlspecialchars($keyword); ?>" placeholder="交易单号/会员ID搜索..." style="flex:1;min-width:200px;padding:8px 12px;border:1px solid var(--gray-200);border-radius:6px;">
            <select name="status" style="padding:8px 12px;border:1px solid var(--gray-200);border-radius:6px;">
                <option value="-999">全部状态</option>
                <option value="0" <?php echo $status === 0 ? 'selected' : ''; ?>>待支付</option>
                <option value="1" <?php echo $status === 1 ? 'selected' : ''; ?>>已充值</option>
            </select>
            <button type="submit" class="btn btn-primary">筛选</button>
        </form>
    </div>
    <div class="content-card">
        <?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"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/></svg></div>
            <h3>暂无记录</h3>
        </div>
        <?php else: ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width:60px;">ID</th>
                    <th>会员信息</th>
                    <th style="width:100px;">金额</th>
                    <th style="width:100px;">支付方式</th>
                    <th style="width:80px;">状态</th>
                    <th style="width:140px;">时间</th>
                    <th style="width:200px;">操作</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($lists as $item): ?>
                <?php $member = $db->fetch("SELECT username, nickname FROM {$db->table('member')} WHERE id = ?", [$item['member_id']]); ?>
                <tr>
                    <td class="id-cell"><?php echo intval($item['id']); ?></td>
                    <td>
                        <div style="font-weight:500;color:var(--gray-800);"><?php echo htmlspecialchars($member['username'] ?? ('用户' . intval($item['member_id']))); ?></div>
                        <div style="font-size:12px;color:var(--gray-400);margin-top:2px;">ID: <?php echo intval($item['member_id']); ?></div>
                    </td>
                    <td style="color:var(--primary);font-weight:600;">￥<?php echo number_format(floatval($item['amount']), 2); ?></td>
                    <td><span class="badge badge-gray"><?php echo htmlspecialchars($item['pay_type'] ?? '-'); ?></span></td>
                    <td><span class="badge <?php echo $statusMap[intval($item['status'])]['class'] ?? 'badge-gray'; ?>"><?php echo $statusMap[intval($item['status'])]['text'] ?? '未知'; ?></span></td>
                    <td style="font-size:12px;color:var(--gray-500);"><?php echo !empty($item['add_time']) ? date('Y-m-d H:i', intval($item['add_time'])) : '-'; ?></td>
                    <td>
                        <div class="btn-group" style="display:flex;gap:6px;flex-wrap:wrap;">
                            <a href="?act=recharge&action=view&id=<?php echo intval($item['id']); ?>" class="btn btn-primary">详情</a>
                            <span style="display:inline-flex;align-items:center;padding:6px 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="padding:16px;text-align:center;">
            <?php if ($page > 1): ?>
            <a href="?act=recharge&page=<?php echo $page - 1; ?>&status=<?php echo $status; ?>&keyword=<?php echo urlencode($keyword); ?>" style="padding:6px 12px;border:1px solid var(--gray-200);border-radius:6px;text-decoration:none;">上一页</a>
            <?php endif; ?>
            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
            <a href="?act=recharge&page=<?php echo $i; ?>&status=<?php echo $status; ?>&keyword=<?php echo urlencode($keyword); ?>" <?php echo $i === $page ? 'class="active"' : ''; ?> style="padding:6px 12px;border:1px solid var(--gray-200);border-radius:6px;text-decoration:none;<?php echo $i === $page ? 'background:#2563eb;color:#fff;' : ''; ?>"><?php echo $i; ?></a>
            <?php endfor; ?>
            <?php if ($page < $totalPages): ?>
            <a href="?act=recharge&page=<?php echo $page + 1; ?>&status=<?php echo $status; ?>&keyword=<?php echo urlencode($keyword); ?>" style="padding:6px 12px;border:1px solid var(--gray-200);border-radius:6px;text-decoration:none;">下一页</a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
    <style>
    .page-context-bar{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-bottom:16px;}
    .page-context-item{background:#fff;border:1px solid #e2e8f0;border-radius:14px;padding:14px 16px;}
    .page-context-label{display:block;font-size:12px;color:#94a3b8;margin-bottom:6px;}
    .page-context-value{display:block;font-size:14px;font-weight:700;color:#1e293b;line-height:1.6;}
    .page-context-muted{color:#475569;font-weight:600;}
    @media (max-width: 1200px){.page-context-bar{grid-template-columns:repeat(2,minmax(0,1fr));}}
    @media (max-width: 768px){.page-context-bar{grid-template-columns:1fr;}}
    </style>
    <?php
}

if (!$licenseObj->hasFeature('recharge')) {
    ?>
    <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:22px;border:1px solid #bfdbfe;background:linear-gradient(135deg,#eff6ff 0%,#ffffff 100%);border-radius:14px;color:#1e40af;line-height:1.8;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;">
                <div>
                    <div style="font-size:18px;font-weight:700;color:#1d4ed8;margin-bottom:6px;">充值功能仅专业版可用</div>
                    <div style="font-size:13px;color:#475569;">免费版和基础版不开放充值记录、充值删除等商城财务管理能力，请升级专业版后使用。</div>
                </div>
                <a href="?act=auth" style="display:inline-flex;align-items:center;justify-content:center;padding:11px 18px;border-radius:10px;background:#2563eb;color:#fff;text-decoration:none;font-weight:700;white-space:nowrap;">升级专业版</a>
            </div>
        </div>
    </div>
    <?php
    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>
