<?php
// collector.php — Безопасный сборщик данных (работает в фоне)
error_reporting(E_ALL);
ini_set('display_errors', 0); // Не показываем ошибки в фоне
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/collector_errors.log');

// Создаём директорию для логов
@mkdir(__DIR__ . '/logs', 0755, true);
@mkdir(__DIR__ . '/cache', 0755, true);

$logFile = __DIR__ . '/logs/collector.log';

function logMessage($message) {
    global $logFile;
    $timestamp = date("Y-m-d H:i:s");
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

logMessage("=== Collector started ===");

try {
    require_once __DIR__ . '/lib/Logger.php';
    require_once __DIR__ . '/lib/DataSources.php';
    $config = require __DIR__ . '/config.php';

    logMessage("Config loaded successfully");

    // Подключение к БД
    $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]
    );

    logMessage("Database connected");

    // Собираем данные из всех источников
    $factors = ['pizza','oil','media','navy','vip','gov','gold','cyber','energy','social','mfa','pm','contractors','darknet','medical','satellite','evacuation','reserves'];
    $raw_values = [];
    $scores = [];
    $errors = [];

    foreach ($factors as $factor) {
        try {
            $raw = DataSources::getValue($factor, $config);
            $raw_values[$factor] = $raw ?? 0;
            $scores[$factor] = DataSources::normalize($factor, $raw_values[$factor]);
            logMessage("Factor '$factor': raw={$raw_values[$factor]}, score={$scores[$factor]}");
        } catch (Exception $e) {
            $raw_values[$factor] = 0;
            $scores[$factor] = 0;
            $errors[] = "$factor: " . $e->getMessage();
            logMessage("ERROR in factor '$factor': " . $e->getMessage());
        }
    }

    // Рассчитываем индекс
    $result = DataSources::calculateIndex($scores);
    $index = $result['index'];
    $aal = $result['aal'];
    $metrics = DataSources::calculateMetrics($index);

    logMessage("Calculated index=$index, aal=$aal");

    // Подготавливаем 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);

    logMessage("Data inserted into database successfully");

    // Сохраняем статистику ошибок
    if (!empty($errors)) {
        $errorLog = __DIR__ . '/logs/api_errors.log';
        file_put_contents($errorLog, date("Y-m-d H:i:s") . "\n" . implode("\n", $errors) . "\n\n", FILE_APPEND);
        logMessage("Errors logged: " . count($errors) . " errors");
    }

    // Очищаем старые записи (храним последние 10000)
    $pdo->exec("DELETE FROM readings WHERE id NOT IN (SELECT id FROM (SELECT id FROM readings ORDER BY timestamp DESC LIMIT 10000) AS tmp)");
    
    logMessage("=== Collector finished successfully ===");
    
    // Возвращаем успех (для синхронных вызовов)
    if (php_sapi_name() !== 'cli') {
        echo json_encode([
            'success' => true,
            'index' => $index,
            'aal' => $aal,
            'errors' => $errors
        ]);
    }

} catch (Exception $e) {
    logMessage("FATAL ERROR: " . $e->getMessage());
    logMessage("Stack trace: " . $e->getTraceAsString());
    
    if (php_sapi_name() !== 'cli') {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
}
?>