<?php
/* 点击计数 + 跳转脚本 */
require_once __DIR__ . '/config.php';

$app = isset($_GET['app']) ? (string) $_GET['app'] : 'default';
if (!isset($APP_LINKS[$app])) {
    $app = 'default';
}

/* 记录点击次数（TXT 存储，每日一行，含历史） */
$file  = __DIR__ . '/data/stats.txt';
$today = date('Y-m-d');

$fh = @fopen($file, 'c+');
if ($fh !== false) {
    if (flock($fh, LOCK_EX)) {
        $content = stream_get_contents($fh);
        $map = array();
        if (is_string($content) && trim($content) !== '') {
            $lines = preg_split('/\r\n|\r|\n/', trim($content));
            foreach ($lines as $line) {
                if (preg_match('/^(\d{4}-\d{2}-\d{2}):(\d+)$/', trim($line), $m)) {
                    $map[$m[1]] = (int) $m[2];
                }
            }
        }
        $map[$today] = (int) (isset($map[$today]) ? $map[$today] : 0) + 1;
        ksort($map);
        $out = '';
        foreach ($map as $d => $c) {
            $out .= $d . ':' . $c . "\n";
        }
        ftruncate($fh, 0);
        rewind($fh);
        fwrite($fh, $out);
        fflush($fh);
        flock($fh, LOCK_UN);
    }
    fclose($fh);
}

/* 302 跳转到真实下载地址 */
header('Location: ' . $APP_LINKS[$app], true, 302);
exit;
