<?php
// /api/latest.php - ОБНОВЛЁННАЯ ВЕРСИЯ С ДОПОЛНИТЕЛЬНЫМИ МЕТРИКАМИ
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

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

    $stmt = $pdo->query("
        SELECT 
            security_index, aal_level, timestamp, is_manual, manual_reason,
            pizza_raw, oil_raw, media_raw, navy_raw, vip_raw, gov_raw, 
            gold_raw, cyber_raw, energy_raw, social_raw,
            pizza_score, oil_score, media_score, navy_score, vip_score, 
            gov_score, gold_score, cyber_score, energy_score, social_score,
            time_to_aa3, signal_detection_time, detection_to_action_time
        FROM readings 
        ORDER BY timestamp DESC 
        LIMIT 1
    ");
    $record = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$record) {
        http_response_code(404);
        echo json_encode(['error' => 'No data available']);
        exit;
    }

    // Форматируем компоненты
    $components = [];
    $factors = ['pizza', 'oil', 'media', 'navy', 'vip', 'gov', 'gold', 'cyber', 'energy', 'social'];
    foreach ($factors as $factor) {
        $components[$factor] = [
            'raw' => (float)$record["{$factor}_raw"],
            'score' => (float)$record["{$factor}_score"]
        ];
    }

    echo json_encode([
        'security_index' => (float)$record['security_index'],
        'aal_level' => (int)$record['aal_level'],
        'timestamp' => $record['timestamp'],
        'is_manual' => (bool)$record['is_manual'],
        'manual_reason' => $record['manual_reason'],
        'components' => $components,
        // ДОПОЛНИТЕЛЬНЫЕ МЕТРИКИ:
        'time_to_aa3' => $record['time_to_aa3'] !== null ? (float)$record['time_to_aa3'] : null,
        'signal_detection_time' => $record['signal_detection_time'] !== null ? (int)$record['signal_detection_time'] : null,
        'detection_to_action_time' => $record['detection_to_action_time'] !== null ? (int)$record['detection_to_action_time'] : null
    ]);

} catch (Exception $e) {
    http_response_code(500);
    error_log("API latest error: " . $e->getMessage());
    echo json_encode(['error' => 'Service unavailable']);
}
?>