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

require_once dirname(__DIR__) . '/core/lib/session.php';
cmsStartSession();

require_once dirname(__DIR__) . '/core/db/db.php';

$db = \Core\Db\DB::getInstance();
$action = trim((string) ($_POST['action'] ?? $_GET['action'] ?? ''));
$downloadId = intval($_POST['download_id'] ?? $_GET['download_id'] ?? $_GET['id'] ?? 0);

function ytDownloadJson($code, $msg, array $data = [])
{
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['code' => $code, 'msg' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE);
    exit;
}

function ytDownloadNormalizePath($path)
{
    $path = trim((string) $path);
    if ($path === '') {
        return '';
    }
    if (preg_match('#^https?://#i', $path)) {
        return $path;
    }
    if (strpos($path, '//') === 0) {
        return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https:' : 'http:') . $path;
    }
    if (preg_match('/^[a-z]:[\\\/]/i', $path)) {
        return '';
    }
    return '/' . ltrim(str_replace('\\', '/', $path), '/');
}

function ytDownloadWriteLog($db, $downloadId, $memberId)
{
    $downloadId = intval($downloadId);
    $memberId = intval($memberId);
    if ($downloadId <= 0 || $memberId <= 0) {
        return false;
    }

    $now = time();
    $recent = $db->fetch(
        "SELECT id FROM {$db->table('download_log')} WHERE member_id = ? AND download_id = ? AND add_time >= ? ORDER BY id DESC LIMIT 1",
        [$memberId, $downloadId, $now - 10]
    );
    if ($recent) {
        return false;
    }

    $db->insert('download_log', [
        'member_id' => $memberId,
        'download_id' => $downloadId,
        'add_time' => $now,
    ]);
    return true;
}

if ($downloadId <= 0) {
    ytDownloadJson(400, '参数错误');
}

$download = $db->fetch(
    "SELECT id, title, file_path, need_login, status FROM {$db->table('download')} WHERE id = ? LIMIT 1",
    [$downloadId]
);
if (!$download || intval($download['status'] ?? 0) !== 1) {
    ytDownloadJson(404, '资源不存在或已下架');
}

$memberId = intval($_SESSION['member_id'] ?? 0);
if (intval($download['need_login'] ?? 0) === 1 && $memberId <= 0) {
    if ($action === 'file') {
        header('Location: /member/login.php?redirect=' . rawurlencode($_SERVER['REQUEST_URI'] ?? '/'));
        exit;
    }
    ytDownloadJson(401, '请先登录后下载');
}

if ($action === 'log') {
    ytDownloadWriteLog($db, $downloadId, $memberId);
    ytDownloadJson(200, '记录成功');
}

if ($action === 'file') {
    ytDownloadWriteLog($db, $downloadId, $memberId);
    $db->query("UPDATE {$db->table('download')} SET down_count = IFNULL(down_count, 0) + 1 WHERE id = ?", [$downloadId]);

    $fileUrl = ytDownloadNormalizePath($download['file_path'] ?? '');
    if ($fileUrl === '') {
        ytDownloadJson(404, '下载文件未配置');
    }

    header('Location: ' . $fileUrl);
    exit;
}

ytDownloadJson(404, '未知操作');
