<?php
session_start();
$admin_password = 'avatiah2025';

if (!isset($_SESSION['admin_logged']) || $_SESSION['admin_logged'] !== true) {
    if (isset($_POST['password']) && $_POST['password'] === $admin_password) {
        $_SESSION['admin_logged'] = true;
    } else {
        echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Вход</title>
              <style>body{background:#f1f5f9;padding:2rem;font-family:Arial;}
              form{max-width:300px;margin:0 auto;background:white;padding:2rem;border-radius:12px;}
              input,button{width:100%;padding:0.75rem;margin:0.5rem 0;border-radius:6px;}
              button{background:#3b82f6;color:white;border:none;cursor:pointer;}</style></head><body>
              <form method="POST"><h2>Вход</h2><input type="password" name="password" required><button>Войти</button></form></body></html>';
        exit;
    }
}

$admin_data_file = __DIR__ . '/admin_data.json';
$factors_dir = __DIR__ . '/factors';
$config_file = __DIR__ . '/factors_config.json';

// === КОНФИГ ===
if (!file_exists($config_file)) file_put_contents($config_file, json_encode([], JSON_PRETTY_PRINT));
$config = json_decode(file_get_contents($config_file), true) ?: [];

// === ЧТЕНИЕ admin_data.json ===
$admin_data = ['aal' => 1.0, 'last_update' => '—', 'page' => '—'];
if (file_exists($admin_data_file)) {
    $json = file_get_contents($admin_data_file);
    $data = json_decode($json, true);
    if (is_array($data)) {
        $admin_data = array_merge($admin_data, $data);
    }
}

// === СПИСОК ВСЕХ СТРАНИЦ (из factors/*.php) ===
$php_files = glob("$factors_dir/*.php") ?: [];
$pages = [];

foreach ($php_files as $file) {
    $name = pathinfo($file, PATHINFO_FILENAME);
    if ($name === 'update_navy') continue;

    $enabled = $config[$name] ?? true;
    $aal = ($admin_data['page'] === $name) ? $admin_data['aal'] : 1.0;

    $pages[] = [
        'name' => $name,
        'aal' => $aal,
        'enabled' => $enabled,
        'is_current' => ($admin_data['page'] === $name)
    ];
}

usort($pages, fn($a, $b) => strcmp($a['name'], $b['name']));
?>

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Админ — Avatiah Security Index</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root { --bg: #f8fafc; --card: #ffffff; --text: #1e293b; --accent: #3b82f6; --green: #10b981; --red: #ef4444; }
        body { background:var(--bg); color:var(--text); font-family:'Inter',sans-serif; padding:1rem; }
        .container { max-width:1000px; margin:0 auto; }
        .header { background:var(--card); padding:2rem; border-radius:12px; text-align:center; box-shadow:0 4px 6px rgba(0,0,0,0.05); }
        .current-page { font-size:1.5rem; font-weight:600; color:var(--accent); margin:1rem 0; }
        .aal-value { font-size:3rem; font-weight:700; color:var(--green); }
        .pages-grid { display:grid; gap:1rem; grid-template-columns:repeat(auto-fill, minmax(280px,1fr)); margin:2rem 0; }
        .page-card { background:var(--card); padding:1.5rem; border-radius:10px; position:relative; box-shadow:0 1px 3px rgba(0,0,0,0.1); }
        .page-name { font-weight:600; color:var(--accent); }
        .page-aal { font-size:1.8rem; font-weight:700; color:var(--green); }
        .status { position:absolute; top:1rem; right:1rem; font-size:0.75rem; padding:0.2rem 0.5rem; border-radius:6px; }
        .status-on { background:#10b98120; color:#059669; }
        .status-off { background:#ef444420; color:#dc2626; }
        .toggle-btn { padding:0.4rem 0.8rem; border:none; border-radius:6px; cursor:pointer; margin-top:0.5rem; }
        .btn-on { background:var(--green); color:white; }
        .btn-off { background:var(--red); color:white; }
        .link { display:inline-block; margin-top:0.5rem; color:var(--accent); text-decoration:none; font-size:0.9rem; }
        .link:hover { text-decoration:underline; }
        .footer { text-align:center; margin-top:2rem; color:#64748b; font-size:0.8rem; }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>Админ-панель</h1>
        <div class="current-page">Текущая страница: <strong><?= ucwords(str_replace('_', ' ', $admin_data['page'])) ?></strong></div>
        <div class="aal-value"><?= number_format($admin_data['aal'], 1) ?></div>
        <p>Обновлено: <?= $admin_data['last_update'] ?></p>
    </div>

    <div class="pages-grid">
        <?php foreach ($pages as $p): ?>
            <div class="page-card <?= $p['is_current'] ? 'border-2 border-blue-500' : '' ?>">
                <div class="page-name"><?= ucwords(str_replace('_', ' ', $p['name'])) ?></div>
                <div class="page-aal"><?= number_format($p['aal'], 1) ?></div>
                <div class="status <?= $p['enabled'] ? 'status-on' : 'status-off' ?>">
                    <?= $p['enabled'] ? 'ВКЛ' : 'ВЫКЛ' ?>
                </div>
                <form method="POST" style="margin-top:0.75rem;">
                    <input type="hidden" name="factor_name" value="<?= $p['name'] ?>">
                    <button type="submit" name="toggle_factor" class="toggle-btn <?= $p['enabled'] ? 'btn-off' : 'btn-on' ?>">
                        <?= $p['enabled'] ? 'Выключить' : 'Включить' ?>
                    </button>
                </form>
                <a href="factors/<?= $p['name'] ?>.php" class="link" target="_blank">Открыть</a>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="footer">
        <p>Avatiah Security Index • Синхронизация через <code>admin_data.json</code></p>
    </div>
</div>
</body>
</html>