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

require_once 'config.php';

// 设置响应头为 JSON
header('Content-Type: application/json; charset=utf-8');

// 1. 检查参数
if (!isset($_GET['id']) || intval($_GET['id']) <= 0) {
    echo json_encode(['status' => 'error', 'message' => '参数错误']);
    exit;
}

$id = (int)$_GET['id'];

// 2. 获取软件信息 (包含作者ID和价格)
$stmt = mysqli_prepare($conn, "SELECT * FROM apps WHERE id = ? AND 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) {
    echo json_encode(['status' => 'error', 'message' => '软件不存在或未审核']);
    exit;
}

$coin_price = intval($app['coin_price'] ?? 0);
$is_paid_app = ($coin_price > 0); // 是否为付费软件

// 3. 权限验证逻辑

// 如果是付费软件，必须登录
if ($is_paid_app) {
    if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
        echo json_encode(['status' => 'error', 'message' => '请先登录', 'redirect' => 'user/index.php']);
        exit;
    }

    $user_id = (int)$_SESSION['user_id'];

    // 查询用户余额
    $user_stmt = mysqli_prepare($conn, "SELECT coins FROM users WHERE id = ?");
    mysqli_stmt_bind_param($user_stmt, "i", $user_id);
    mysqli_stmt_execute($user_stmt);
    $user_result = mysqli_stmt_get_result($user_stmt);
    $user = mysqli_fetch_assoc($user_result);

    if (!$user) {
        echo json_encode(['status' => 'error', 'message' => '用户不存在']);
        exit;
    }

    $user_coins = intval($user['coins']);

    // 检查余额
    if ($user_coins < $coin_price) {
        echo json_encode(['status' => 'error', 'message' => '小马币不足，还差 ' . ($coin_price - $user_coins) . ' 个', 'redirect' => 'user/index.php']);
        exit;
    }

    // 【扣费逻辑】
    // 扣除用户余额
    $new_balance = $user_coins - $coin_price;
    $deduct_stmt = mysqli_prepare($conn, "UPDATE users SET coins = ? WHERE id = ?");
    mysqli_stmt_bind_param($deduct_stmt, "ii", $new_balance, $user_id);
    mysqli_stmt_execute($deduct_stmt);

    // 记录用户消费日志 (用于 syxq.php 显示)
    $log_desc = '购买软件: ' . $app['name'];
    $log_stmt = mysqli_prepare($conn, "INSERT INTO coin_logs (user_id, type, change_amount, balance_after, description, app_id, create_time) VALUES (?, 'consume', ?, ?, ?, ?, NOW())");
    $neg_price = -$coin_price; // 消费是负数
    mysqli_stmt_bind_param($log_stmt, "iidsi", $user_id, $neg_price, $new_balance, $log_desc, $id);
    mysqli_stmt_execute($log_stmt);

    // 【作者收益逻辑】
    // 如果软件有上传者 (user_id 不为空)，且不是自己下载自己的软件
    if (!empty($app['user_id']) && $app['user_id'] != $user_id) {
        $author_id = $app['user_id'];
        
        // 查询作者当前余额
        $auth_stmt = mysqli_prepare($conn, "SELECT coins FROM users WHERE id = ?");
        mysqli_stmt_bind_param($auth_stmt, "i", $author_id);
        mysqli_stmt_execute($auth_stmt);
        $auth_res = mysqli_stmt_get_result($auth_stmt);
        $author = mysqli_fetch_assoc($auth_res);

        if ($author) {
            // 作者余额增加 (这里设置作者获得 100% 收益，如需抽成可修改此处)
            $author_new_coins = $author['coins'] + $coin_price;
            mysqli_query($conn, "UPDATE users SET coins = $author_new_coins WHERE id = $author_id");

            // 记录作者收入日志 (用于 syxq.php 显示)
            $income_desc = '软件收入: ' . $app['name'];
            $inc_log = mysqli_prepare($conn, "INSERT INTO coin_logs (user_id, type, change_amount, balance_after, description, app_id, create_time) VALUES (?, 'income', ?, ?, ?, ?, NOW())");
            mysqli_stmt_bind_param($inc_log, "iidsi", $author_id, $coin_price, $author_new_coins, $income_desc, $id);
            mysqli_stmt_execute($inc_log);
        }
    }
}

// 4. 更新通用统计 (下载次数、IP统计、下载历史)

// 更新下载次数
mysqli_query($conn, "UPDATE apps SET download_count = download_count + 1 WHERE id = $id");

// 更新下载人数 (独立IP统计)
$ip = $_SERVER['REMOTE_ADDR'];
$ip_safe = mysqli_real_escape_string($conn, $ip);

// 确保日志表存在
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS download_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    app_id INT NOT NULL,
    ip_address VARCHAR(45) NOT NULL,
    download_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX(app_id, ip_address)
)");

$check_log = mysqli_query($conn, "SELECT id FROM download_logs WHERE app_id = $id AND ip_address = '$ip_safe'");

if (mysqli_num_rows($check_log) == 0) {
    mysqli_query($conn, "INSERT INTO download_logs (app_id, ip_address) VALUES ($id, '$ip_safe')");
    mysqli_query($conn, "UPDATE apps SET download_people = download_people + 1 WHERE id = $id");
}

// 记录登录用户的下载历史
if (isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'] === true) {
    $user_id = (int)$_SESSION['user_id'];
    
    // 确保历史表存在
    mysqli_query($conn, "CREATE TABLE IF NOT EXISTS download_history (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        app_id INT NOT NULL,
        download_time DATETIME DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY user_app (user_id, app_id)
    )");

    // 插入或更新历史记录
    mysqli_query($conn, "INSERT INTO download_history (user_id, app_id, download_time) 
                         VALUES ($user_id, $id, NOW()) 
                         ON DUPLICATE KEY UPDATE download_time = NOW()");
}

// 5. 返回成功结果 (不再直接跳转，返回 URL 供前端打开)
echo json_encode([
    'status' => 'success', 
    'message' => '准备下载', 
    'url' => $app['download_url']
]);
exit;
?>
