<?php
session_start();
date_default_timezone_set('UTC');

// === АУТЕНТИФИКАЦИЯ ===
if (!isset($_SESSION['admin']) && ($_POST['pass'] ?? '') !== 'avatiah2025') {
    echo '<form method="post" style="text-align:center;margin:100px auto;max-width:300px;font-family:sans-serif">
        <h2 style="color:#333">Avatiah Admin</h2>
        <input type="password" name="pass" placeholder="Пароль" required style="padding:10px;font-size:16px;width:100%;margin-bottom:10px;border:1px solid #ddd;border-radius:4px">
        <button type="submit" style="padding:10px 20px;font-size:16px;background:#1e3c72;color:white;border:none;border-radius:4px;cursor:pointer">Войти</button>
    </form>';
    exit;
}
$_SESSION['admin'] = true;

// === НАСТРОЙКИ ===
$factors_dir = __DIR__ . '/factors';
$config_file = __DIR__ . '/admin_config.json';
$history_file = __DIR__ . '/history.json';
$update_log_file = __DIR__ . '/update_log.json';
if (!is_dir($factors_dir)) mkdir($factors_dir, 0755, true);

// === ЗАГРУЗКА КОНФИГУРАЦИИ ===
$config = [
    'enabled_factors' => [],
    'factor_weights' => [],
    'defcon_mode' => true,
];
if (file_exists($config_file)) {
    $tmp = json_decode(file_get_contents($config_file), true);
    if ($tmp) $config = array_merge($config, $tmp);
}

// === ОБРАБОТКА ДЕЙСТВИЙ ===
$messages = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['toggle_factor'])) {
        $factor = $_POST['toggle_factor'];
        if (in_array($factor, $config['enabled_factors'])) {
            $config['enabled_factors'] = array_values(array_diff($config['enabled_factors'], [$factor]));
            $action = 'disabled';
        } else {
            $config['enabled_factors'][] = $factor;
            $action = 'enabled';
        }
        file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));

        $history = file_exists($history_file) ? json_decode(file_get_contents($history_file), true) : [];
        $history[] = [
            'time' => date('d.m.Y H:i:s'),
            'action' => $action,
            'factor' => $factor
        ];
        $history = array_slice($history, -50);
        file_put_contents($history_file, json_encode($history, JSON_PRETTY_PRINT));

        $messages[] = ['type' => 'success', 'text' => "Фактор '$factor' " . ($action === 'enabled' ? 'включен' : 'отключен')];
    }

    if (isset($_POST['update_weight'])) {
        $factor = $_POST['factor'];
        $weight = max(0.1, min(3.0, floatval($_POST['weight'])));
        $config['factor_weights'][$factor] = $weight;
        file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));
        $messages[] = ['type' => 'success', 'text' => "Вес фактора '$factor' обновлен на $weight"];
    }

    if (isset($_POST['toggle_mode'])) {
        $config['defcon_mode'] = !$config['defcon_mode'];
        file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));
        $messages[] = ['type' => 'success', 'text' => "Режим переключен на " . ($config['defcon_mode'] ? 'DEFCON' : 'AAL')];
    }

    if (isset($_POST['logout'])) {
        session_destroy();
        header('Location: admin.php');
        exit;
    }

    if (isset($_POST['force_update'])) {
        $factor = $_POST['force_update'];
        $update_script = __DIR__ . '/factors/fetch_' . $factor . '.php';
        $success = false;
        $error_msg = '';
        if (file_exists($update_script)) {
            $result = @file_get_contents('http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/factors/fetch_' . $factor . '.php', false, stream_context_create(['http' => ['timeout' => 10]]));
            if ($result !== false) {
                $success = true;
                $messages[] = ['type' => 'success', 'text' => "Фактор '$factor' обновлен успешно"];
            } else {
                $error_msg = "Таймаут или недоступно";
            }
        } elseif ($factor === 'navy') {
            $result = @file_get_contents('http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/fetch_navy.php', false, stream_context_create(['http' => ['timeout' => 10]]));
            if ($result !== false) {
                $success = true;
                $messages[] = ['type' => 'success', 'text' => "Navy обновлен успешно"];
            } else {
                $error_msg = "Таймаут Navy";
            }
        } else {
            $error_msg = "Скрипт fetch_{$factor}.php не найден";
        }

        $update_log = file_exists($update_log_file) ? json_decode(file_get_contents($update_log_file), true) : [];
        $update_log[] = [
            'time' => date('d.m.Y H:i:s'),
            'factor' => $factor,
            'success' => $success,
            'error' => $error_msg
        ];
        $update_log = array_slice($update_log, -20);
        file_put_contents($update_log_file, json_encode($update_log, JSON_PRETTY_PRINT));

        if ($error_msg) $messages[] = ['type' => 'error', 'text' => $error_msg];
    }

    // === ОБНОВЛЕНИЕ ВСЕХ С АНАЛИЗОМ ===
    if (isset($_POST['update_all'])) {
        $updated = [];
        $failed = [];
        $missing_scripts = [];
        $timeout_errors = [];
        $json_errors = [];
        $other_errors = [];

        foreach (glob($factors_dir . '/*.json') as $file) {
            $factor_name = pathinfo($file, PATHINFO_FILENAME);
            $fetch_script = __DIR__ . '/factors/fetch_' . $factor_name . '.php';
            $fetch_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/fetch_' . $factor_name . '.php';
            $navy_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/fetch_navy.php';

            if (!file_exists($fetch_script) && $factor_name !== 'navy') {
                $missing_scripts[] = $factor_name;
                $failed[] = $factor_name;
                continue;
            }

            $url = ($factor_name === 'navy') ? $navy_url : $fetch_url;
            $context = stream_context_create(['http' => ['timeout' => 12]]);
            $result = @file_get_contents($url, false, $context);

            if ($result === false) {
                $last_error = error_get_last();
                $msg = $last_error['message'] ?? '';
                if (strpos($msg, 'timed out') !== false) {
                    $timeout_errors[] = $factor_name;
                } else {
                    $other_errors[] = $factor_name;
                }
                $failed[] = $factor_name;
                continue;
            }

            $data = json_decode($result, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                $json_errors[] = $factor_name;
                $failed[] = $factor_name;
                continue;
            }

            if (!isset($data['aal']) || !isset($data['last_update'])) {
                $json_errors[] = $factor_name . " (нет aal/last_update)";
                $failed[] = $factor_name;
                continue;
            }

            $target = $factors_dir . '/' . $factor_name . '.json';
            if (file_put_contents($target, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)) !== false) {
                $updated[] = $factor_name;
            } else {
                $other_errors[] = $factor_name . " (не записано)";
                $failed[] = $factor_name;
            }
        }

        $update_log = file_exists($update_log_file) ? json_decode(file_get_contents($update_log_file), true) : [];
        $update_log[] = [
            'time' => date('d.m.Y H:i:s'),
            'action' => 'update_all',
            'updated' => $updated,
            'failed' => $failed,
            'missing' => $missing_scripts,
            'timeout' => $timeout_errors,
            'json' => $json_errors,
            'other' => $other_errors
        ];
        $update_log = array_slice($update_log, -50);
        file_put_contents($update_log_file, json_encode($update_log, JSON_PRETTY_PRINT));

        $msg = "Успешно: " . count($updated) . ", Ошибок: " . count($failed);
        if (!empty($missing_scripts)) $msg .= " | Нет скриптов: " . count($missing_scripts);
        $messages[] = ['type' => count($failed) == 0 ? 'success' : 'error', 'text' => $msg];
    }

    $_SESSION['admin_messages'] = $messages;
    header('Location: admin.php');
    exit;
}

// === СООБЩЕНИЯ ===
$messages = $_SESSION['admin_messages'] ?? [];
unset($_SESSION['admin_messages']);

// === АНАЛИЗ ФАКТОРОВ ===
$factor_analysis = [];
$files = glob($factors_dir . '/*.json') ?: [];
$outdated_count = 0;
$missing_script_count = 0;

foreach ($files as $file) {
    $name = pathinfo($file, PATHINFO_FILENAME);
    $json = file_get_contents($file);
    $data = json_decode($json, true);
    $script_exists = file_exists(__DIR__ . '/factors/fetch_' . $name . '.php') || ($name === 'navy' && file_exists(__DIR__ . '/fetch_navy.php'));

    $last_update = isset($data['last_update']) ? $data['last_update'] : null;
    $is_outdated = ($last_update && (time() - strtotime($last_update)) > 86400);
    $enabled = in_array($name, $config['enabled_factors']) || empty($config['enabled_factors']);

    if ($is_outdated && $enabled) $outdated_count++;
    if (!$script_exists) $missing_script_count++;

    $status = 'OK';
    $reason = '';
    if (!$script_exists) {
        $status = 'Нет скрипта';
        $reason = 'fetch_' . $name . '.php отсутствует';
    } elseif (!$data || json_last_error() !== JSON_ERROR_NONE) {
        $status = 'JSON ошибка';
        $reason = 'Файл повреждён';
    } elseif (!isset($data['aal'])) {
        $status = 'Нет AAL';
        $reason = 'Поле aal отсутствует';
    } elseif ($is_outdated) {
        $status = 'Устарело';
        $reason = 'Обновлено >24ч назад';
    }

    $factor_analysis[$name] = [
        'name' => $name,
        'human_name' => ucwords(str_replace(['_', '-'], ' ', $name)),
        'status' => $status,
        'reason' => $reason,
        'last_update' => $last_update ?? '—',
        'is_outdated' => $is_outdated,
        'enabled' => $enabled,
        'script_exists' => $script_exists,
        'aal' => isset($data['aal']) ? $data['aal'] : null,
        'weight' => $config['factor_weights'][$name] ?? 1.0,
        'contribution' => 0
    ];
}

// === РАСЧЁТ ИНДЕКСА ===
$sum = $sum_weights = 0;
$last_update_global = '';

foreach ($factor_analysis as $name => $f) {
    if ($f['enabled'] && $f['aal'] !== null) {
        $weighted = $f['aal'] * $f['weight'];
        $sum += $weighted;
        $sum_weights += $f['weight'];
        $factor_analysis[$name]['contribution'] = ($sum_weights > 0) ? round(($weighted / $sum) * 100, 1) : 0;
    }
    if ($f['last_update'] > $last_update_global) {
        $last_update_global = $f['last_update'];
    }
}

$total_aal = $sum_weights > 0 ? round($sum / $sum_weights, 2) : 1.0;
$defcon = $config['defcon_mode'] ? max(1, min(5, 6 - round($total_aal))) : $total_aal;

function getDefconColor($level) {
    $colors = [5 => '#10b981', 4 => '#f59e0b', 3 => '#f97316', 2 => '#ef4444', 1 => '#dc2626'];
    return $colors[$level] ?? '#6b7280';
}

function getDefconText($level) {
    $texts = [5 => 'Минимальная угроза', 4 => 'Повышенная готовность', 3 => 'Значительная угроза', 2 => 'Высокая угроза', 1 => 'КРИТИЧЕСКАЯ УГРОЗА'];
    return $texts[$level] ?? 'Неизвестно';
}

$display_value = $config['defcon_mode'] ? $defcon : $total_aal;
$display_text = $config['defcon_mode'] ? getDefconText($defcon) : getDefconText(6 - round($total_aal));
$display_color = getDefconColor($config['defcon_mode'] ? $defcon : (6 - round($total_aal)));

// === total_index.json ===
$total_index = [
    'total_aal' => $total_aal,
    'defcon' => $defcon,
    'mode' => $config['defcon_mode'] ? 'DEFCON' : 'AAL',
    'factor_count' => count(array_filter($factor_analysis, function($f) { return $f['enabled'] && $f['aal'] !== null; })),
    'total_factors' => count($factor_analysis),
    'last_update' => $last_update_global ?: date('d.m.Y H:i') . ' UTC',
    'factors' => array_values($factor_analysis)
];
file_put_contents(__DIR__ . '/total_index.json', json_encode($total_index, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

// === ЛОГИ ===
$history = file_exists($history_file) ? json_decode(file_get_contents($history_file), true) : [];
$history = array_reverse(array_slice($history, -10));

$update_log = file_exists($update_log_file) ? json_decode(file_get_contents($update_log_file), true) : [];
$update_log = array_reverse(array_slice($update_log, -15));
?>

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Avatiah Admin - Анализ</title>
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';">
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: #0a0e1a; color: #e2e8f0; padding: 20px; }
        .container { max-width: 1600px; margin: 0 auto; }
        .header { background: linear-gradient(135deg, #1e3c72, #2a5298); padding: 30px; border-radius: 16px; text-align: center; margin-bottom: 30px; }
        .header h1 { font-size: 2.5em; }
        .card { background: #1a2332; border: 1px solid #2d3748; border-radius: 12px; padding: 25px; margin-bottom: 20px; }
        .card h2 { color: #60a5fa; border-bottom: 2px solid #2d3748; padding-bottom: 10px; }
        .message { padding: 10px; border-radius: 8px; margin-bottom: 10px; }
        .message.success { background: rgba(16,185,129,0.2); color: #10b981; border-left: 4px solid #10b981; }
        .message.error { background: rgba(239,68,68,0.2); color: #ef4444; border-left: 4px solid #ef4444; }
        table { width: 100%; border-collapse: collapse; font-size: 0.9em; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #2d3748; }
        th { background: #1e293b; color: #60a5fa; }
        .status-ok { color: #10b981; }
        .status-error { color: #ef4444; }
        .status-warning { color: #f97316; }
        .update-all button { background: #059669; color: white; padding: 12px 30px; border: none; border-radius: 8px; cursor: pointer; }
        .logout button { background: #dc2626; color: white; padding: 12px 30px; border: none; border-radius: 8px; cursor: pointer; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Avatiah Admin - Анализ обновлений</h1>
        </div>

        <?php if (!empty($messages)): ?>
            <div class="messages">
                <?php foreach ($messages as $msg): ?>
                    <div class="message <?= $msg['type'] ?>"><?= htmlspecialchars($msg['text']) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($outdated_count > 0): ?>
            <div class="card" style="border-left:4px solid #ef4444;background:rgba(239,68,68,0.1);">
                <strong>Устарело:</strong> <?= $outdated_count ?> активных факторов (>24ч)
            </div>
        <?php endif; ?>

        <div class="card">
            <div style="text-align:center;padding:30px;">
                <div style="font-size:5em;color:<?= $display_color ?>;font-weight:bold;">
                    <?= $config['defcon_mode'] ? "DEFCON $defcon" : "AAL $total_aal" ?>
                </div>
                <div style="color:<?= $display_color ?>;font-size:1.5em;"><?= $display_text ?></div>
            </div>
        </div>

        <div style="text-align:center;margin:20px 0;">
            <form method="post" class="update-all" style="display:inline;">
                <button type="submit" name="update_all">Обновить все (анализ)</button>
            </form>
        </div>

        <div class="card">
            <h2>Статус факторов</h2>
            <table>
                <tr>
                    <th>Фактор</th>
                    <th>Статус</th>
                    <th>Причина</th>
                    <th>AAL</th>
                    <th>Вклад</th>
                    <th>Обновлено</th>
                    <th>Действие</th>
                </tr>
                <?php foreach ($factor_analysis as $f): 
                    $cls = $f['status'] === 'OK' ? 'status-ok' : ($f['is_outdated'] ? 'status-warning' : 'status-error');
                ?>
                <tr>
                    <td><strong><?= htmlspecialchars($f['human_name']) ?></strong></td>
                    <td><span class="<?= $cls ?>"><?= $f['status'] ?></span></td>
                    <td style="font-size:0.8em;color:#94a3b8;"><?= htmlspecialchars($f['reason']) ?></td>
                    <td><?= $f['aal'] ?? '—' ?></td>
                    <td><?= $f['contribution'] ?>%</td>
                    <td style="color:<?= $f['is_outdated'] ? '#ef4444' : '#10b981' ?>"><?= $f['last_update'] ?></td>
                    <td>
                        <?php if ($f['script_exists']): ?>
                            <form method="post" style="display:inline;">
                                <input type="hidden" name="force_update" value="<?= $f['name'] ?>">
                                <button type="submit" style="font-size:0.8em;padding:3px 6px;">Upd</button>
                            </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>

        <div style="text-align:center;" class="logout">
            <form method="post">
                <button type="submit" name="logout">Выйти</button>
            </form>
        </div>
    </div>
</body>
</html>