<?php
/* evacuation.php – Дипломатия | Avatiah Security Index
   Обновление: каждые 30 мин через JS
   Кэш: evacuation_cache.json
   API: fetch_evacuation.php
   Дата: 02.11.2025 10:00 UTC
*/
// === ЭКСПОРТ В /factors (1 строка) ===
file_put_contents(__DIR__.'/factors/'.pathinfo(__FILE__,PATHINFO_FILENAME).'.json', 
    json_encode(['aal'=>$aal,'last_update'=>date('d.m.Y H:i').' UTC'], JSON_UNESCAPED_UNICODE)
);

date_default_timezone_set('UTC');
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
header("Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self' data:;");

$update_interval = 30;

// ---- 1. Чтение кэша ----
$cache_file = __DIR__ . '/evacuation_cache.json';
$evac = [];
if (file_exists($cache_file)) {
    $json = file_get_contents($cache_file);
    $tmp  = json_decode($json, true);
    if (json_last_error() === JSON_ERROR_NONE) $evac = $tmp;
}
$evac = array_merge([
    'last_update'        => date('d.m.Y H:i') . ' UTC',
    'aal'                => 1,
    'aal_text'           => 'Норма (стабильная дипломатия)',
    'aal_color'          => '#10b981',
    'total_flights'      => 5,
    'diplomatic_flights' => 3,
    'vip_flights'        => 2,
    'normal_range'       => '1–3',
    'trend'              => 'Стабильная (+58 авиакомпаний, +20% трафик TLV, American с марта 2026)',
    'flights'            => [
        ['code'=>'LY542','route'=>'TLV → ATH','type'=>'diplomatic','desc'=>'Координация с Грецией','source'=>'Flightradar24'],
        ['code'=>'LY328','route'=>'TLV → FCO','type'=>'diplomatic','desc'=>'Дипломатический корпус','source'=>'EL AL'],
        ['code'=>'Private','route'=>'TLV → GVA','type'=>'vip','desc'=>'VIP‑дипломатия','source'=>'OSINT'],
        ['code'=>'USAF','route'=>'TLV → RAM','type'=>'diplomatic','desc'=>'Военная координация','source'=>'State.gov'],
        ['code'=>'LY14','route'=>'TLV → AMM','type'=>'diplomatic','desc'=>'Региональная дипломатия','source'=>'Flightradar24']
    ],
    'responses' => [
        'Дипломатия стабильна: 3–5 рейсов/день (Flightradar24)',
        'Координация: TLV → ATH/FCO/AMM',
        'Мониторинг: EL AL, USAF',
        'Предупреждение: +58 авиакомпаний, American с марта 2026'
    ]
], $evac);

$aal          = (int)$evac['aal'];
$contribution = round($aal * 1.08, 1);

// ---- 2. Синхронизация с total_index.json ----
$total_file = __DIR__ . '/total_index.json';
$total = ['factors'=>[],'total_aal'=>1.0,'last_update'=>date('d.m.Y H:i').' UTC','factor_count'=>0];
if (file_exists($total_file)) {
    $json = file_get_contents($total_file);
    $tmp  = json_decode($json, true);
    if (json_last_error() === JSON_ERROR_NONE) $total = $tmp;
}
$total['factors']['evacuation'] = ['aal'=>$aal,'last_update'=>$evac['last_update'],'contribution'=>$contribution];
$sum = $cnt = 0;
foreach ($total['factors'] as $f) { if (isset($f['aal'])) { $sum += $f['aal']; $cnt++; } }
$total['total_aal']   = $cnt ? round($sum / $cnt, 2) : 1.0;
$total['factor_count']= $cnt;
$total['last_update'] = date('d.m.Y H:i').' UTC';
file_put_contents($total_file, json_encode($total, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
    <title>Дипломатия | Avatiah Security Index</title>
    <meta name="description" content="AAL <?= $aal ?>. Рейсов: <?= $evac['total_flights'] ?>. Стабильная дипломатия. <?= $evac['last_update'] ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root{--bg:#0a0e1a;--card:#1a2332;--border:#2d3748;--text:#e2e8f0;--green:#10b981;--yellow:#f59e0b;--accent:#3498db;--font-xs:.75rem}
        *{box-sizing:border-box;margin:0;padding:0}
        body{background:var(--bg);color:var(--text);font-family:'Inter',sans-serif;line-height:1.6;padding:clamp(.5rem,2vw,1rem);display:flex;flex-direction:column;min-height:100vh}
        .container{max-width:1600px;margin:auto;display:grid;gap:1.5rem}
        @media(min-width:768px){.container{grid-template-columns:1fr 340px}}
        .section{background:var(--card);border-radius:12px;padding:1.5rem;border:1px solid var(--border)}
        .header{background:linear-gradient(135deg,#1e3c72,#2a5298);color:#fff;padding:2rem;border-radius:16px;text-align:center}
        .header h1{font-size:clamp(1.8rem,5vw,2.8rem);margin-bottom:.5rem}
        .back-link{display:inline-block;margin-top:1rem;color:#fff;text-decoration:underline}
        .aal-circle{width:140px;height:140px;border-radius:50%;margin:auto;display:flex;align-items:center;justify-content:center;font-size:3rem;font-weight:700}
        .aal-info h2{font-size:1.8rem;margin:.5rem 0}
        .count-indicator{font-size:3rem;font-weight:bold;color:var(--accent);text-align:center;margin:1rem 0}
        .incident-item{padding:1rem;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center}
        .incident-item:last-child{border-bottom:none}
        .incident-type{color:var(--accent);font-weight:600}
        .incident-severity{display:inline-block;padding:.2rem .6rem;border-radius:12px;font-size:.8rem;margin-left:.5rem}
        .severity-diplomatic{background:var(--yellow);color:#fff}
        .severity-vip{background:#9b59b6;color:#fff}
        .response-list{list-style:none}
        .response-item{padding:.5rem 0;border-bottom:1px solid var(--border)}
        .response-item:last-child{border-bottom:none}
        .aal-scale{display:grid;grid-template-columns:repeat(5,1fr);gap:.5rem;margin:1rem 0}
        .scale-item{padding:.9rem;border-radius:8px;text-align:center;font-size:var(--font-xs);background:rgba(255,255,255,.03)}
        .scale-item.active{border:2px solid #fff}
        .scale-item div:first-child{font-weight:700;font-size:1.1em}
        .sidebar .section{margin-bottom:1rem}
        .aal-thresholds{display:flex;flex-direction:column;gap:.4rem;margin-top:.5rem}
        .threshold{display:flex;align-items:center;font-size:.85rem}
        .threshold-bar{width:100%;height:8px;background:#334155;border-radius:4px;overflow:hidden;margin-left:.5rem}
        .threshold-fill{height:100%;transition:width .3s}
        .threshold-1 .threshold-fill{background:var(--green);width:20%}
        .threshold-2 .threshold-fill{background:var(--yellow);width:40%}
        .footer{margin-top:auto;background:#111827;padding:2rem;border-top:1px solid var(--border);text-align:center;color:#94a3b8}
        .update-status{font-size:.8rem;color:var(--green);text-align:center;margin-top:.5rem}
    </style>
</head>
<body>
<div class="container">
    <div class="main-content">
        <div class="header">
            <h1>Дипломатия</h1>
            <p>Рейсы • Координация • Логистика | <span id="last-update"><?= htmlspecialchars($evac['last_update']) ?></span></p>
            <a href="/" class="back-link">Назад к индексу</a>
        </div>

        <div class="section">
            <div class="aal-info">
                <div class="aal-circle" id="aal-circle" style="background:<?= $evac['aal_color'] ?>"><?= $aal ?>.0</div>
                <h2 id="aal-text"><?= htmlspecialchars($evac['aal_text']) ?></h2>
                <div class="count-indicator" id="flights-value"><?= $evac['total_flights'] ?></div>
                <div style="display:flex;justify-content:center;gap:.75rem;font-size:.95rem">
                    <div><strong>Всего рейсов</strong></div>
                    <div><strong>Норма</strong> (<?= htmlspecialchars($evac['normal_range']) ?>)</div>
                </div>
            </div>
            <p class="update-status" id="update-status">Обновление через <span id="countdown">30:00</span></p>
        </div>

        <div class="section">
            <h2>Активные рейсы</h2>
            <div id="flight-list">
                <?php foreach ($evac['flights'] as $f): ?>
                <div class="incident-item">
                    <div class="incident-type">
                        <strong><?= htmlspecialchars($f['code']) ?></strong> - <?= htmlspecialchars($f['route']) ?>
                        <span class="incident-severity severity-<?= $f['type'] ?>">
                            <?= $f['type']==='diplomatic' ? 'Дипломатия' : 'VIP' ?>
                        </span>
                    </div>
                    <div style="font-size:.9rem;color:#94a3b8"><?= htmlspecialchars($f['desc']) ?></div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="section">
            <h2>Меры координации</h2>
            <ul class="response-list">
                <?php foreach ($evac['responses'] as $r): ?>
                <li class="response-item"><?= htmlspecialchars($r) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>

        <div class="section">
            <h2>Шкала активности</h2>
            <div class="aal-scale">
                <div class="scale-item <?= $aal==1?'active':'' ?>" style="background:#10b98120"><div>1</div><div>Норма<br><small>0–2</small></div></div>
                <div class="scale-item <?= $aal==2?'active':'' ?>" style="background:#f59e0b20"><div>2</div><div>Внимание<br><small>3–5</small></div></div>
                <div class="scale-item"><div>3</div><div>Риск<br><small>6–10</small></div></div>
                <div class="scale-item"><div>4</div><div>Критично<br><small>11–15</small></div></div>
                <div class="scale-item"><div>5</div><div>Максимум<br><small>16+</small></div></div>
            </div>
        </div>
    </div>

    <div class="sidebar">
        <div class="section">
            <h3>Пороги тревоги (AAL)</h3>
            <div class="aal-thresholds">
                <div class="threshold threshold-1"><span>1 – Норма</span><div class="threshold-bar"><div class="threshold-fill"></div></div></div>
                <div class="threshold threshold-2"><span>2 – Внимание</span><div class="threshold-bar"><div class="threshold-fill"></div></div></div>
            </div>
            <p style="margin-top:.5rem;font-size:.8rem;text-align:center">Текущий: <span class="current-aal"><?= $aal ?>.0</span></p>
        </div>

        <div class="section">
            <h3>Статистика</h3>
            <p><strong>Всего:</strong> <span id="stats-total"><?= $evac['total_flights'] ?></span></p>
            <p><strong>Дипломатия:</strong> <?= $evac['diplomatic_flights'] ?></p>
            <p><strong>VIP:</strong> <?= $evac['vip_flights'] ?></p>
            <p><strong>Тренд:</strong> <?= htmlspecialchars($evac['trend']) ?></p>
            <p><strong>Вклад:</strong> <?= $contribution ?>/10</p>
        </div>

        <div class="section">
            <h3>Мониторинг</h3>
            <p><strong>Источники:</strong> Flightradar24, State.gov</p>
            <p><strong>Частота:</strong> каждые 30 мин</p>
        </div>

        <div class="section">
            <h3>Обновление</h3>
            <p><strong>Последнее:</strong> <span id="sidebar-update"><?= date('H:i') ?></span></p>
            <p><strong>Следующее:</strong> <span id="next-update">--:--</span></p>
        </div>
    </div>
</div>

<div class="footer">
    <p><strong>Avatiah Security Index</strong> — OSINT‑аналитика в реальном времени</p>
    <p>© 2025 Avatiah • <?= date('d.m.Y H:i') ?></p>
</div>

<script src="evacuation.js"></script>
</body>
</html>