<?php
// api/latest.php — Отдаёт последние данные для фронтенда
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

require_once __DIR__ . '/../config.php';

try {
    $config = require __DIR__ . '/../config.php';
    
    $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,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );

    // Получаем последнюю запись
    $stmt = $pdo->query("
        SELECT * 
        FROM readings 
        ORDER BY timestamp DESC 
        LIMIT 1
    ");
    
    $record = $stmt->fetch();
    
    if (!$record) {
        // Если данных нет — возвращаем заглушку
        http_response_code(503);
        echo json_encode([
            'error' => 'No data available',
            'message' => 'Collector has not run yet. Please wait for data collection.',
            'timestamp' => date('Y-m-d H:i:s')
        ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Формируем ответ в формате, ожидаемом фронтендом
    $response = [
        'success' => true,
        'timestamp' => $record['timestamp'],
        'security_index' => (float)$record['security_index'],
        'aal_level' => (int)$record['aal_level'],
        'is_manual' => (bool)$record['is_manual'],
        'manual_reason' => $record['manual_reason'] ?? null,
        
        // Метрики
        'time_to_aa3' => $record['time_to_aa3'] !== null ? (float)$record['time_to_aa3'] : null,
        'signal_detection_time' => $record['signal_detection_time'] !== null ? (float)$record['signal_detection_time'] : null,
        'detection_to_action_time' => $record['detection_to_action_time'] !== null ? (float)$record['detection_to_action_time'] : null,
        
        // Компоненты (все 18 факторов)
        'components' => [
            'pizza' => [
                'raw' => (float)$record['pizza_raw'],
                'score' => (float)$record['pizza_score']
            ],
            'oil' => [
                'raw' => (float)$record['oil_raw'],
                'score' => (float)$record['oil_score']
            ],
            'media' => [
                'raw' => (float)$record['media_raw'],
                'score' => (float)$record['media_score']
            ],
            'navy' => [
                'raw' => (float)$record['navy_raw'],
                'score' => (float)$record['navy_score']
            ],
            'vip' => [
                'raw' => (float)$record['vip_raw'],
                'score' => (float)$record['vip_score']
            ],
            'gov' => [
                'raw' => (float)$record['gov_raw'],
                'score' => (float)$record['gov_score']
            ],
            'gold' => [
                'raw' => (float)$record['gold_raw'],
                'score' => (float)$record['gold_score']
            ],
            'cyber' => [
                'raw' => (float)$record['cyber_raw'],
                'score' => (float)$record['cyber_score']
            ],
            'energy' => [
                'raw' => (float)$record['energy_raw'],
                'score' => (float)$record['energy_score']
            ],
            'social' => [
                'raw' => (float)$record['social_raw'],
                'score' => (float)$record['social_score']
            ],
            'mfa' => [
                'raw' => (float)$record['mfa_raw'],
                'score' => (float)$record['mfa_score']
            ],
            'pm' => [
                'raw' => (float)$record['pm_raw'],
                'score' => (float)$record['pm_score']
            ],
            'contractors' => [
                'raw' => (float)$record['contractors_raw'],
                'score' => (float)$record['contractors_score']
            ],
            'darknet' => [
                'raw' => (float)$record['darknet_raw'],
                'score' => (float)$record['darknet_score']
            ],
            'medical' => [
                'raw' => (float)$record['medical_raw'],
                'score' => (float)$record['medical_score']
            ],
            'satellite' => [
                'raw' => (float)$record['satellite_raw'],
                'score' => (float)$record['satellite_score']
            ],
            'evacuation' => [
                'raw' => (float)$record['evacuation_raw'],
                'score' => (float)$record['evacuation_score']
            ],
            'reserves' => [
                'raw' => (float)$record['reserves_raw'],
                'score' => (float)$record['reserves_score']
            ]
        ],
        
        // Дополнительная информация
        'data_age_minutes' => round((time() - strtotime($record['timestamp'])) / 60, 1),
        'next_update' => date('Y-m-d H:i:s', strtotime($record['timestamp']) + 900) // +15 минут
    ];

    // Проверка свежести данных
    $data_age_seconds = time() - strtotime($record['timestamp']);
    if ($data_age_seconds > 1800) { // Старше 30 минут
        $response['warning'] = 'Data is outdated. Collector may not be running properly.';
        $response['data_age_minutes'] = round($data_age_seconds / 60, 1);
    }

    echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Database error',
        'message' => 'Could not connect to database',
        'details' => $e->getMessage()
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Server error',
        'message' => $e->getMessage()
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
?>