<?php
// collector.php — АВТОМАТИЧЕСКИ ОБНОВЛЯЕТСЯ КАЖДЫЕ 15 МИНУТ
require_once __DIR__ . '/lib/Logger.php';
require_once __DIR__ . '/lib/DataSources.php';

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

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]
    );

    // Все 18 факторов
    $factors = ['pizza','oil','media','navy','vip','gov','gold','cyber','energy','social','mfa','pm','contractors','darknet','medical','satellite','evacuation','reserves'];
    $raw_values = [];
    $scores = [];
    foreach ($factors as $factor) {
        $raw = DataSources::getValue($factor, $config);
        $raw_values[$factor] = $raw ?? 0;
        $scores[$factor] = DataSources::normalize($factor, $raw_values[$factor]);
    }

    $result = DataSources::calculateIndex($scores);
    $index = $result['index'];
    $aal = $result['aal'];
    $metrics = DataSources::calculateMetrics($index);

    // Подготавливаем поля для SQL
    $columns = [];
    $placeholders = [];
    $values = [];

    foreach ($factors as $f) {
        $columns[] = "{$f}_raw";
        $columns[] = "{$f}_score";
        $placeholders[] = ":{$f}_raw";
        $placeholders[] = ":{$f}_score";
        $values[":{$f}_raw"] = $raw_values[$f];
        $values[":{$f}_score"] = $scores[$f];
    }

    $columns = array_merge($columns, [
        'security_index', 'aal_level', 'is_manual',
        'time_to_aa3', 'signal_detection_time', 'detection_to_action_time'
    ]);
    $placeholders = array_merge($placeholders, [
        ':security_index', ':aal_level', '0',
        ':time_to_aa3', ':signal_detection_time', ':detection_to_action_time'
    ]);
    $values[':security_index'] = $index;
    $values[':aal_level'] = $aal;
    $values[':time_to_aa3'] = $metrics['time_to_aa3'];
    $values[':signal_detection_time'] = $metrics['signal_detection_time'];
    $values[':detection_to_action_time'] = $metrics['detection_to_action_time'];

    $sql = "INSERT INTO readings (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($values);

    echo "✅ SUCCESS: Index={$index}, AAL={$aal}\n";

} catch (Exception $e) {
    echo "❌ ERROR: " . $e->getMessage() . "\n";
}
?>