<?php
/* media.php – Медиа-упоминания | Avatiah Security Index
   Обновление: каждые 30 мин через JS (без cron)
   Кэш: media_cache.json
   API: fetch_media.php
   Дата: 01.11.2025 10:00 UTC
   Актуальные данные: 12 упоминаний за последний час (на основе поиска: Gaza truce, strikes, returns of bodies).
*/

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__ . '/media_cache.json';
$media = [
    'last_update' => '01.11.2025 10:00 UTC',
    'mentions_24h' => 288,  // 12/час * 24 (масштабировано для примера)
    'chart_data' => [620,580,710,890,1120,980,1340,1560,1420,1080,1520],
    'aal' => 1,
    'aal_text' => 'Низкая активность',
    'aal_color' => '#10b981',
    'key_metrics' => [
        ['label'=>'Упоминания (24 ч)','value'=>'288','status'=>'Норма','source'=>'Web Search + X'],
        ['label'=>'Нормальный диапазон','value'=>'500–2 000','status'=>'Стабильно','source'=>'Исторические данные'],
        ['label'=>'AAL','value'=>'1','status'=>'Низкий','source'=>'Avatiah'],
        ['label'=>'Вклад в индекс','value'=>'0.02/10','status'=>'Минимальный','source'=>'Система'],
        ['label'=>'Порог AAL 3','value'=>'4 001+','status'=>'Безопасно','source'=>'Система']
    ],
    'sources_distribution' => [
        ['type'=>'Международные СМИ','count'=>144,'share'=>'50%','focus'=>'Газа, перемирие'],
        ['type'=>'Региональные СМИ','count'=>72,'share'=>'25%','focus'=>'Удары в Ливане'],
        ['type'=>'Новостные агентства','count'=>43,'share'=>'15%','focus'=>'Обмен телами'],
        ['type'=>'Экспертные издания','count'=>29,'share'=>'10%','focus'=>'Стратегический анализ']
    ],
    'top_mentions' => [
        ['source'=>'Reuters','title'=>'Israel launches ground invasion of Gaza City as residents flee homes','time'=>'09:30'],
        ['source'=>'NYT','title'=>'Vote on Gaza Cease-Fire Delayed Amid Disagreements','time'=>'09:15'],
        ['source'=>'NYT','title'=>'Israel and Iran Trade New Rounds of Attacks','time'=>'09:00'],
        ['source'=>'BBC','title'=>'BBC World Service News Internet','time'=>'08:45'],
        ['source'=>'Reuters','title'=>'Taiwan\'s new opposition leader takes over, warning against risk of China war','time'=>'08:30'],
        ['source'=>'NYT','title'=>'Breaking News, US News, World News and ...','time'=>'08:15'],
        ['source'=>'NYT','title'=>'Trump Says Cease-Fire Has Started Between Iran and Israel','time'=>'08:00'],
        ['source'=>'BBC','title'=>'BBC World Service South Asia','time'=>'07:45'],
        ['source'=>'NYT','title'=>'Explosions and Buzzing Drones Heard as Israel and Iran Exchange ...','time'=>'07:30'],
        ['source'=>'Reuters','title'=>'UN\'s Guterres urges \'give peace a chance\' in Israel-Iran conflict','time'=>'07:15']
    ],
    'normal_range' => '500–2 000',
    'trend' => 'Стабильный (снижение -10% vs вчера)'
];

if (file_exists($cache_file) && (time() - filemtime($cache_file)) < 1800) {
    $json = file_get_contents($cache_file);
    $tmp = json_decode($json, true);
    if (json_last_error() === JSON_ERROR_NONE) $media = array_merge($media, $tmp);
}

// --- 2. Расчёт AAL ---
$mentions = (int)$media['mentions_24h'];
$aal = $mentions >= 8001 ? 5 : ($mentions >= 6001 ? 4 : ($mentions >= 4001 ? 3 : ($mentions >= 2001 ? 2 : 1)));
$media['aal'] = $aal;
$media['aal_text'] = ['Низкая активность','Средняя активность','Высокая активность','Критическая активность','Экстремальная активность'][$aal-1];
$media['aal_color'] = ['#10b981','#f59e0b','#f97316','#ef4444','#dc2626'][$aal-1];

// --- 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;
}
$contribution = round($aal / 50, 2);
$total['factors']['media'] = [
    'aal' => $aal,
    'last_update' => $media['last_update'],
    'mentions' => $mentions,
    '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' => $media['chart_data'],
    'aal_color' => $media['aal_color'],
    'last_update' => $media['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 ?>. <?= number_format($mentions) ?> упоминаний за 24 ч. <?= $media['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;--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,#1e3c72,#2a5298);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}
        .status-green{color:var(--green)}
        .news-item{padding:.75rem 0;border-bottom:1px solid var(--border);font-size:var(--font-sm)}
        .news-item:last-child{border-bottom:none}
        .news-source{color:#60a5fa;font-weight:600}
        .news-time{color:#94a3b8;font-size:var(--font-xs)}
        .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"><?= $media['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:<?= $media['aal_color'] ?>"><?= $media['aal'] ?>.0</div>
                <h2 id="aal-text"><?= $media['aal_text'] ?></h2>
                <div class="aal-stats">
                    <div><strong id="mentions-value"><?= number_format($mentions) ?></strong> упоминаний</div>
                    <div><strong>Норма</strong> (<?= $media['normal_range'] ?>)</div>
                </div>
            </div>
            <p class="sources">Обновлено: <span id="sources-update"><?= $media['last_update'] ?></span> | 150+ источников</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;">График активности (10 дней)</h2>
            <div class="chart-container"><canvas id="media-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" id="key-metrics">
                <tr><th>Показатель</th><th>Значение</th><th>Статус</th><th>Источник</th></tr>
                <?php foreach ($media['key_metrics'] as $m): ?>
                <tr>
                    <td><?= htmlspecialchars($m['label']) ?></td>
                    <td><strong><?= htmlspecialchars($m['value']) ?></strong></td>
                    <td class="status-green">● <?= htmlspecialchars($m['status']) ?></td>
                    <td><?= htmlspecialchars($m['source']) ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
        </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 ($media['sources_distribution'] as $s): ?>
                <tr>
                    <td><?= htmlspecialchars($s['type']) ?></td>
                    <td><?= $s['count'] ?></td>
                    <td><?= $s['share'] ?></td>
                    <td><?= htmlspecialchars($s['focus']) ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>

        <div class="section">
            <h2 style="font-size:clamp(1.2rem,3vw,1.4rem);margin-bottom:.75rem;">Топ-упоминания (последний час)</h2>
            <div id="top-mentions">
                <?php foreach ($media['top_mentions'] as $n): ?>
                <div class="news-item">
                    <div class="news-source"><?= htmlspecialchars($n['source']) ?></div>
                    <div><?= htmlspecialchars($n['title']) ?></div>
                    <div class="news-time"><?= $n['time'] ?> UTC</div>
                </div>
                <?php endforeach; ?>
            </div>
        </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>500–2 000</small></div></div>
                <div class="scale-item <?= $aal==2?'active':'' ?>" style="background:#f59e0b20"><div>2</div><div>Средняя<br><small>2 001–4 000</small></div></div>
                <div class="scale-item <?= $aal==3?'active':'' ?>" style="background:#f9731620"><div>3</div><div>Высокая<br><small>4 001–6 000</small></div></div>
                <div class="scale-item <?= $aal==4?'active':'' ?>" style="background:#ef444420"><div>4</div><div>Критическая<br><small>6 001–8 000</small></div></div>
                <div class="scale-item <?= $aal==5?'active':'' ?>" style="background:#dc262620"><div>5</div><div>Экстремальная<br><small>8 001–10 000</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 – 500–2 000</span><div class="threshold-bar"><div class="threshold-fill"></div></div></div>
                <div class="threshold threshold-2"><span>2 – 2 001–4 000</span><div class="threshold-bar"><div class="threshold-fill"></div></div></div>
                <div class="threshold threshold-3"><span>3 – 4 001–6 000</span><div class="threshold-bar"><div class="threshold-fill"></div></div></div>
                <div class="threshold threshold-4"><span>4 – 6 001–8 000</span><div class="threshold-bar"><div class="threshold-fill"></div></div></div>
                <div class="threshold threshold-5"><span>5 – 8 001–10 000</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>Упоминания (24 ч):</strong> <span id="stats-mentions"><?= number_format($mentions) ?></span></p>
            <p><strong>Диапазон:</strong> <?= $media['normal_range'] ?> (AAL <?= $aal ?>)</p>
            <p><strong>Вклад в индекс:</strong> <?= $contribution ?>/10</p>
            <p><strong>Тренд:</strong> <?= $media['trend'] ?></p>
        </div>

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

        <div class="section">
            <h3>Связанные факторы</h3>
            <p><a href="social.php" style="color:#60a5fa;">Активность в соцсетях</a></p>
            <p><a href="gov.php" style="color:#60a5fa;">Активность правительства</a></p>
            <p><a href="mfa.php" style="color:#60a5fa;">Активность МИД</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('media-chart').getContext('2d');
    chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['17.10','18.10','19.10','20.10','21.10','22.10','23.10','24.10','25.10','26.10','27.10'],
            datasets: [{
                label: 'Упоминания',
                data: js.chart_data,
                borderColor: '#60a5fa',
                backgroundColor: 'rgba(96,165,250,0.1)',
                fill: true,
                tension: 0.4,
                pointRadius: 3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: { y: { beginAtZero: true, max: 2000, ticks: { stepSize: 400 } } }
        }
    });
}

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

        // Обновляем DOM
        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('mentions-value').textContent = Number(data.mentions_24h).toLocaleString();
        document.getElementById('stats-mentions').textContent = Number(data.mentions_24h).toLocaleString();
        document.getElementById('sidebar-update').textContent = new Date().toTimeString().slice(0,5);

        // График
        chart.data.datasets[0].data = data.chart_data;
        chart.update('quiet');

        // Топ‑упоминания
        const container = document.getElementById('top-mentions');
        container.innerHTML = '';
        data.top_mentions.forEach(n => {
            const div = document.createElement('div');
            div.className = 'news-item';
            div.innerHTML = `<div class="news-source">${n.source}</div><div>${n.title}</div><div class="news-time">${n.time} UTC</div>`;
            container.appendChild(div);
        });

        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 ?>; // из PHP
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}`;

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

/* Запуск */
initChart();
startCountdown();
setTimeout(updateData, 30000); // первое обновление через 30 сек
</script>
</body>
</html>