<?php
require_once 'config.php';

// 开启Session
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// 获取软件ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    die("参数错误");
}

// 查询软件详情 (关联用户表获取投稿者昵称)
$stmt = mysqli_prepare($conn, "SELECT a.*, u.username as author_name FROM apps a LEFT JOIN users u ON a.user_id = u.id WHERE a.id = ? AND a.status = 1");
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$app = mysqli_fetch_assoc($result);

if (!$app) {
    die("软件不存在或未审核");
}

// 【新增】获取来源页面，实现原路返回
$back_url = 'index.php'; // 默认返回首页
if (isset($_SERVER['HTTP_REFERER'])) {
    $referer_host = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
    $current_host = $_SERVER['HTTP_HOST'];
    if ($referer_host == $current_host) {
        $back_url = $_SERVER['HTTP_REFERER'];
    }
}

// 获取当前用户的小马币余额
$user_coins = 0;
$is_logged_in = false;

if (isset($_SESSION['user_id'])) {
    $is_logged_in = true;
    $user_id = intval($_SESSION['user_id']);
    $coin_stmt = mysqli_prepare($conn, "SELECT coins FROM users WHERE id = ?");
    mysqli_stmt_bind_param($coin_stmt, "i", $user_id);
    mysqli_stmt_execute($coin_stmt);
    $coin_result = mysqli_stmt_get_result($coin_stmt);
    if ($coin_row = mysqli_fetch_assoc($coin_result)) {
        $user_coins = intval($coin_row['coins']);
    }
}

// 网盘颜色配置
function getDiskStyleYl($type) {
    $styles = [
        '百度网盘'     => ['bg'=>'#0697ff'],
        '夸克网盘'     => ['bg'=>'#519cff'],
        '迅雷网盘'     => ['bg'=>'#f59e0b'],
        '蓝奏云'       => ['bg'=>'#b33dff'],
        '阿里云盘'     => ['bg'=>'#ff6b00'],
        '腾讯微云'     => ['bg'=>'#10b981'],
        '中国移动云盘' => ['bg'=>'#ec4899'],
        '123云盘'      => ['bg'=>'#8b5cf6'],
    ];
    return $styles[$type] ?? ['bg'=>'#6c757d'];
}

$disk_style = getDiskStyleYl($app['disk_type']);
$coin_price = intval($app['coin_price'] ?? 0);
$is_enough = ($user_coins >= $coin_price);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?= htmlspecialchars($app['name']) ?> - 软件详情</title>
    <style>
        body { background: #f5f7fa; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; padding: 20px; color: #333; padding-top: 70px; }
        .container { max-width: 600px; margin: 0 auto; background: #fff; border-radius: 16px; padding: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        
        /* 返回按钮 */
        .back-btn {
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1000;
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            padding: 8px 15px;
            border-radius: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-decoration: none;
            color: #333;
            font-size: 14px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 5px;
            border: 1px solid rgba(0,0,0,0.05);
            transition: all 0.2s;
        }
        .back-btn:active { transform: scale(0.95); background: #f0f0f0; }

        .header { text-align: center; margin-bottom: 20px; }
        .app-icon { width: 80px; height: 80px; border-radius: 18px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); margin-bottom: 10px; }
        .app-name { font-size: 22px; font-weight: bold; margin: 0; }
        .app-meta { font-size: 13px; color: #888; margin-top: 5px; display: flex; justify-content: center; gap: 10px; flex-wrap: wrap; }
        
        .info-card { background: #f8f9fa; border-radius: 12px; padding: 15px; margin-bottom: 20px; }
        .info-row { display: flex; justify-content: space-between; margin-bottom: 8px; font-size: 14px; }
        .info-row:last-child { margin-bottom: 0; }
        .info-label { color: #666; }
        .info-value { color: #333; font-weight: 500; }
        
        /* 小马币信息区域 */
        .coin-info { background: linear-gradient(135deg, #fff3cd, #ffeeba); border-radius: 12px; padding: 15px; margin-bottom: 20px; border: 1px solid #ffc107; }
        .coin-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; font-size: 14px; }
        .coin-row:last-child { margin-bottom: 0; }
        .coin-label { color: #856404; }
        .coin-value { color: #856404; font-weight: bold; }
        .coin-warning { color: #dc3545; font-size: 12px; margin-top: 8px; }
        
        .price-tag { background: #fff; color: #856404; padding: 2px 8px; border-radius: 4px; font-weight: bold; }
        
        .download-btn { width: 100%; padding: 14px; border: none; border-radius: 30px; color: white; font-size: 16px; font-weight: 600; cursor: pointer; box-shadow: 0 4px 10px rgba(0,0,0,0.1); transition: transform 0.2s; display: flex; align-items: center; justify-content: center; gap: 8px; }
        .download-btn:active { transform: scale(0.98); }
        .download-btn:disabled { background: #ccc !important; cursor: not-allowed; }
        
        .login-btn, .get-coin-btn { 
            display: block; 
            width: 100%; 
            padding: 14px; 
            border-radius: 30px; 
            text-align: center; 
            font-size: 16px; 
            font-weight: 600; 
            text-decoration: none; 
            box-shadow: 0 4px 10px rgba(0,0,0,0.1); 
            transition: transform 0.2s;
            color: white;
            border: none;
        }
        .login-btn { background: #007bff; }
        .get-coin-btn { background: #28a745; }
        .login-btn:active, .get-coin-btn:active { transform: scale(0.98); }
        
        .toast { position: fixed; bottom: 50px; left: 50%; transform: translateX(-50%); background: rgba(0,0,0,0.8); color: white; padding: 10px 20px; border-radius: 20px; font-size: 14px; display: none; z-index: 999; }
    </style>
</head>
<body>

<!-- 返回按钮 -->
<a href="<?= htmlspecialchars($back_url) ?>" class="back-btn">← 返回</a>

<div class="container">
    <div class="header">
        <img src="<?= htmlspecialchars($app['image']) ?>" class="app-icon" onerror="this.src='https://via.placeholder.com/80'">
        <h1 class="app-name"><?= htmlspecialchars($app['name']) ?></h1>
        <div class="app-meta">
            <span>📂 <?= htmlspecialchars($app['category']) ?></span>
            <?php if(!empty($app['author_name'])): ?>
            <span>👤 <?= htmlspecialchars($app['author_name']) ?></span>
            <?php endif; ?>
            <span>🕒 <?= date('Y-m-d', strtotime($app['created_at'])) ?></span>
        </div>
    </div>
    
    <?php if($coin_price > 0): ?>
    <!-- 只有收费软件才显示小马币信息区域 -->
    <div class="coin-info">
        <div class="coin-row">
            <span class="coin-label">💰 您的小马币</span>
            <span class="coin-value"><?= $is_logged_in ? $user_coins : '未登录' ?></span>
        </div>
        <div class="coin-row">
            <span class="coin-label">📦 软件价格</span>
            <span class="price-tag"><?= $coin_price ?> 个小马币</span>
        </div>
        <?php if(!$is_logged_in): ?>
        <div class="coin-warning">⚠️ 您还未登录，请先登录后下载</div>
        <?php elseif(!$is_enough): ?>
        <div class="coin-warning">⚠️ 小马币不足，还差 <?= ($coin_price - $user_coins) ?> 个</div>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <div class="info-card">
        <div class="info-row">
            <span class="info-label">网盘类型</span>
            <span class="info-value"><?= htmlspecialchars($app['disk_type']) ?></span>
        </div>
        <?php if(!empty($app['disk_code'])): ?>
        <div class="info-row">
            <span class="info-label">提取码</span>
            <span class="info-value" style="color: #007bff; font-weight: bold; user-select: all;"><?= htmlspecialchars($app['disk_code']) ?></span>
        </div>
        <?php endif; ?>
        <?php if($coin_price <= 0): ?>
        <div class="info-row">
            <span class="info-label">下载所需</span>
            <span class="info-value">
                <span style="color: #28a745;">🆓 免费下载</span>
            </span>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- 【核心修改】按钮显示逻辑 -->
    <?php if($coin_price <= 0): ?>
        <!-- 1. 免费软件：无需登录，直接下载 -->
        <button class="download-btn" 
                style="background: <?= $disk_style['bg'] ?>;" 
                onclick="handleDownload(<?= $app['id'] ?>, 0, '<?= htmlspecialchars($app['download_url']) ?>')">
            🚀 立即下载
        </button>

    <?php elseif(!$is_logged_in): ?>
        <!-- 2. 收费软件 + 未登录：提示登录 -->
        <a href="user/index.php" class="login-btn">🔐 请先登录</a>
    
    <?php elseif(!$is_enough): ?>
        <!-- 3. 收费软件 + 余额不足：提示充值 -->
        <a href="user/index.php" class="get-coin-btn">💎 获取小马币</a>
    
    <?php else: ?>
        <!-- 4. 收费软件 + 已登录 + 余额充足：下载 -->
        <button class="download-btn" 
                style="background: <?= $disk_style['bg'] ?>;" 
                onclick="handleDownload(<?= $app['id'] ?>, <?= $coin_price ?>, '<?= htmlspecialchars($app['download_url']) ?>')">
            🚀 立即下载
        </button>
    <?php endif; ?>
    
    <?php if(!empty($app['description'])): ?>
    <div style="margin-top: 20px; font-size: 14px; color: #555; line-height: 1.6;">
        <strong>软件介绍：</strong>
        <p style="margin-top: 5px; white-space: pre-wrap;"><?= htmlspecialchars($app['description']) ?></p>
    </div>
    <?php endif; ?>
</div>

<div class="toast" id="toast"></div>

<script>
    function handleDownload(appId, price, url) {
        // 免费软件直接下载（price参数已经是0，这里逻辑不变，但确保免费时不再弹确认框）
        if (price <= 0) {
            fetch('download.php?id=' + appId); // 记录下载次数
            window.open(url, '_blank');
            showToast('正在下载...');
            return;
        }
        
        // 收费软件：确认扣费
        if (confirm('下载需花费 ' + price + ' 个小马币，确定支付吗？')) {
            showToast('正在处理...');
            
            fetch('download.php?id=' + appId)
            .then(response => {
                if (!response.ok) throw new Error('服务器响应异常');
                return response.text();
            })
            .then(text => {
                try {
                    return JSON.parse(text);
                } catch (e) {
                    throw new Error('服务器返回格式错误');
                }
            })
            .then(res => {
                if (res.status === 'success') {
                    window.open(url, '_blank');
                    showToast('✅ 支付成功，正在下载...');
                } else {
                    alert('❌ ' + (res.message || '下载失败'));
                    if (res.redirect) {
                        setTimeout(() => { window.location.href = res.redirect; }, 1000);
                    }
                }
            })
            .catch(err => {
                alert('❌ ' + err.message);
            });
        }
    }
    
    function showToast(msg) {
        const t = document.getElementById('toast');
        t.textContent = msg;
        t.style.display = 'block';
        setTimeout(() => t.style.display = 'none', 2000);
    }
</script>

</body>
</html>
