<?php

declare(strict_types=1);

// Google Play
$playUrl = 'https://play.google.com/store/apps/details?id=com.dastrass.dastrass_app';

// App Store
$appStoreUrl = 'https://apps.apple.com/tj/app/dasrass/id6783342154';

// Файл статистики
$countFile = __DIR__ . '/country.txt';

// User Agent
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

// Определяем iPhone / iPad / iPod
$isIOS =
    stripos($userAgent, 'iPhone') !== false ||
    stripos($userAgent, 'iPad') !== false ||
    stripos($userAgent, 'iPod') !== false ||
    (
        stripos($userAgent, 'Macintosh') !== false &&
        stripos($userAgent, 'Mobile') !== false
    );

// Если iPhone/iPad — переходим в App Store
if ($isIOS) {
    header('Cache-Control: no-store, no-cache, must-revalidate');
    header('Location: ' . $appStoreUrl, true, 302);
    exit;
}

// Создать файл, если его нет
if (!file_exists($countFile)) {
    file_put_contents($countFile, "android=0\n", LOCK_EX);
}

// Значение по умолчанию
$android = 0;

// Прочитать файл
$lines = @file($countFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];

foreach ($lines as $line) {

    if (strpos($line, '=') === false) {
        continue;
    }

    list($key, $value) = explode('=', $line, 2);

    if (trim($key) === 'android') {
        $android = (int)trim($value);
    }
}

// Считать только один раз за 30 дней
if (empty($_COOKIE['android_visit'])) {

    $android++;

    setcookie('android_visit', '1', [
        'expires'  => time() + 60 * 60 * 24 * 30,
        'path'     => '/',
        'httponly' => true,
        'samesite' => 'Lax'
    ]);

    file_put_contents(
        $countFile,
        "android={$android}\n",
        LOCK_EX
    );
}

// Без кэша
header('Cache-Control: no-store, no-cache, must-revalidate');

// Переход в Google Play
header('Location: ' . $playUrl, true, 302);
exit;