<?php
$cfg = require dirname(__DIR__) . '/config.php';
$file = $cfg['settings_file'];
$localApk = dirname(__DIR__) . '/app-release.apk';

function abs_url($path) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    if ($path === '' || $path[0] !== '/') {
        $path = '/' . ltrim($path, '/');
    }
    return $scheme . '://' . $host . $path;
}

function load_apk_url($file) {
    if (!is_file($file)) return '';
    $j = json_decode((string)file_get_contents($file), true);
    return is_array($j) ? trim((string)($j['apk_url'] ?? '')) : '';
}

function notify_invite_download($code) {
    $code = strtoupper(trim((string)$code));
    if ($code === '' || !preg_match('/^[A-Z0-9_-]{3,20}$/', $code)) return;
    $mall = 'https://yb.zh-app-kytiyu.com/api.php?action=invite_download';
    $payload = json_encode(['inviteCode' => $code], JSON_UNESCAPED_SLASHES);
    if (function_exists('curl_init')) {
        $ch = curl_init($mall);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 2,
            CURLOPT_CONNECTTIMEOUT => 1,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        @curl_exec($ch);
        @curl_close($ch);
        return;
    }
    $ctx = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/json\r\n",
            'content' => $payload,
            'timeout' => 2,
        ],
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false],
    ]);
    @file_get_contents($mall, false, $ctx);
}

$url = load_apk_url($file);
if ($url === '' && is_file($localApk)) {
    $url = 'app-release.apk';
}

$inviteCode = $_GET['inviteCode'] ?? $_GET['invite'] ?? $_GET['code'] ?? $_GET['ref'] ?? '';
if ($inviteCode !== '') {
    notify_invite_download($inviteCode);
    @setcookie('velora_app_downloaded', '1', time() + 2592000, '/');
    @setcookie('velora_app_clicked', '1', time() + 2592000, '/');
}

if ($url === '') {
    http_response_code(503);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Download</title></head>';
    echo '<body style="font-family:sans-serif;padding:40px;text-align:center;background:#111318;color:#eef3fb">';
    echo '<h1>Download link not set</h1><p>Please set an APK URL in the admin panel.</p>';
    echo '<p><a href="../admin/" style="color:#ff7043">Open Admin</a></p></body></html>';
    exit;
}

if (!preg_match('#^https?://#i', $url)) {
    $url = abs_url($url);
}

header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
header('Location: ' . $url, true, 302);
exit;
