<?php
// /admin/index.php — ИСПРАВЛЕННАЯ ВЕРСИЯ
session_start();
if (!($_SESSION['admin_logged_in'] ?? false)) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../lib/DataSources.php';
require_once __DIR__ . '/../lib/Logger.php';

$config = require __DIR__ . '/../config.php';

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

try {
    $pdo = new PDO(
        "mysql:host={$config['db_host']};dbname={$config['db_name']};charset=utf8mb4",
        $config['db_user'],
        $config['db_pass'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // Обработка сохранения
    if ($_POST['action'] ?? '' === 'update') {
        if ($_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')) {
            die('Ошибка безопасности CSRF');
        }
        
        $id = (int)$_POST['id'];
        $raw = [
            'pizza' => (float)$_POST['pizza_raw'],
            'oil' => (float)$_POST['oil_raw'],
            'media' => (float)$_POST['media_raw'],
            'navy' => (float)$_POST['navy_raw'],
            'vip' => (float)$_POST['vip_raw'],
            'gov' => (float)$_POST['gov_raw'],
            'gold' => (float)$_POST['gold_raw'],
            'cyber' => (float)$_POST['cyber_raw'],
            'energy' => (float)$_POST['energy_raw'],
            'social' => (float)$_POST['social_raw'],
            'mfa' => (float)$_POST['mfa_raw'],
            'pm' => (float)$_POST['pm_raw'],
            'contractors' => (float)$_POST['contractors_raw'],
            'darknet' => (float)$_POST['darknet_raw'],
            'medical' => (float)$_POST['medical_raw'],
            'satellite' => (float)$_POST['satellite_raw'],
            'evacuation' => (float)$_POST['evacuation_raw'],
            'reserves' => (float)$_POST['reserves_raw'],
        ];

        $scores = [];
        foreach ($raw as $factor => $value) {
            $scores[$factor] = DataSources::normalize($factor, $value);
        }
        $result = DataSources::calculateIndex($scores);
        $index = $result['index'];
        $aal = $result['aal'];
        $metrics = DataSources::calculateMetrics($index);

        // Подготавливаем данные для UPDATE
        $updateFields = [];
        $params = [];
        foreach ($raw as $f => $v) {
            $updateFields[] = "{$f}_raw = ?";
            $updateFields[] = "{$f}_score = ?";
            $params[] = $v;
            $params[] = $scores[$f];
        }
        $updateFields[] = "security_index = ?";
        $updateFields[] = "aal_level = ?";
        $updateFields[] = "is_manual = 1";
        $updateFields[] = "manual_reason = ?";
        $updateFields[] = "updated_at = NOW()";
        $updateFields[] = "time_to_aa3 = ?";
        $updateFields[] = "signal_detection_time = ?";
        $updateFields[] = "detection_to_action_time = ?";
        
        $params[] = $index;
        $params[] = $aal;
        $params[] = $_POST['manual_reason'] ?? '';
        $params[] = $metrics['time_to_aa3'];
        $params[] = $metrics['signal_detection_time'];
        $params[] = $metrics['detection_to_action_time'];
        $params[] = $id;

        $sql = "UPDATE readings SET " . implode(', ', $updateFields) . " WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        header('Location: index.php?saved=1');
        exit;
    }

    // Получаем последнюю запись
    $record = $pdo->query("SELECT * FROM readings ORDER BY timestamp DESC LIMIT 1")->fetch();

    // Если записей нет — создаём тестовую
    if (!$record) {
        // Вставляем тестовые данные
        $test_data = [
            'pizza_raw' => 2.5, 'oil_raw' => 75.5, 'media_raw' => 1200, 'navy_raw' => 3, 'vip_raw' => 8, 'gov_raw' => 2,
            'gold_raw' => 45.5, 'cyber_raw' => 2, 'energy_raw' => 60.0, 'social_raw' => 2.5,
            'mfa_raw' => 2, 'pm_raw' => 3, 'contractors_raw' => 1, 'darknet_raw' => 2, 'medical_raw' => 1, 
            'satellite_raw' => 2, 'evacuation_raw' => 1, 'reserves_raw' => 1,
            'pizza_score' => 5.2, 'oil_score' => 4.1, 'media_score' => 6.8, 'navy_score' => 5.0, 'vip_score' => 2.0,
            'gov_score' => 8.9, 'gold_score' => 3.3, 'cyber_score' => 2.2, 'energy_score' => 4.4, 'social_score' => 3.1,
            'mfa_score' => 2.0, 'pm_score' => 4.0, 'contractors_score' => 1.0, 'darknet_score' => 2.0, 'medical_score' => 1.0,
            'satellite_score' => 2.0, 'evacuation_score' => 1.0, 'reserves_score' => 1.0,
            'security_index' => 4.7, 'aal_level' => 3
        ];

        $columns = implode(', ', array_keys($test_data));
        $placeholders = ':' . implode(', :', array_keys($test_data));
        $sql = "INSERT INTO readings ($columns) VALUES ($placeholders)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($test_data);
        
        $record = $pdo->query("SELECT * FROM readings ORDER BY timestamp DESC LIMIT 1")->fetch();
    }

} catch (Exception $e) {
    die("Ошибка базы данных: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Админка — Avatiah Security Index</title>
    <meta charset="utf-8">
    <style>
        body { font-family: sans-serif; padding: 20px; background: #f9f9f9; }
        .form-group { margin: 15px 0; }
        label { display: inline-block; width: 320px; font-weight: bold; }
        input { padding: 8px; width: 120px; border: 1px solid #ddd; border-radius: 4px; }
        button { padding: 12px 24px; background: #e74c3c; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; }
        button:hover { background: #c0392b; }
        .info { background: #fff; padding: 20px; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .current-index { background: #e8f4fd; padding: 15px; border-radius: 8px; margin: 15px 0; }
        .current-index-value { font-size: 24px; font-weight: bold; color: #2980b9; }
    </style>
</head>
<body>
    <h1>🛠️ Административная панель</h1>

    <?php if (isset($_GET['saved'])): ?>
        <div class="info success">✅ Данные успешно обновлены!</div>
    <?php endif; ?>

    <div class="info">
        <strong>Последняя запись:</strong> <?= htmlspecialchars($record['timestamp']) ?>
        <?php if ($record['is_manual']): ?>
            <span style="color:#e74c3c;">(ручная корректировка)</span>
        <?php endif; ?>
    </div>

    <?php
    $current_scores = [];
    $factors = ['pizza','oil','media','navy','vip','gov','gold','cyber','energy','social','mfa','pm','contractors','darknet','medical','satellite','evacuation','reserves'];
    foreach ($factors as $f) {
        $current_scores[$f] = DataSources::normalize($f, $record["{$f}_raw"]);
    }
    $current_result = DataSources::calculateIndex($current_scores);
    ?>
    <div class="current-index">
        <strong>Текущий Security Index:</strong> 
        <span class="current-index-value"><?= $current_result['index'] ?> / 10</span> 
        (AAL-<?= $current_result['aal'] ?>)
    </div>

    <form method="POST">
        <input type="hidden" name="action" value="update">
        <input type="hidden" name="id" value="<?= $record['id'] ?>">
        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

        <?php
        $fields = [
            'pizza_raw' => '🍕 Индекс ночной активности (1-5.2)',
            'oil_raw' => '🛢️ Волатильность нефти (%/день)',
            'media_raw' => '📰 Медиа-упоминания/час',
            'navy_raw' => '🚢 Военное присутствие США (уровень 1-5)',
            'vip_raw' => '✈️ Дипломатические рейсы/неделю',
            'gov_raw' => '🏛️ Активность правительства США',
            'gold_raw' => '💎 Волатильность золота (%/день)',
            'cyber_raw' => '🔒 Киберугрозы (уровень 1-5)',
            'energy_raw' => '⚡ Угрозы энергосистеме Израиля (уровень 1-5)',
            'social_raw' => '📱 Соцсети лидеров (уровень 1-5)',
            'mfa_raw' => '🌍 Активность МИД Израиля (уровень 1-5)',
            'pm_raw' => '👨‍💼 Заявления премьер-министра (уровень 1-5)',
            'contractors_raw' => '🏭 Активность военных подрядчиков (уровень 1-5)',
            'darknet_raw' => '🌐 Даркнет активность (уровень 1-5)',
            'medical_raw' => '🏥 Военные медзапасы (уровень 1-5)',
            'satellite_raw' => '🛰️ Спутниковая активность (уровень 1-5)',
            'evacuation_raw' => '🚁 Эвакуация дипломатов (уровень 1-5)',
            'reserves_raw' => '👥 Мобилизация резервистов (уровень 1-5)',
        ];
        foreach ($fields as $key => $label): 
            $factor = str_replace('_raw', '', $key);
            $score_key = "{$factor}_score";
        ?>
            <div class="form-group">
                <label><?= $label ?>:</label>
                <input type="number" step="0.1" name="<?= $key ?>" value="<?= htmlspecialchars($record[$key]) ?>" required>
                <span style="margin-left: 10px; color: #3498db;">Score: <?= htmlspecialchars(number_format($record[$score_key], 1)) ?></span>
            </div>
        <?php endforeach; ?>

        <div class="form-group">
            <label>📝 Причина ручной правки:</label>
            <input type="text" name="manual_reason" value="<?= htmlspecialchars($record['manual_reason'] ?? '') ?>" style="width:400px;" placeholder="Объясните причину корректировки">
        </div>

        <button type="submit">💾 Сохранить изменения</button>
        <a href="../" style="margin-left:20px; color: #3498db;">← Вернуться на сайт</a>
    </form>
</body>
</html>