<?php
/* energy.php – Волатильность энергии | Avatiah Security Index
   Обновление: каждые 30 мин через JS (без cron)
   Кэш: energy_cache.json
   API: fetch_energy.php
   Дата: 01.11.2025 10:00 UTC
   Актуальные данные: Henry Hub 3.36%, AAL 3, вклад 5.3%
*/

date_default_timezone_set('UTC');
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');

$update_interval = 30; // Каждые 30 минут

// --- 1. Чтение кэша (все данные динамические) ---
$cache_file = __DIR__ . '/energy_cache.json';
$energy = json_decode(file_get_contents($cache_file), true) ?: [
    'last_update' => '01.11.2025 10:00 UTC',
    'aal' => 3,
    'aal_text' => 'Высокая волатильность',
    'aal_color' => '#f97316',
    'volatility' => 3.36,
    'price' => 3.28,
    'price_change' => +2.1,
    'chart_data' => [1.2, 1.4, 1.8, 2.1, 2.3, 2.6, 2.8, 3.0, 3.1, 3.2, 3.36],
    'normal_range' => '1–2%',
    'trend' => 'Растущий',
    'markets' => [
        ['name' => 'Природный газ (Henry Hub)', 'volatility' => 3.36, 'price' => '$3.28/MMBtu', 'trend' => 'up', 'color' => '#f97316'],
        ['name' => 'Нефть WTI', 'volatility' => 12.5, 'price' => '$84.72/баррель', 'trend' => 'up', 'color' => '#f97316'],
        ['name' => 'Уголь (API2)', 'volatility' => 2.1, 'price' => '$120/тонна', 'trend' => 'stable', 'color' => '#e67e22'],
        ['name' => 'СПГ (Азия)', 'volatility' => 4.8, 'price' => '$14.5/MMBtu', 'trend' => 'up', 'color' => '#f97316']
    ],
    'risks' => [
        'Ближний Восток: Риски disruptions в Ормузском проливе',
        'Восточное Средиземноморье: Напряженность вокруг газовых месторождений',
        'Северная Европа: Уязвимость подводной инфраструктуры',
        'Азия: Конкуренция за СПГ поставки'
    ],
    'impact' => [
        ['indicator' => 'Инфляция в ЕС', 'value' => '3.8%', 'change' => '+0.4%', 'type' => 'positive'],
        ['indicator' => 'Промышленное производство', 'value' => '-1.2%', 'change' => '-0.8%', 'type' => 'negative'],
        ['indicator' => 'Транспортные издержки', 'value' => '+15%', 'change' => '+5%', 'type' => 'positive'],
        ['indicator' => 'Курс EUR/USD', 'value' => '1.08', 'change' => '-0.02', 'type' => 'negative']
    ]
];

// --- 2. Расчёт AAL и вклада (динамично) ---
$aal = (int)$energy['aal'];
$contribution = round($aal * 1.34, 1); // 6.7 / 5 = 1.34

// --- 3. Синхронизация с 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']['energy'] = [
    'aal' => $aal,
    'last_update' => $energy['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));

// --- 4. JS-данные (динамично) ---
$js_data = json_encode([
    'chart_data' => $energy['chart_data'],
    'aal_color' => $energy['aal_color'],
    'last_update' => $energy['last_update']
], JSON_UNESCAPED_UNICODE);
?>
<!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>Волатильность энергии | Avatiah Security Index</title>
    <meta name="description" content="AAL <?= $aal ?>. Волатильность Henry Hub: <?= $energy['volatility'] ?>%. <?= $energy['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;--darkred:#dc2626;--accent:#e67e22;--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}}
        @media(min-width:1200px){.container{grid-template-columns:1fr 360px}}
        .section{background:var(--card);border-radius:12px;padding:clamp(1rem,2.5vw,1.5rem);border:1px solid var(--border)}
        .header{background:linear-gradient(135deg,#d35400,#e67e22);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}
        .header p{font-size:clamp(.9rem,2vw,1rem);opacity:.9}
        .back-link{display:inline-block;margin-top:1rem;color:#fff;text-decoration:underline;font-size:clamp(.8rem,1.8vw,.9rem)}
        .aal-circle{width:clamp(100px,20vw,140px);height:clamp(100px,20vw,140px);border-radius:50%;margin:0 auto 1rem;display:flex;align-items:center;justify-content:center;font-size:clamp(2rem,6vw,3rem);font-weight:700}
        .aal-info{text-align:center}
        .aal-info h2{font-size:clamp(1.3rem,4vw,1.8rem);margin:.5rem 0}
        .aal-stats{display:flex;flex-wrap:wrap;justify-content:center;gap:.75rem;margin:.75rem 0;font-size:clamp(.85rem,2vw,.95rem)}
        .sources{text-align:center;font-size:var(--font-xs);color:#94a3b8;margin-top:.5rem}
        .chart-container{position:relative;height:clamp(280px,45vw,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:clamp(.6rem,1.5vw,.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}
        .data-table{width:100%;border-collapse:collapse;margin:1rem 0;font-size:var(--font-sm)}
        .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}
        .price-indicator{font-size:3rem;font-weight:bold;text-align:center;margin:1rem 0;color:var(--accent)}
        .change-positive{color:var(--green)}
        .change-negative{color:var(--red)}
        .metric-highlight{background:rgba(230,126,34,.1);padding:1rem;border-radius:8px;border-left:4px solid var(--accent);margin:1rem 0}
        .risk-list{list-style:none;padding:0}
        .risk-item{padding:.5rem 0;border-bottom:1px solid var(--border)}
        .risk-item:last-child{border-bottom:none}
        .sidebar .section{margin-bottom:1rem}
        .sidebar h3{font-size:clamp(1rem,2.5vw,1.1rem);margin-bottom:.5rem}
        .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 ease}
        .threshold-1 .threshold-fill{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:var(--darkred);width:100%}
        .current-aal{font-weight:700}
        .footer{margin-top:auto;background:#111827;padding:clamp(1.5rem,4vw,2rem);border-top:1px solid var(--border);text-align:center;font-size:var(--font-sm);color:#94a3b8}
        .footer a{color:inherit;text-decoration:underline}
        .update-status{font-size:.8rem;color:#10b981;text-align:center;margin-top:.5rem}
        @media(max-width:480px){.aal-stats{flex-direction:column;align-items:center}.aal-scale{grid-template-columns:1fr}}
        @media(min-width:768px) and (max-width:992px){.container{grid-template-columns:1fr}}
    </style>
</head>
<body>
<div class="container">
    <div class="main-content">
        <div class="header">
            <h1>Волатильность энергии</h1>
            <p>Природный газ • Нефть • СПГ | <span id="last-update"><?= htmlspecialchars($energy['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:<?= $energy['aal_color'] ?>"><?= $aal ?>.0</div>
                <h2 id="aal-text"><?= htmlspecialchars($energy['aal_text']) ?></h2>
                <div class="price-indicator" id="volatility-value"><?= $energy['volatility'] ?>%</div>
                <div class="aal-stats">
                    <div><strong>Henry Hub</strong> $<span id="price-value"><?= $energy['price'] ?></span>/MMBtu</div>
                    <div><strong>Изменение</strong> <span id="price-change" class="<?= $energy['price_change'] > 0 ? 'change-positive' : 'change-negative' ?>"> <?= $energy['price_change'] > 0 ? '+' : '' ?><?= $energy['price_change'] ?>%</span></div>
                </div>
            </div>
            <p class="sources">Обновлено: <span id="sources-update"><?= htmlspecialchars($energy['last_update']) ?></span> | CME, ICE, EIA</p>
            <p class="update-status" id="update-status">Обновление через <span id="countdown">30:00</span></p>
        </div>

        <div class="section">
            <h2 style="font-size:clamp(1.2rem,3vw,1.4rem);margin-bottom:.75rem;">Волатильность Henry Hub (10 дней)</h2>
            <div class="chart-container"><canvas id="energy-chart"></canvas></div>
        </div>

        <div class="section">
            <h2 style="font-size:clamp(1.2rem,3vw,1.4rem);margin-bottom:.75rem;">Сравнение энергоносителей</h2>
            <table class="data-table">
                <tr><th>Энергоноситель</th><th>Волатильность</th><th>Цена</th><th>Тренд</th></tr>
                <?php foreach ($energy['markets'] as $m): ?>
                <tr>
                    <td><strong><?= htmlspecialchars($m['name']) ?></strong></td>
                    <td><?= $m['volatility'] ?>%</td>
                    <td><?= htmlspecialchars($m['price']) ?></td>
                    <td><span style="color:<?= $m['color'] ?>"> <?= $m['trend'] === 'up' ? 'Растущий' : ($m['trend'] === 'stable' ? 'Стабильный' : 'Падающий') ?></span></td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>

        <div class="section">
            <h2 style="font-size:clamp(1.2rem,3vw,1.4rem);margin-bottom:.75rem;">Ключевые региональные риски</h2>
            <ul class="risk-list">
                <?php foreach ($energy['risks'] as $r): ?>
                <li class="risk-item"><?= htmlspecialchars($r) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>

        <div class="section">
            <h2 style="font-size:clamp(1.2rem,3vw,1.4rem);margin-bottom:.75rem;">Влияние на экономику</h2>
            <table class="data-table">
                <tr><th>Показатель</th><th>Значение</th><th>Изменение</th></tr>
                <?php foreach ($energy['impact'] as $i): ?>
                <tr>
                    <td><?= htmlspecialchars($i['indicator']) ?></td>
                    <td><?= htmlspecialchars($i['value']) ?></td>
                    <td class="<?= $i['type'] === 'positive' ? 'change-positive' : 'change-negative' ?>">
                        <?= htmlspecialchars($i['change']) ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>

        <div class="section">
            <h2 style="font-size:clamp(1.2rem,3vw,1.4rem);margin-bottom:.75rem;">Шкала энерговоздействия</h2>
            <div class="aal-scale">
                <div class="scale-item <?= $aal==1?'active':'' ?>" style="background:#10b98120"><div>1</div><div>Низкая<br><small>1–2%</small></div></div>
                <div class="scale-item <?= $aal==2?'active':'' ?>" style="background:#f59e0b20"><div>2</div><div>Повышенная<br><small>2.1–3%</small></div></div>
                <div class="scale-item <?= $aal==3?'active':'' ?>" style="background:#f9731620"><div>3</div><div>Высокая<br><small>3.1–4%</small></div></div>
                <div class="scale-item <?= $aal==4?'active':'' ?>" style="background:#ef444420"><div>4</div><div>Критическая<br><small>4.1–5%</small></div></div>
                <div class="scale-item <?= $aal==5?'active':'' ?>" style="background:#dc262620"><div>5</div><div>Экстремальная<br><small>5%+</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 class="threshold threshold-3"><span>3 – Риск</span><div class="threshold-bar"><div class="threshold-fill"></div></div></div>
                <div class="threshold threshold-4"><span>4 – Критично</span><div class="threshold-bar"><div class="threshold-fill"></div></div></div>
                <div class="threshold threshold-5"><span>5 – Максимум</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-vol"><?= $energy['volatility'] ?>%</span></p>
            <p><strong>Норма:</strong> <?= htmlspecialchars($energy['normal_range']) ?></p>
            <p><strong>Тренд:</strong> <?= htmlspecialchars($energy['trend']) ?></p>
            <p><strong>Вклад:</strong> <?= $contribution ?>/10</p>
        </div>

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

        <div class="section">
            <h3>Связанные факторы</h3>
            <p><a href="oil.php" style="color:var(--accent)">Нефть</a></p>
            <p><a href="navy.php" style="color:var(--accent)">ВМС</a></p>
            <p><a href="cyber.php" style="color:var(--accent)">Кибер</a></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>
const js = <?= $js_data ?>;
let chart;

/* ---------- Инициализация графика ---------- */
function initChart() {
    const ctx = document.getElementById('energy-chart').getContext('2d');
    chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['-10д','-9д','-8д','-7д','-6д','-5д','-4д','-3д','-2д','-1д','сегодня'],
            datasets: [{
                label: 'Волатильность (%)',
                data: js.chart_data,
                borderColor: '#e67e22',
                backgroundColor: 'rgba(230,126,34,0.1)',
                fill: true,
                tension: 0.4,
                pointRadius: 3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 5,
                    ticks: { stepSize: 1, callback: v => v + '%' }
                }
            }
        }
    });
}

/* ---------- Обновление без перезагрузки ---------- */
async function updateData() {
    try {
        await fetch('fetch_energy.php?' + Date.now());
        const r = await fetch('energy_cache.json?' + Date.now());
        const data = await r.json();

        document.getElementById('last-update').textContent = data.last_update;
        document.getElementById('aal-circle').textContent = data.aal + '.0';
        document.getElementById('aal-circle').style.background = data.aal_color;
        document.getElementById('aal-text').textContent = data.aal_text;
        document.getElementById('volatility-value').textContent = data.volatility + '%';
        document.getElementById('stats-vol').textContent = data.volatility + '%';
        document.getElementById('sidebar-update').textContent = new Date().toTimeString().slice(0,5);

        chart.data.datasets[0].data = data.chart_data;
        chart.update('quiet');

        document.getElementById('update-status').textContent = 'Обновлено!';
        setTimeout(() => document.getElementById('update-status').textContent = 'Обновление через 30:00', 3000);
    } catch (e) {
        console.error('Ошибка обновления:', e);
    }
}

/* ---------- Универсальный таймер обновления ---------- */
const UPDATE_INTERVAL_MINUTES = <?= $update_interval ?>;
let countdownInterval;
function startCountdown() {
    const now = Date.now();
    const next = Math.ceil(now / (UPDATE_INTERVAL_MINUTES * 60 * 1000)) * (UPDATE_INTERVAL_MINUTES * 60 * 1000);
    let remaining = next - now;

    countdownInterval = setInterval(() => {
        remaining -= 1000;
        const min = String(Math.floor(remaining / 60000)).padStart(2, '0');
        const sec = String(Math.floor((remaining % 60000) / 1000)).padStart(2, '0');
        document.getElementById('countdown').textContent = `${min}:${sec}`;
        document.getElementById('next-update').textContent = new Date(next).toTimeString().slice(0, 5);

        if (remaining <= 0) {
            clearInterval(countdownInterval);
            updateData().then(startCountdown);
        }
    }, 1000);
}

/* Запуск */
initChart();
startCountdown();
setTimeout(updateData, 30000);
</script>
</body>
</html>