<?php
/* oil.php – Волатильность нефти WTI | Avatiah Security Index
   Полная, адаптивная, информативная страница
   Обновление: каждые 30 мин через JS
   Кэш: oil_cache.json
   API: fetch_oil.php
   Экспорт: /factors/oil.json → admin.php
   Дата: 03.11.2025 10:00 UTC
*/

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;");

// === 1. Чтение кэша ===
$cache_file = __DIR__ . '/oil_cache.json';
$oil = [
    'last_update' => date('d.m.Y H:i') . ' UTC',
    'aal' => 1.2,
    'aal_text' => 'Норма (стабильный рынок)',
    'aal_color' => '#10b981',
    'volatility' => '2.8%',
    'volatility_change' => '-0.4%',
    'price_wti' => '$81.92',
    'price_brent' => '$85.67',
    'chart_data' => [3.1, 2.9, 2.7, 2.5, 2.8, 3.0, 2.9, 2.6, 2.8, 3.2, 2.8],
    'factors' => [
        'Стабильный спрос в Азии и Европе',
        'Нет угроз Ормузскому проливу',
        'Снижение геополитического риска',
        'Стабильный курс USD',
        'Сезонное снижение спроса'
    ],
    'sources' => [
        ['name' => 'LiteFinance', 'url' => 'https://www.litefinance.org'],
        ['name' => 'Capital.com', 'url' => 'https://www.capital.com'],
        ['name' => 'Bloomberg', 'url' => 'https://www.bloomberg.com'],
        ['name' => 'Reuters', 'url' => 'https://www.reuters.com']
    ],
    'related_factors' => [
        ['name' => 'navy.php', 'title' => 'Активность ВМС', 'change' => '-1.2%'],
        ['name' => 'energy.php', 'title' => 'Волатильность энергии', 'change' => '-0.8%'],
        ['name' => 'media.php', 'title' => 'Медиа-упоминания', 'change' => '-0.05%']
    ]
];

if (file_exists($cache_file)) {
    $json = file_get_contents($cache_file);
    $tmp = json_decode($json, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        $oil = array_merge($oil, $tmp);
    }
}

$aal = $oil['aal'];
$contribution = round($aal * 1.8, 1);

// === 2. ЭКСПОРТ В /factors/oil.json (для admin.php) ===
$factors_dir = __DIR__ . '/factors';
if (!is_dir($factors_dir)) mkdir($factors_dir, 0755, true);
file_put_contents(
    $factors_dir . '/oil.json',
    json_encode([
        'aal' => $aal,
        'last_update' => $oil['last_update'],
        'active_flights' => 0,
        'total_flights' => 0
    ], 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.0, maximum-scale=1.0, user-scalable=no">
    <title>Волатильность нефти WTI | Avatiah Security Index</title>
    <meta name="description" content="AAL <?= $aal ?>. Волатильность: <?= $oil['volatility'] ?>. <?= $oil['last_update'] ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root{--bg:#0a0e1a;--card:#1a2332;--border:#2d3748;--text:#e2e8f0;--green:#10b981;--yellow:#f59e0b;--orange:#f97316;--red:#ef4444;--font-base:1rem;--font-sm:.875rem;--font-xs:.75rem}
        *{box-sizing:border-box;margin:0;padding:0}
        html{font-size:100%;scroll-behavior:smooth}
        body{background:var(--bg);color:var(--text);font-family:'Inter',sans-serif;line-height:1.6;padding:clamp(.5rem,2vw,1rem);min-height:100vh;display:flex;flex-direction:column}
        .container{max-width:1600px;margin:0 auto;display:grid;gap:clamp(1rem,2.5vw,1.5rem)}
        @media(min-width:768px){.container{grid-template-columns:1fr 340px}}
        .section{background:var(--card);border-radius:12px;padding:clamp(1rem,2.5vw,1.5rem);border:1px solid var(--border)}
        .header{background:linear-gradient(135deg,#1a472a,#2e8b57);color:#fff;padding:clamp(1.5rem,4vw,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:clamp(100px,20vw,140px);height:clamp(100px,20vw,140px);border-radius:50%;margin:auto;display:flex;align-items:center;justify-content:center;font-size:clamp(2rem,6vw,3rem);font-weight:700}
        .aal-info h2{font-size:1.8rem;margin:.5rem 0}
        .chart-container{position:relative;height:340px;margin:1.5rem 0;background:rgba(255,255,255,.05);border-radius:8px;padding:1rem}
        .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:.75rem;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}
        .data-table{width:100%;border-collapse:collapse;margin:1rem 0;font-size:.875rem}
        .data-table th,.data-table td{padding:.75rem;text-align:left;border-bottom:1px solid var(--border)}
        .data-table th{background:rgba(255,255,255,.05);font-weight:600}
        .change-positive{color:var(--green)}.change-negative{color:var(--red)}
        .factor-list{list-style:none}.factor-list li{padding:.5rem 0;border-bottom:1px solid var(--border)}
        .sidebar .section{margin-bottom:1rem}
        .threshold-bar{width:100%;height:8px;background:#334155;border-radius:4px;overflow:hidden;margin-left:.5rem}
        .threshold-fill{height:100%;background:var(--green);width:20%}
        .threshold-2 .threshold-fill{background:var(--yellow);width:40%}
        .threshold-3 .threshold-fill{background:var(--orange);width:60%}
        .threshold-4 .threshold-fill{background:var(--red);width:80%}
        .threshold-5 .threshold-fill{background:#dc2626;width:100%}
        .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>Волатильность нефти WTI</h1>
            <p>Ормуз • Суэц • Израиль • <span id="last-update"><?= htmlspecialchars($oil['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:<?= $oil['aal_color'] ?>"><?= number_format($aal, 1) ?></div>
                <h2 id="aal-text"><?= htmlspecialchars($oil['aal_text']) ?></h2>
                <div style="display:flex;justify-content:center;gap:1rem;font-size:.95rem">
                    <div><strong id="volatility-value"><?= $oil['volatility'] ?></strong> волатильность</div>
                    <div><strong id="volatility-change"><?= $oil['volatility_change'] ?></strong> за день</div>
                </div>
                <div style="display:flex;justify-content:center;gap:1rem;font-size:.95rem;margin-top:.5rem">
                    <div>WTI: <span id="price-wti"><?= $oil['price_wti'] ?></span></div>
                    <div>Brent: <span id="price-brent"><?= $oil['price_brent'] ?></span></div>
                </div>
            </div>
            <p class="update-status" id="update-status">Обновление через <span id="countdown">30:00</span></p>
        </div>

        <!-- ГРАФИК ВСТРОЕН -->
        <div class="section">
            <h2 style="font-size:1.4rem;margin-bottom:.75rem;">График волатильности (10 дней)</h2>
            <div class="chart-container">
                <canvas id="oil-chart"></canvas>
            </div>
        </div>

        <div class="section">
            <h2 style="font-size:1.4rem;margin-bottom:.75rem;">Ключевые показатели</h2>
            <table class="data-table">
                <tr><th>Показатель</th><th>Значение</th><th>Изменение</th><th>Источник</th></tr>
                <tr><td>Волатильность WTI</td><td><strong id="table-volatility"><?= $oil['volatility'] ?></strong></td><td id="table-change" class="change-negative"><?= $oil['volatility_change'] ?></td><td>LiteFinance</td></tr>
                <tr><td>Цена WTI</td><td id="table-wti"><?= $oil['price_wti'] ?></td><td class="change-negative">-0.6%</td><td>Bloomberg</td></tr>
                <tr><td>Цена Brent</td><td id="table-brent"><?= $oil['price_brent'] ?></td><td class="change-negative">-0.4%</td><td>Reuters</td></tr>
                <tr><td>Нормальный диапазон</td><td>1–3%</td><td>-</td><td>Исторические данные</td></tr>
                <tr><td>Вклад в индекс</td><td><?= $contribution ?>/10</td><td>-</td><td>Avatiah</td></tr>
            </table>
        </div>

        <div class="section">
            <h2 style="font-size:1.4rem;margin-bottom:.75rem;">Факторы влияния</h2>
            <ul class="factor-list" id="factors-list">
                <?php foreach ($oil['factors'] as $f): ?>
                <li><?= htmlspecialchars($f) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>

        <div class="section">
            <h2 style="font-size:1.4rem;margin-bottom:.75rem;">Шкала волатильности</h2>
            <div class="aal-scale">
                <div class="scale-item <?= $aal<=1.5?'active':'' ?>" style="background:#10b98120"><div>1</div><div>Низкая<br><small>1–3%</small></div></div>
                <div class="scale-item <?= $aal>1.5&&$aal<=2.5?'active':'' ?>" style="background:#f59e0b20"><div>2</div><div>Повышенная<br><small>4–8%</small></div></div>
                <div class="scale-item"><div>3</div><div>Высокая<br><small>9–15%</small></div></div>
                <div class="scale-item"><div>4</div><div>Критическая<br><small>16–25%</small></div></div>
                <div class="scale-item"><div>5</div><div>Экстремальная<br><small>26–50%</small></div></div>
            </div>
        </div>

        <div class="section">
            <h2 style="font-size:1.4rem;margin-bottom:.75rem;">Источники</h2>
            <div style="display:grid;gap:.5rem;font-size:.875rem;">
                <?php foreach ($oil['sources'] as $s): ?>
                <a href="<?= $s['url'] ?>" target="_blank" style="color:#60a5fa;text-decoration:none;"><?= $s['name'] ?></a>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div class="sidebar">
        <div class="section">
            <h3>Пороги тревоги (AAL)</h3>
            <div style="display:flex;flex-direction:column;gap:.4rem;">
                <div style="display:flex;align-items:center;font-size:.85rem">
                    <span>1 – 1–3%</span>
                    <div class="threshold-bar"><div class="threshold-fill"></div></div>
                </div>
                <div style="display:flex;align-items:center;font-size:.85rem">
                    <span>2 – 4–8%</span>
                    <div class="threshold-bar"><div class="threshold-fill threshold-2"></div></div>
                </div>
            </div>
            <p style="margin-top:.5rem;font-size:.8rem;text-align:center">Текущий: <strong><?= number_format($aal, 1) ?></strong></p>
        </div>

        <div class="section">
            <h3>Статистика</h3>
            <p><strong>Волатильность:</strong> <span id="sidebar-volatility"><?= $oil['volatility'] ?></span></p>
            <p><strong>Тренд:</strong> <span class="change-negative">Снижение</span></p>
            <p><strong>Вклад:</strong> <?= $contribution ?>/10</p>
        </div>

        <div class="section">
            <h3>Связанные факторы</h3>
            <?php foreach ($oil['related_factors'] as $r): ?>
            <p><a href="<?= $r['name'] ?>" style="color:#60a5fa;"><?= $r['title'] ?></a> <small><?= $r['change'] ?></small></p>
            <?php endforeach; ?>
        </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>
const initialData = <?= json_encode($oil, JSON_UNESCAPED_UNICODE) ?>;
let oilChart = null;
const UPDATE_INTERVAL = 30;

function initChart(data) {
    const ctx = document.getElementById('oil-chart');
    oilChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['-10д','-9д','-8д','-7д','-6д','-5д','-4д','-3д','-2д','вчера','сегодня'],
            datasets: [{
                label: 'Волатильность WTI (%)',
                data: data.chart_data,
                borderColor: '#f59e0b',
                backgroundColor: 'rgba(245,158,11,0.1)',
                fill: true,
                tension: 0.4,
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, max: 15, ticks: { stepSize: 3 } },
                x: { ticks: { font: { size: 11 } } }
            }
        }
    });
}

function updateDOM(d) {
    document.getElementById('last-update').textContent = d.last_update;
    document.getElementById('aal-circle').textContent = d.aal.toFixed(1);
    document.getElementById('aal-circle').style.background = d.aal_color;
    document.getElementById('aal-text').textContent = d.aal_text;
    document.getElementById('volatility-value').textContent = d.volatility;
    document.getElementById('volatility-change').textContent = d.volatility_change;
    document.getElementById('price-wti').textContent = d.price_wti;
    document.getElementById('price-brent').textContent = d.price_brent;
    document.getElementById('table-volatility').textContent = d.volatility;
    document.getElementById('table-change').textContent = d.volatility_change;
    document.getElementById('table-wti').textContent = d.price_wti;
    document.getElementById('table-brent').textContent = d.price_brent;
    document.getElementById('sidebar-volatility').textContent = d.volatility;

    const list = document.getElementById('factors-list');
    list.innerHTML = '';
    d.factors.forEach(f => { const li = document.createElement('li'); li.textContent = f; list.appendChild(li); });

    if (oilChart) {
        oilChart.data.datasets[0].data = d.chart_data;
        oilChart.update('quiet');
    }
}

async function fetchData() {
    try {
        await fetch('fetch_oil.php?' + Date.now());
        const r = await fetch('oil_cache.json?' + Date.now());
        const d = await r.json();
        updateDOM(d);
        document.getElementById('update-status').textContent = 'Обновлено!';
        setTimeout(() => document.getElementById('update-status').innerHTML = 'Обновление через <span id="countdown">30:00</span>', 3000);
    } catch (e) { console.error(e); }
}

function startCountdown() {
    let secs = UPDATE_INTERVAL * 60;
    const interval = setInterval(() => {
        secs--;
        const m = String(Math.floor(secs / 60)).padStart(2, '0');
        const s = String(secs % 60).padStart(2, '0');
        const el = document.getElementById('countdown');
        if (el) el.textContent = `${m}:${s}`;
        if (secs <= 0) { clearInterval(interval); fetchData().then(startCountdown); }
    }, 1000);
}

document.addEventListener('DOMContentLoaded', () => {
    initChart(initialData);
    startCountdown();
    setTimeout(fetchData, 30000);
});
</script>
</body>
</html>