<?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';

if (!is_dir($factors_dir)) mkdir($factors_dir, 0755, true);

// === ЗАГРУЗКА КОНФИГУРАЦИИ ===
$config = [
    'enabled_factors' => [],
    'factor_weights' => [],
    'defcon_mode' => true, // true = DEFCON (5-1), false = AAL (1-5)
];

if (file_exists($config_file)) {
    $tmp = json_decode(file_get_contents($config_file), true);
    if ($tmp) $config = array_merge($config, $tmp);
}

// === ОБРАБОТКА ДЕЙСТВИЙ ===
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]));
        } else {
            $config['enabled_factors'][] = $factor;
        }
        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' => in_array($factor, $config['enabled_factors']) ? 'enabled' : 'disabled',
            'factor' => $factor
        ];
        $history = array_slice($history, -50); // Последние 50 записей
        file_put_contents($history_file, json_encode($history, JSON_PRETTY_PRINT));
    }
    
    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));
    }
    
    if (isset($_POST['toggle_mode'])) {
        $config['defcon_mode'] = !$config['defcon_mode'];
        file_put_contents($config_file, json_encode($config, JSON_PRETTY_PRINT));
    }
    
    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';
        if (file_exists($update_script)) {
            file_get_contents('http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/factors/fetch_' . $factor . '.php');
        } elseif ($factor === 'navy') {
            // Прямое обновление navy
            file_get_contents('http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/fetch_navy.php');
        }
        header('Location: admin.php');
        exit;
    }
    
    if (isset($_POST['update_all'])) {
        // Обновление всех факторов
        foreach (glob($factors_dir . '/*.json') as $file) {
            $factor_name = pathinfo($file, PATHINFO_FILENAME);
            $fetch_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/fetch_' . $factor_name . '.php';
            @file_get_contents($fetch_url, false, stream_context_create(['http' => ['timeout' => 5]]));
        }
        header('Location: admin.php');
        exit;
    }
}

// === ЧТЕНИЕ ФАКТОРОВ ===
$files = glob($factors_dir . '/*.json') ?: [];
$factors = [];
$sum = $count = 0;
$last_update = '';

// DEBUG: Показать найденные файлы
// echo "<!-- DEBUG: Found files: " . implode(', ', $files) . " -->";

foreach ($files as $file) {
    $json = file_get_contents($file);
    $data = json_decode($json, true);
    if ($data && isset($data['aal'])) {
        $name = pathinfo($file, PATHINFO_FILENAME);
        $weight = $config['factor_weights'][$name] ?? 1.0;
        $enabled = in_array($name, $config['enabled_factors']) || empty($config['enabled_factors']);
        
        $factors[$name] = [
            'name' => ucwords(str_replace(['_', '-'], ' ', $name)),
            'aal' => $data['aal'],
            'last_update' => $data['last_update'] ?? '—',
            'enabled' => $enabled,
            'weight' => $weight,
            'weighted_aal' => $enabled ? ($data['aal'] * $weight) : 0
        ];
        
        if ($enabled) {
            $sum += $data['aal'] * $weight;
            $count += $weight;
        }
        
        if (($data['last_update'] ?? '') > $last_update) {
            $last_update = $data['last_update'];
        }
    }
}

// === РАСЧЕТ ИНДЕКСА ===
$total_aal = $count > 0 ? round($sum / $count, 2) : 1.0;

// Конвертация в DEFCON (инверсия: AAL 1→DEFCON 5, AAL 5→DEFCON 1)
$defcon = $config['defcon_mode'] ? (6 - round($total_aal)) : $total_aal;
$defcon = max(1, min(5, $defcon));

// === ЦВЕТА И СТАТУСЫ ===
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($factors, fn($f) => $f['enabled'])),
    'total_factors' => count($factors),
    'last_update' => $last_update ?: date('d.m.Y H:i') . ' UTC',
    'factors' => $factors
];
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)); // Последние 10
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Avatiah Admin - Security Index Control</title>
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: linear-gradient(135deg, #0a0e1a 0%, #1a2332 100%); color: #e2e8f0; min-height: 100vh; padding: 20px; }
        .container { max-width: 1400px; margin: 0 auto; }
        
        /* Header */
        .header { background: linear-gradient(135deg, #1e3c72, #2a5298); padding: 30px; border-radius: 16px; margin-bottom: 30px; text-align: center; box-shadow: 0 10px 40px rgba(0,0,0,0.3); }
        .header h1 { font-size: 2.5em; margin-bottom: 10px; text-shadow: 2px 2px 4px rgba(0,0,0,0.3); }
        .header p { font-size: 1.1em; opacity: 0.9; }
        
        /* Main Grid */
        .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; }
        @media (max-width: 1024px) { .grid { grid-template-columns: 1fr; } }
        
        /* Cards */
        .card { background: #1a2332; border: 1px solid #2d3748; border-radius: 12px; padding: 25px; box-shadow: 0 4px 20px rgba(0,0,0,0.2); }
        .card h2 { font-size: 1.5em; margin-bottom: 20px; color: #60a5fa; border-bottom: 2px solid #2d3748; padding-bottom: 10px; }
        
        /* DEFCON Display */
        .defcon-display { text-align: center; padding: 40px; background: linear-gradient(135deg, rgba(255,255,255,0.05), rgba(255,255,255,0.02)); border-radius: 12px; margin-bottom: 20px; }
        .defcon-value { font-size: 6em; font-weight: bold; margin: 20px 0; text-shadow: 0 0 20px currentColor; transition: all 0.3s ease; }
        .defcon-text { font-size: 1.5em; font-weight: 600; margin-top: 10px; }
        .defcon-subtext { font-size: 1em; opacity: 0.7; margin-top: 10px; }
        
        /* Mode Toggle */
        .mode-toggle { text-align: center; margin-bottom: 20px; }
        .mode-toggle button { padding: 12px 30px; font-size: 1.1em; border: none; border-radius: 8px; cursor: pointer; background: #2563eb; color: white; transition: all 0.3s; font-weight: 600; }
        .mode-toggle button:hover { background: #1d4ed8; transform: translateY(-2px); }
        
        /* Factor Card */
        .factor { background: rgba(255,255,255,0.05); padding: 20px; margin-bottom: 15px; border-radius: 8px; border-left: 4px solid #6b7280; transition: all 0.3s; }
        .factor.enabled { border-left-color: #10b981; background: rgba(16,185,129,0.1); }
        .factor.disabled { opacity: 0.6; }
        .factor-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .factor-name { font-size: 1.2em; font-weight: 600; }
        .factor-aal { font-size: 2em; font-weight: bold; }
        .factor-controls { display: flex; gap: 10px; align-items: center; margin-top: 10px; }
        .factor-info { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; font-size: 0.9em; color: #94a3b8; }
        
        /* Buttons */
        .btn { padding: 8px 16px; border: none; border-radius: 6px; cursor: pointer; font-size: 0.9em; transition: all 0.2s; font-weight: 500; }
        .btn-toggle { background: #059669; color: white; }
        .btn-toggle.disabled { background: #6b7280; }
        .btn-toggle:hover { transform: scale(1.05); }
        .btn-weight { background: #2563eb; color: white; padding: 6px 12px; }
        
        /* Weight Input */
        .weight-control { display: flex; align-items: center; gap: 10px; }
        .weight-control input { width: 60px; padding: 6px; border: 1px solid #2d3748; background: #0a0e1a; color: white; border-radius: 4px; text-align: center; }
        
        /* Stats */
        .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px; }
        .stat { background: rgba(255,255,255,0.05); padding: 20px; border-radius: 8px; text-align: center; }
        .stat-value { font-size: 2.5em; font-weight: bold; color: #60a5fa; }
        .stat-label { font-size: 0.9em; color: #94a3b8; margin-top: 5px; }
        
        /* History */
        .history-item { background: rgba(255,255,255,0.03); padding: 12px; margin-bottom: 8px; border-radius: 6px; display: flex; justify-content: space-between; align-items: center; font-size: 0.9em; }
        .history-time { color: #94a3b8; }
        .history-action { font-weight: 600; }
        .history-action.enabled { color: #10b981; }
        .history-action.disabled { color: #ef4444; }
        
        /* DEFCON Scale */
        .defcon-scale { display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; margin: 20px 0; }
        .scale-item { padding: 15px; border-radius: 8px; text-align: center; transition: all 0.3s; cursor: pointer; }
        .scale-item.active { border: 3px solid white; transform: scale(1.05); }
        .scale-item:hover { transform: scale(1.05); }
        .scale-level { font-size: 2em; font-weight: bold; }
        .scale-text { font-size: 0.8em; margin-top: 5px; }
        
        /* Logout */
        .logout { text-align: center; margin-top: 30px; }
        .logout button { background: #dc2626; color: white; padding: 12px 30px; font-size: 1em; border: none; border-radius: 8px; cursor: pointer; }
        
        /* AAL Color Classes */
        .aal-1 { color: #10b981; }
        .aal-2 { color: #f59e0b; }
        .aal-3 { color: #f97316; }
        .aal-4 { color: #ef4444; }
        .aal-5 { color: #dc2626; }
    </style>
</head>
<body>
<div class="container">
    <!-- Header -->
    <div class="header">
        <h1>🛡️ Avatiah Security Index Control</h1>
        <p>Управление факторами безопасности и расчет общего индекса угрозы</p>
    </div>
    
    <!-- Mode Toggle -->
    <div class="mode-toggle">
        <form method="post" style="display:inline;">
            <button type="submit" name="toggle_mode">
                <?= $config['defcon_mode'] ? '📊 Переключить на AAL Mode' : '⚠️ Переключить на DEFCON Mode' ?>
            </button>
        </form>
    </div>
    
    <!-- DEFCON Display -->
    <div class="card">
        <div class="defcon-display">
            <div style="font-size:1.2em;font-weight:600;margin-bottom:10px;">
                <?= $config['defcon_mode'] ? 'DEFENSE READINESS CONDITION' : 'AVATIAH ALERT LEVEL' ?>
            </div>
            <div class="defcon-value" style="color:<?= $display_color ?>">
                <?= $config['defcon_mode'] ? 'DEFCON ' . $defcon : 'AAL ' . $total_aal ?>
            </div>
            <div class="defcon-text" style="color:<?= $display_color ?>">
                <?= $display_text ?>
            </div>
            <div class="defcon-subtext">
                Активных факторов: <?= count(array_filter($factors, fn($f) => $f['enabled'])) ?> из <?= count($factors) ?>
                <br>Обновлено: <?= $last_update ?>
            </div>
        </div>
        
        <!-- DEFCON Scale -->
        <div class="defcon-scale">
            <?php for ($i = 5; $i >= 1; $i--): 
                $active = ($config['defcon_mode'] && $defcon == $i) || (!$config['defcon_mode'] && round($total_aal) == (6-$i));
                $color = getDefconColor($i);
            ?>
            <div class="scale-item <?= $active ? 'active' : '' ?>" style="background:<?= $color ?>20;border:2px solid <?= $color ?>">
                <div class="scale-level" style="color:<?= $color ?>">
                    <?= $config['defcon_mode'] ? $i : (6-$i) ?>
                </div>
                <div class="scale-text"><?= getDefconText($i) ?></div>
            </div>
            <?php endfor; ?>
        </div>
    </div>
    
    <!-- Stats -->
    <div class="stats">
        <div class="stat">
            <div class="stat-value"><?= count($factors) ?></div>
            <div class="stat-label">Всего факторов</div>
        </div>
        <div class="stat">
            <div class="stat-value"><?= count(array_filter($factors, fn($f) => $f['enabled'])) ?></div>
            <div class="stat-label">Активных</div>
        </div>
        <div class="stat">
            <div class="stat-value" style="color:<?= $display_color ?>"><?= $display_value ?></div>
            <div class="stat-label">Текущий уровень</div>
        </div>
    </div>
    
    <!-- Grid -->
    <div class="grid">
        <!-- Factors -->
        <div class="card">
            <h2>⚙️ Управление факторами</h2>
            <?php if (empty($factors)): ?>
                <p style="color:#6b7280;text-align:center;padding:40px;">Нет данных в /factors</p>
            <?php else: ?>
                <?php foreach ($factors as $key => $f): 
                    $aal_class = 'aal-' . round($f['aal']);
                ?>
                <div class="factor <?= $f['enabled'] ? 'enabled' : 'disabled' ?>">
                    <div class="factor-header">
                        <div class="factor-name">
                            <a href="/factors/<?= $key ?>.php" target="_blank" style="color:inherit;text-decoration:none;" title="Открыть страницу фактора">
                                <?= htmlspecialchars($f['name']) ?> 🔗
                            </a>
                        </div>
                        <div class="factor-aal <?= $aal_class ?>"><?= $f['aal'] ?></div>
                    </div>
                    
                    <div class="factor-info">
                        <div><strong>Вес:</strong> <?= $f['weight'] ?>x</div>
                        <div><strong>Взвеш. AAL:</strong> <?= round($f['weighted_aal'], 2) ?></div>
                        <div><strong>Обновлено:</strong> <span style="color:<?= (time() - strtotime($f['last_update'])) > 86400 ? '#ef4444' : '#10b981' ?>"><?= htmlspecialchars($f['last_update']) ?></span></div>
                        <div><strong>Статус:</strong> <?= $f['enabled'] ? '✅ Активен' : '❌ Отключен' ?></div>
                    </div>
                    
                    <div class="factor-controls">
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="toggle_factor" value="<?= $key ?>">
                            <button type="submit" class="btn btn-toggle <?= $f['enabled'] ? '' : 'disabled' ?>">
                                <?= $f['enabled'] ? '✓ Включен' : '○ Отключен' ?>
                            </button>
                        </form>
                        
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="force_update" value="<?= $key ?>">
                            <button type="submit" class="btn" style="background:#8b5cf6;color:white;" title="Принудительное обновление">
                                🔄
                            </button>
                        </form>
                        
                        <form method="post" class="weight-control">
                            <input type="hidden" name="factor" value="<?= $key ?>">
                            <label>Вес:</label>
                            <input type="number" name="weight" value="<?= $f['weight'] ?>" min="0.1" max="3" step="0.1">
                            <button type="submit" name="update_weight" class="btn btn-weight">💾</button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <!-- History & Info -->
        <div>
            <!-- History -->
            <div class="card" style="margin-bottom:20px;">
                <h2>📜 История изменений</h2>
                <?php if (empty($history)): ?>
                    <p style="color:#6b7280;text-align:center;padding:20px;">Нет записей</p>
                <?php else: ?>
                    <?php foreach ($history as $h): ?>
                    <div class="history-item">
                        <div>
                            <span class="history-action <?= $h['action'] ?>">
                                <?= $h['action'] === 'enabled' ? '✅ Включен' : '❌ Отключен' ?>
                            </span>
                            <strong><?= htmlspecialchars(ucwords(str_replace(['_','-'], ' ', $h['factor']))) ?></strong>
                        </div>
                        <div class="history-time"><?= $h['time'] ?></div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <!-- Info -->
            <div class="card">
                <h2>ℹ️ Информация</h2>
                <div style="font-size:0.95em;line-height:1.8;">
                    <p><strong>DEFCON Mode:</strong> Военная система готовности (5 = мир, 1 = война)</p>
                    <p><strong>AAL Mode:</strong> Уровень угрозы Avatiah (1 = безопасно, 5 = критично)</p>
                    <p style="margin-top:15px;"><strong>Расчет индекса:</strong></p>
                    <ul style="margin-left:20px;color:#94a3b8;">
                        <li>Каждый фактор имеет AAL от 1 до 5</li>
                        <li>Можно назначить вес (0.1-3.0x)</li>
                        <li>Отключенные факторы не учитываются</li>
                        <li>Общий индекс = среднее взвешенное активных факторов</li>
                    </ul>
                    <p style="margin-top:15px;"><strong>Файлы:</strong></p>
                    <ul style="margin-left:20px;color:#94a3b8;">
                        <li><code>/factors/*.json</code> - данные факторов</li>
                        <li><code>total_index.json</code> - общий индекс</li>
                        <li><code>admin_config.json</code> - настройки</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Logout -->
    <div class="logout">
        <form method="post">
            <button type="submit" name="logout">🚪 Выйти</button>
        </form>
    </div>
</div>

<script>
// Auto-refresh every 60 seconds
setTimeout(() => location.reload(), 60000);

// Visual feedback on button clicks
document.querySelectorAll('button').forEach(btn => {
    btn.addEventListener('click', function() {
        this.style.transform = 'scale(0.95)';
        setTimeout(() => this.style.transform = '', 100);
    });
});
</script>
</body>
</html>