<?php
session_start();
require_once '../config.php';

// 检查登录状态
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}

$user_id = $_SESSION['user_id'];

// --- 统计数据 ---
$total_income = 0;
$total_expense = 0;

// 计算总收入 (正数)
$stmt_in = mysqli_prepare($conn, "SELECT SUM(change_amount) as total FROM coin_logs WHERE user_id = ? AND change_amount > 0");
mysqli_stmt_bind_param($stmt_in, "i", $user_id);
mysqli_stmt_execute($stmt_in);
$res_in = mysqli_stmt_get_result($stmt_in);
if ($row_in = mysqli_fetch_assoc($res_in)) {
    $total_income = $row_in['total'] ?? 0;
}

// 计算总支出 (负数转正数显示)
$stmt_out = mysqli_prepare($conn, "SELECT SUM(change_amount) as total FROM coin_logs WHERE user_id = ? AND change_amount < 0");
mysqli_stmt_bind_param($stmt_out, "i", $user_id);
mysqli_stmt_execute($stmt_out);
$res_out = mysqli_stmt_get_result($stmt_out);
if ($row_out = mysqli_fetch_assoc($res_out)) {
    $total_expense = abs($row_out['total'] ?? 0);
}

// --- 筛选与分页逻辑 ---
$filter = isset($_GET['type']) ? $_GET['type'] : 'all';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$pageSize = 15;
$offset = ($page - 1) * $pageSize;

// 构建查询条件
$whereSql = "cl.user_id = ?";
$params = [$user_id];
$types = "i";

if ($filter !== 'all') {
    $whereSql .= " AND cl.type = ?";
    $params[] = $filter;
    $types .= "s";
}

// 查询当前页数据 (关联 apps 表获取软件信息)
// 重点：通过 cl.app_id 关联 apps.id
$sql = "SELECT cl.*, a.name as app_name, a.id as real_app_id 
        FROM coin_logs cl 
        LEFT JOIN apps a ON cl.app_id = a.id 
        WHERE $whereSql 
        ORDER BY cl.id DESC 
        LIMIT ?, ?";
        
$params[] = $offset;
$params[] = $pageSize;
$types .= "ii";

$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, $types, ...$params);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$logs = [];
while ($row = mysqli_fetch_assoc($result)) {
    $logs[] = $row;
}

// 查询总数用于分页
$countSql = "SELECT COUNT(*) as total FROM coin_logs cl WHERE $whereSql";
$countParams = array_slice($params, 0, -2);
$countTypes = substr($types, 0, -2);

$stmt_count = mysqli_prepare($conn, $countSql);
if (!empty($countParams)) {
    mysqli_stmt_bind_param($stmt_count, $countTypes, ...$countParams);
}
mysqli_stmt_execute($stmt_count);
$res_count = mysqli_stmt_get_result($stmt_count);
$row_count = mysqli_fetch_assoc($res_count);
$totalRecords = $row_count['total'];
$totalPages = ceil($totalRecords / $pageSize);

// --- 详细类型处理函数 ---
function getLogDetails($log) {
    $type = $log['type'];
    $desc = $log['description']; 
    $appName = $log['app_name'] ?? '未知软件'; // 如果关联不到软件，显示未知

    // 默认结构
    $data = [
        'icon' => '📝',
        'title' => '其他变动',
        'color' => '#666',
        'bg' => '#f0f0f0',
        'link' => '' 
    ];

    switch ($type) {
        case 'checkin':
            $data = ['icon' => '📅', 'title' => '每日签到奖励', 'color' => '#28a745', 'bg' => '#e8f5e9'];
            break;
        case 'recharge':
            $data = ['icon' => '💳', 'title' => '卡密充值', 'color' => '#007bff', 'bg' => '#e3f2fd'];
            break;
        case 'income':
            // 收入：显示具体软件名
            $data = ['icon' => '💰', 'title' => '软件收入: ' . $appName, 'color' => '#ff6b00', 'bg' => '#fff3cd'];
            break;
        case 'consume':
            // 消费：显示具体软件名
            $data = ['icon' => '🛒', 'title' => '购买软件: ' . $appName, 'color' => '#dc3545', 'bg' => '#ffebee'];
            break;
        case 'admin_add':
            $data = ['icon' => '🎁', 'title' => '后台发放', 'color' => '#17a2b8', 'bg' => '#e0f7fa'];
            break;
        case 'admin_reduce':
            $data = ['icon' => '⚠️', 'title' => '后台扣除', 'color' => '#6c757d', 'bg' => '#f5f5f5'];
            break;
    }

    // 如果不是软件相关的类型（如后台操作），优先显示描述
    if ($type !== 'income' && $type !== 'consume' && !empty($desc)) {
        $data['title'] = $desc;
    }

    // 设置跳转链接：只有软件相关且有ID才跳转
    if (($type === 'income' || $type === 'consume') && !empty($log['real_app_id'])) {
        $data['link'] = '../yl.php?id=' . $log['real_app_id'];
    }

    return $data;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>收益详情</title>
    <style>
        body { background-color: #f4f6f9; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; padding-bottom: 20px; }
        .container { max-width: 500px; margin: 0 auto; }

        /* 顶部导航 */
        .header { background: white; padding: 15px 20px; display: flex; align-items: center; box-shadow: 0 1px 3px rgba(0,0,0,0.05); position: sticky; top: 0; z-index: 100; }
        .back-btn { font-size: 20px; color: #333; text-decoration: none; margin-right: 15px; }
        .title { font-size: 18px; font-weight: bold; color: #333; }

        /* 统计卡片 */
        .stats-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 20px; padding: 20px; border-radius: 12px; color: white; display: flex; justify-content: space-around; box-shadow: 0 4px 10px rgba(102, 126, 234, 0.4); }
        .stat-item { text-align: center; }
        .stat-num { font-size: 24px; font-weight: bold; margin-bottom: 5px; }
        .stat-label { font-size: 12px; opacity: 0.9; }

        /* 筛选栏 */
        .filter-bar { display: flex; background: white; margin: 0 20px 15px; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        .filter-item { flex: 1; text-align: center; padding: 10px 0; font-size: 13px; color: #666; text-decoration: none; border-bottom: 2px solid transparent; transition: all 0.2s; }
        .filter-item.active { color: #667eea; font-weight: bold; border-bottom-color: #667eea; background: #f8f9ff; }
        .filter-item:hover { background: #f9f9f9; }

        /* 列表样式 */
        .log-list { margin: 0 20px; }
        .log-item { background: white; border-radius: 10px; padding: 15px; margin-bottom: 12px; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 5px rgba(0,0,0,0.03); }
        
        .log-left { display: flex; align-items: center; gap: 12px; }
        .log-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px; }
        
        .log-info { display: flex; flex-direction: column; }
        .log-title { font-size: 15px; font-weight: 600; color: #333; margin-bottom: 4px; }
        .log-time { font-size: 12px; color: #999; }
        
        .log-right { text-align: right; }
        .log-amount { font-size: 16px; font-weight: bold; font-family: 'DIN Alternate', sans-serif; }
        .amount-add { color: #28a745; }
        .amount-reduce { color: #dc3545; }
        
        .log-balance { font-size: 11px; color: #aaa; margin-top: 4px; }
        
        /* 链接样式 */
        .clickable-title { text-decoration: none; color: #333; display: flex; align-items: center; }
        .clickable-title:active { opacity: 0.7; }
        .link-arrow { font-size: 12px; color: #ccc; margin-left: 4px; }

        /* 分页 */
        .pagination { display: flex; justify-content: center; align-items: center; gap: 10px; margin: 20px 0; }
        .page-btn { padding: 6px 12px; background: white; border: 1px solid #ddd; border-radius: 4px; color: #333; text-decoration: none; font-size: 13px; }
        .page-btn:hover { background: #f0f0f0; }
        .page-btn.disabled { color: #ccc; pointer-events: none; }
        .page-info { font-size: 13px; color: #666; }

        /* 空状态 */
        .empty-state { text-align: center; padding: 50px 20px; color: #999; }
        .empty-icon { font-size: 50px; margin-bottom: 15px; }
    </style>
</head>
<body>

<div class="container">
    <!-- 顶部导航 -->
    <div class="header">
        <a href="home.php" class="back-btn">←</a>
        <div class="title">收益详情</div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-card">
        <div class="stat-item">
            <div class="stat-num">+<?php echo $total_income; ?></div>
            <div class="stat-label">总收益</div>
        </div>
        <div class="stat-item" style="border-left: 1px solid rgba(255,255,255,0.2); padding-left: 30px;">
            <div class="stat-num">-<?php echo $total_expense; ?></div>
            <div class="stat-label">总消费</div>
        </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
        <a href="?type=all" class="filter-item <?php echo $filter === 'all' ? 'active' : ''; ?>">全部</a>
        <a href="?type=income" class="filter-item <?php echo $filter === 'income' ? 'active' : ''; ?>">收入</a>
        <a href="?type=consume" class="filter-item <?php echo $filter === 'consume' ? 'active' : ''; ?>">消费</a>
        <a href="?type=checkin" class="filter-item <?php echo $filter === 'checkin' ? 'active' : ''; ?>">签到</a>
        <a href="?type=recharge" class="filter-item <?php echo $filter === 'recharge' ? 'active' : ''; ?>">充值</a>
    </div>

    <!-- 列表区域 -->
    <div class="log-list">
        <?php if (empty($logs)): ?>
            <div class="empty-state">
                <div class="empty-icon">📭</div>
                <div>暂无记录</div>
            </div>
        <?php else: ?>
            <?php foreach ($logs as $log): ?>
                <?php $details = getLogDetails($log); ?>
                <div class="log-item">
                    <div class="log-left">
                        <div class="log-icon" style="background: <?php echo $details['bg']; ?>;">
                            <?php echo $details['icon']; ?>
                        </div>
                        <div class="log-info">
                            <?php if(!empty($details['link'])): ?>
                                <a href="<?php echo $details['link']; ?>" class="clickable-title">
                                    <span class="log-title"><?php echo htmlspecialchars($details['title']); ?></span>
                                    <span class="link-arrow">></span>
                                </a>
                            <?php else: ?>
                                <span class="log-title"><?php echo htmlspecialchars($details['title']); ?></span>
                            <?php endif; ?>
                            <span class="log-time"><?php echo date('Y-m-d H:i', strtotime($log['create_time'])); ?></span>
                        </div>
                    </div>
                    <div class="log-right">
                        <div class="log-amount <?php echo $log['change_amount'] > 0 ? 'amount-add' : 'amount-reduce'; ?>">
                            <?php echo $log['change_amount'] > 0 ? '+' . $log['change_amount'] : $log['change_amount']; ?>
                        </div>
                        <div class="log-balance">余额: <?php echo $log['balance_after']; ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- 分页 -->
    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?type=<?php echo $filter; ?>&page=<?php echo $page-1; ?>" class="page-btn">上一页</a>
            <?php else: ?>
                <span class="page-btn disabled">上一页</span>
            <?php endif; ?>

            <span class="page-info"><?php echo $page; ?> / <?php echo $totalPages; ?></span>

            <?php if ($page < $totalPages): ?>
                <a href="?type=<?php echo $filter; ?>&page=<?php echo $page+1; ?>" class="page-btn">下一页</a>
            <?php else: ?>
                <span class="page-btn disabled">下一页</span>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

</body>
</html>
