<?php
header('Content-Type: text/html; charset=utf-8');

/* -------------------------------------------------
   1. БЕЗОПАСНОЕ ПОДКЛЮЧЕНИЕ КОНФИГА
   ------------------------------------------------- */
$config_path = __DIR__ . '/../config.php';
$api_keys = [];
if (file_exists($config_path)) {
    $config = include $config_path;
    $api_keys = $config['api_keys'] ?? [];
}

/* -------------------------------------------------
   2. ПАРАМЕТРЫ ФАКТОРА
   ------------------------------------------------- */
$page_title   = "Цена нефти Brent";
$factor_id    = "oil";
$factor_name  = "Цена нефти Brent";
$factor_weight = "9.4%";

/* -------------------------------------------------
   3. ЧТЕНИЕ API (с таймаутом и без SSL-ошибок)
   ------------------------------------------------- */
$api_data = null;
$api_url  = 'https://' . $_SERVER['HTTP_HOST'] . '/api/latest.php';

$context = stream_context_create([
    'http' => ['timeout' => 8],
    'ssl'  => ['verify_peer' => false, 'verify_peer_name' => false]
]);

$api_response = @file_get_contents($api_url, false, $context);
if ($api_response !== false) {
    $api_data = json_decode($api_response, true);
}

/* -------------------------------------------------
   4. УРОВЕНЬ И ВКЛАД
   ------------------------------------------------- */
$raw_price = $api_data['components'][$factor_id]['raw'] ?? null;
$current_price = is_numeric($raw_price) ? (float)$raw_price : 85.2; // fallback

// Уровни по цене Brent
function getOilLevel(float $price): int {
    return match (true) {
        $price <= 70  => 1,
        $price <= 85  => 2,
        $price <= 100 => 3,
        $price <= 120 => 4,
        default       => 5
    };
}
$current_level = getOilLevel($current_price);

function getOilScore(int $level): float {
    return [1 => 1.8, 2 => 3.5, 3 => 5.3, 4 => 7.2, 5 => 9.0][$level] ?? 1.8;
}
$current_score = getOilScore($current_level);

$threat_color = match ($current_level) {
    1 => '#27ae60', 2 => '#f39c12', 3 => '#e67e22',
    4 => '#e74c3c', 5 => '#c0392b', default => '#95a5a6'
};

$last_update = $api_data['timestamp'] ?? date('Y-m-d H:i:s');

/* -------------------------------------------------
   5. AAL (Порог тревоги)
   ------------------------------------------------- */
$aal_level = match ($current_level) { 1=>5, 2=>4, 3=>3, 4=>2, 5=>1, default=>3 };
$aal_color = match ($aal_level) { 5=>'#27ae60', 4=>'#f39c12', 3=>'#e67e22', 2=>'#e74c3c', 1=>'#c0392b' };
$aal_text  = match ($aal_level) { 5=>'Минимальный риск', 4=>'Повышенное внимание', 3=>'Угроза', 2=>'Критическая ситуация', 1=>'Максимальная тревога' };

/* -------------------------------------------------
   6. ИСТОРИЧЕСКИЕ ДАННЫЕ ДЛЯ ГРАФИКА (10 дней)
   ------------------------------------------------- */
$historical_oil = [72.5, 74.1, 76.8, 79.3, 81.0, 83.2, 84.9, 85.7, 85.2, $current_price];
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?> | Avatiah Security Index</title>

    <!-- Шрифт и Chart.js -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>

    <!-- Общий CSS + локальные стили -->
    <style>
        <?php include __DIR__ . '/factors.css'; ?>

        /* Кнопка в шапке */
        .back-to-index-inline {
            display: inline-block;
            margin-top: 1rem;
            background: #2c3e50;
            color: white;
            padding: 0.55rem 1.1rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            font-size: 0.9rem;
            transition: background 0.2s;
        }
        .back-to-index-inline:hover { background: #34495e; }

        /* Цена */
        .price-current {
            font-size: 3rem;
            font-weight: 700;
            color: <?= $threat_color ?>;
            margin: 0.5rem 0;
        }
        .price-change {
            font-size: 1.1rem;
            color: #95a5a6;
        }
    </style>
</head>
<body>
<div class="container">

    <!-- ==================== MAIN ==================== -->
    <div class="main-content">

        <!-- Header -->
        <div class="header">
            <h1><?= $factor_name ?></h1>
            <p class="subtitle">Вклад в Avatiah Security Index: <?= $factor_weight ?></p>
            <a href="/" class="back-to-index-inline">Назад к общему индексу</a>
        </div>

        <!-- Уровень + AAL -->
        <div class="section">
            <div class="level-indicator">
                <div class="level-circle" style="background:<?= $threat_color ?>;"><?= $current_level ?></div>
                <div class="level-description">Повышенная волатильность</div>
            </div>

            <p style="text-align:center; margin:1rem 0;">
                <span class="price-current">$<?= number_format($current_price, 2) ?></span><br>
                <span class="price-change">+0.5% за 24 часа</span>
            </p>

            <!-- AAL -->
            <div style="margin-top: 1rem; text-align: center;">
                <div style="display: inline-block; background: <?= $aal_color ?>; color: white; padding: 0.5rem 1rem; border-radius: 8px; font-weight: 600; font-size: 1.1rem;">
                    AAL <?= $aal_level ?>
                </div>
                <p style="margin: 0.5rem 0 0; color: #bdc3c7; font-size: 0.9rem;"><?= $aal_text ?></p>
            </div>
        </div>

        <!-- График -->
        <div class="section">
            <h2>График цены Brent (10 дней)</h2>
            <div class="chart-container">
                <canvas id="oil-chart"></canvas>
            </div>
        </div>

        <!-- Шкала цен -->
        <div class="section">
            <h2>Шкала воздействия</h2>
            <div class="impact-scale">
                <div class="scale-item <?= $current_level==1?'active':'' ?>">
                    <div class="scale-value">1</div>
                    <div class="scale-description">$60–70<br><small>Низкая цена</small></div>
                </div>
                <div class="scale-item <?= $current_level==2?'active':'' ?>">
                    <div class="scale-value">2</div>
                    <div class="scale-description">$70–85<br><small>Норма</small></div>
                </div>
                <div class="scale-item <?= $current_level==3?'active':'' ?>">
                    <div class="scale-value">3</div>
                    <div class="scale-description">$85–100<br><small>Риск</small></div>
                </div>
                <div class="scale-item <?= $current_level==4?'active':'' ?>">
                    <div class="scale-value">4</div>
                    <div class="scale-description">$100–120<br><small>Кризис</small></div>
                </div>
                <div class="scale-item <?= $current_level==5?'active':'' ?>">
                    <div class="scale-value">5</div>
                    <div class="scale-description">>$120<br><small>Шок</small></div>
                </div>
            </div>
        </div>

        <!-- Пояснение -->
        <div class="section">
            <h2>Влияние на индекс</h2>
            <div class="info-card">
                <p>Рост цен на нефть выше <strong>$100</strong> усиливает давление на экономику Израиля, Ирана и союзников.</p>
                <p>Текущий уровень: <strong><?= $current_level ?>/5</strong> → Вклад: <strong><?= number_format($current_score,1) ?>/10</strong></p>
            </div>
        </div>

    </div>
    <!-- ==================== /MAIN ==================== -->

    <!-- ==================== SIDEBAR ==================== -->
    <div class="sidebar">

        <!-- Вес -->
        <div class="section">
            <h2>Вес в индексе</h2>
            <div class="info-card">
                <div style="text-align:center;">
                    <div style="font-size:3rem;font-weight:bold;color:#e74c3c;">9.4%</div>
                    <div style="font-size:1.2rem;">Четвёртый по значимости</div>
                </div>
            </div>
        </div>

        <!-- Пороги AAL -->
        <div class="section">
            <h2>Пороги тревоги (AAL)</h2>
            <div class="info-card warning">
                <p><strong>AAL 5:</strong> $60–70</p>
                <p><strong>AAL 4:</strong> $70–85</p>
                <p><strong>AAL 3:</strong> $85–100</p>
                <p><strong>AAL 2:</strong> $100–120</p>
                <p><strong>AAL 1:</strong> >$120</p>
            </div>
        </div>

        <!-- Статистика -->
        <div class="section">
            <h2>Статистика</h2>
            <div class="info-card">
                <p><strong>Текущая цена:</strong> $<?= number_format($current_price, 2) ?></p>
                <p><strong>Уровень:</strong> <?= $current_level ?>/5</p>
                <p><strong>Вклад:</strong> <?= number_format($current_score,1) ?>/10</p>
            </div>
        </div>

        <!-- Источники -->
        <div class="section">
            <h2>Источники</h2>
            <div class="info-card">
                <p><a href="https://www.eia.gov" target="_blank">EIA.gov</a></p>
                <p><a href="https://www.bloomberg.com/energy" target="_blank">Bloomberg</a></p>
                <p><a href="https://www.tradingview.com" target="_blank">TradingView</a></p>
            </div>
        </div>

    </div>
    <!-- ==================== /SIDEBAR ==================== -->

</div>

<!-- ==================== FOOTER ==================== -->
<?php include __DIR__ . '/../footer.php'; ?>

<!-- ==================== CHART ==================== -->
<script>
document.addEventListener('DOMContentLoaded', () => {
    const ctx = document.getElementById('oil-chart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['-10д','-9д','-8д','-7д','-6д','-5д','-4д','-3д','-2д','сегодня'],
            datasets: [{
                label: 'Цена Brent ($)',
                data: <?= json_encode($historical_oil) ?>,
                borderColor: '#f39c12',
                backgroundColor: 'rgba(243,156,18,0.1)',
                tension: 0.4,
                fill: true,
                pointBackgroundColor: '#f39c12',
                pointRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return '$' + context.parsed.y.toFixed(2);
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    ticks: {
                        callback: function(value) { return '$' + value; }
                    },
                    grid: { color: 'rgba(255,255,255,0.05)' }
                },
                x: { grid: { display: false } }
            }
        }
    });
});
</script>
</body>
</html>