<?php
if (pathinfo($_SERVER['REQUEST_URI'], PATHINFO_EXTENSION) !== 'php') {
    http_response_code(301);
    header('Location: ' . $_SERVER['REQUEST_URI'] . '.php');
    exit;
}
header('Content-Type: text/html; charset=utf-8');

$config_path = __DIR__ . '/../config.php';
$api_keys = [];
if (file_exists($config_path)) {
    $config = include $config_path;
    $api_keys = $config['api_keys'] ?? [];
}

$page_title   = "Министерство обороны Израиля";
$factor_id    = "defense";
$factor_name  = "Минобороны Израиля";
$factor_weight = "9.8%";

$api_url = 'https://' . $_SERVER['HTTP_HOST'] . '/api/latest.php';
if (filter_var($api_url, FILTER_VALIDATE_URL) === false) {
    error_log("Invalid API URL: $api_url");
    $api_data = null;
} else {
    $context = stream_context_create(['http' => ['timeout' => 8], 'ssl' => ['verify_peer' => false]]);
    $api_response = @file_get_contents($api_url, false, $context);
    $api_data = $api_response !== false ? json_decode($api_response, true) : null;
}

$raw_level = $api_data['components'][$factor_id]['raw'] ?? null;
$current_level = is_numeric($raw_level) ? max(1, min(5, (int)$raw_level)) : 3;

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

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

$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=>'Максимальная тревога' };

$statements = [
    ['text' => 'IDF усиливает резервы на севере.', 'time' => '2 ч назад', 'tone' => 'Жёсткий'],
    ['text' => 'Готовимся к любым сценариям.', 'time' => '6 ч назад', 'tone' => 'Предупреждение']
];

$historical = [2,2,2,3,3,3,3,3,3,$current_level];

$css_content = file_exists(__DIR__ . '/factors.css') ? file_get_contents(__DIR__ . '/factors.css') : '';
?>
<!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>
    <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>
    <style>
        <?= $css_content ?: 'body{font-family:Inter,sans-serif;background:#1e1e1e;color:#ecf0f1;margin:0;padding:0}.container{display:flex;gap:2rem;max-width:1200px;margin:2rem auto;padding:0 1rem}.main-content{flex:1}.sidebar{width:300px}.header h1{font-size:2rem;margin:0}.subtitle{color:#95a5a6;font-size:0.9rem}.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}.back-to-index-inline:hover{background:#34495e}.level-circle{width:60px;height:60px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.8rem;font-weight:bold;color:white}.level-indicator{display:flex;align-items:center;gap:1rem}.chart-container{height:300px;margin:1rem 0}.info-card{background:rgba(255,255,255,0.05);border-radius:12px;padding:1rem}.statement{padding:0.8rem;border-bottom:1px solid rgba(255,255,255,0.08)}.impact-scale{display:flex;gap:1rem;justify-content:space-between}.scale-item{text-align:center;flex:1}.scale-value{width:40px;height:40px;border-radius:50%;background:#34495e;color:white;display:flex;align-items:center;justify-content:center;margin:0 auto 0.5rem;font-weight:bold}.scale-item.active .scale-value{background:#e74c3c}' ?>
    </style>
</head>
<body>
<div class="container">
    <div class="main-content">
        <div class="header">
            <h1><?= $factor_name ?></h1>
            <p class="subtitle">Вклад: <?= $factor_weight ?></p>
            <a href="/" class="back-to-index-inline">Назад к общему индексу</a>
        </div>

        <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>Уровень активности: <strong><?= $current_level ?>/5</strong></p>
            <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>Заявления</h2>
            <div class="info-card">
                <?php foreach ($statements as $s): ?>
                    <div class="statement">
                        <p><strong>"<?= htmlspecialchars($s['text']) ?>"</strong></p>
                        <p><small><?= htmlspecialchars($s['time']) ?></small></p>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="section">
            <h2>График (10 дней)</h2>
            <div class="chart-container">
                <canvas id="defense-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">Норма</div></div>
                <div class="scale-item <?= $current_level==2?'active':'' ?>"><div class="scale-value">2</div><div class="scale-description">Внимание</div></div>
                <div class="scale-item <?= $current_level==3?'active':'' ?>"><div class="scale-value">3</div><div class="scale-description">Риск</div></div>
                <div class="scale-item <?= $current_level==4?'active':'' ?>"><div class="scale-value">4</div><div class="scale-description">Кризис</div></div>
                <div class="scale-item <?= $current_level==5?'active':'' ?>"><div class="scale-value">5</div><div class="scale-description">Война</div></div>
            </div>
        </div>
    </div>

    <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.8%</div></div></div></div>
        <div class="section"><h2>AAL</h2><div class="info-card warning"><p><strong>AAL 5:</strong> Уровень 1</p><p><strong>AAL 3:</strong> Уровень 3</p></div></div>
        <div class="section"><h2>Источники</h2><div class="info-card"><p><a href="https://mod.gov.il" target="_blank">mod.gov.il</a></p></div></div>
    </div>
</div>

<?php include __DIR__ . '/../footer.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', () => {
    new Chart(document.getElementById('defense-chart').getContext('2d'), {
        type:'line', data:{labels:['-10д','-9д','-8д','-7д','-6д','-5д','-4д','-3д','-2д','сегодня'], datasets:[{data:<?= json_encode($historical) ?>,borderColor:'#e67e22',backgroundColor:'rgba(230,126,34,0.1)',tension:0.4,fill:true}]},
        options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,max:5,ticks:{stepSize:1}}}}
    });
});
</script>
</body>
</html>