<?php
/**
 * Smart link: https://dasrass.com/app/
 * Android → Google Play, iOS → App Store, else → website.
 * Counts unique visits (cookie, 30 days) in country.txt
 */

declare(strict_types=1);

$androidUrl = 'https://play.google.com/store/apps/details?id=com.dastrass.dastrass_app';
$iosUrl = 'https://apps.apple.com/tj/app/dasrass/id6783342154';
$webUrl = 'https://dasrass.com/';

$countFile = __DIR__ . '/country.txt';

function load_counts(string $file): array
{
    $defaults = ['android' => 0, 'ios' => 0, 'web' => 0];
    if (!is_file($file)) {
        return $defaults;
    }
    $data = $defaults;
    $lines = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
    foreach ($lines as $line) {
        if (!str_contains($line, '=')) {
            continue;
        }
        [$key, $value] = explode('=', $line, 2);
        $key = trim($key);
        if (array_key_exists($key, $data)) {
            $data[$key] = (int) trim($value);
        }
    }
    return $data;
}

function save_counts(string $file, array $data): void
{
    $body = "android={$data['android']}\nios={$data['ios']}\nweb={$data['web']}\n";
    $fp = @fopen($file, 'c+');
    if ($fp === false) {
        @file_put_contents($file, $body);
        return;
    }
    try {
        if (flock($fp, LOCK_EX)) {
            ftruncate($fp, 0);
            rewind($fp);
            fwrite($fp, $body);
            fflush($fp);
            flock($fp, LOCK_UN);
        }
    } finally {
        fclose($fp);
    }
}

$data = load_counts($countFile);

$ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
$isAndroid = str_contains($ua, 'android');
$isIOS = str_contains($ua, 'iphone')
    || str_contains($ua, 'ipad')
    || str_contains($ua, 'ipod');

$cookieDays = 60 * 60 * 24 * 30;
$secure = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');

$cookieOpts = [
    'expires' => time() + $cookieDays,
    'path' => '/',
    'secure' => $secure,
    'httponly' => true,
    'samesite' => 'Lax',
];

if ($isAndroid) {
    if (empty($_COOKIE['android_visit'])) {
        $data['android']++;
        setcookie('android_visit', '1', $cookieOpts);
    }
    $target = $androidUrl;
} elseif ($isIOS) {
    if (empty($_COOKIE['ios_visit'])) {
        $data['ios']++;
        setcookie('ios_visit', '1', $cookieOpts);
    }
    $target = $iosUrl;
} else {
    if (empty($_COOKIE['web_visit'])) {
        $data['web']++;
        setcookie('web_visit', '1', $cookieOpts);
    }
    $target = $webUrl;
}

save_counts($countFile, $data);

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