<?php
/**
 * Web entrypoint AltAurum Shop.
 */

$root = dirname(__DIR__);

/*
 * Maintenance gate выполняется раньше .env, Composer, Yii, session и consent.
 * Во время миграций/обновления vendor пользователь получает корректный 503,
 * даже если приложение временно не может загрузиться.
 */
$maintenanceFile = $root . '/runtime/maintenance.flag';
if (is_file($maintenanceFile)) {
    http_response_code(503);
    header('Content-Type: text/html; charset=UTF-8');
    header('Retry-After: 120');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

    $startedAt = '';
    $payload = json_decode((string)@file_get_contents($maintenanceFile), true);
    if (is_array($payload) && !empty($payload['started_at'])) {
        $startedAt = htmlspecialchars((string)$payload['started_at'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }

    echo '<!doctype html><html lang="ru"><head><meta charset="utf-8">'
        . '<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">'
        . '<title>AltAurum обновляется</title><style>'
        . '*,*:before,*:after{box-sizing:border-box}html,body{margin:0;min-height:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#f5f8f6;color:#23342b}body{display:grid;place-items:center;padding:24px}.box{width:min(100%,560px);background:#fff;border:1px solid #dce6df;border-radius:24px;padding:32px;box-shadow:0 20px 60px rgba(25,55,38,.10)}.brand{font-size:22px;font-weight:800;color:#176b45}.ico{width:52px;height:52px;border-radius:16px;background:#eaf5ee;display:grid;place-items:center;margin:24px 0 18px;font-size:26px}.box h1{margin:0 0 12px;font-size:clamp(27px,7vw,38px);line-height:1.1}.box p{margin:0;color:#617067;line-height:1.55}.small{margin-top:18px!important;font-size:13px;color:#869188!important}@media(max-width:520px){body{place-items:end center;padding:0}.box{border-radius:24px 24px 0 0;padding:26px 20px max(28px,env(safe-area-inset-bottom));border-bottom:0}}'
        . '</style></head><body><main class="box"><div class="brand">AltAurum</div><div class="ico">↻</div>'
        . '<h1>Обновляем магазин</h1><p>Сейчас устанавливается новая версия. Обычно это занимает несколько минут. Ваши заказы и данные сохраняются.</p>'
        . ($startedAt !== '' ? '<p class="small">Обновление начато: ' . $startedAt . '</p>' : '')
        . '</main></body></html>';
    exit;
}

$envFile = $root . '/.env';
require $root . '/config/load-env.php';

$appEnv = strtolower(trim((string)(getenv('APP_ENV') ?: 'prod')));
if (!in_array($appEnv, ['prod', 'dev'], true)) {
    $appEnv = 'prod';
}

$debugValue = strtolower(trim((string)(getenv('YII_DEBUG') ?: '0')));
$debugRequested = in_array($debugValue, ['1', 'true', 'yes', 'on'], true);
$userIP = $_SERVER['REMOTE_ADDR'] ?? '';
$allowedIPs = array_values(array_filter(array_map('trim', explode(',', (string)(getenv('DEV_ALLOWED_IPS') ?: '127.0.0.1,::1')))));
$isDev = $appEnv === 'dev' && $debugRequested && in_array($userIP, $allowedIPs, true);

defined('YII_DEBUG') or define('YII_DEBUG', $isDev);
defined('YII_ENV') or define('YII_ENV', $isDev ? 'dev' : 'prod');

require $root . '/vendor/autoload.php';
require $root . '/vendor/yiisoft/yii2/Yii.php';

// config/web.php использует классы app\* до создания Application.
// Явный alias делает Yii autoload доступным уже на этапе чтения конфига.
Yii::setAlias('@app', $root);

$config = require $root . '/config/web.php';
(new yii\web\Application($config))->run();
