<?php
// /api/latest.php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../config.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]
    );

    $stmt = $pdo->query("SELECT * FROM readings ORDER BY timestamp DESC LIMIT 1");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

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

    echo json_encode([
        'security_index' => round($row['security_index'], 1),
        'aal_level' => (int)$row['aal_level'],
        'timestamp' => $row['timestamp'],
        'is_manual' => (bool)$row['is_manual'],
        'components' => [
            'pizza'  => ['raw' => $row['pizza_raw'],  'score' => $row['pizza_score']],
            'oil'    => ['raw' => $row['oil_raw'],    'score' => $row['oil_score']],
            'media'  => ['raw' => $row['media_raw'],  'score' => $row['media_score']],
            'navy'   => ['raw' => $row['navy_raw'],   'score' => $row['navy_score']],
            'vip'    => ['raw' => $row['vip_raw'],    'score' => $row['vip_score']],
            'gov'    => ['raw' => $row['gov_raw'],    'score' => $row['gov_score']],
            'gold'   => ['raw' => $row['gold_raw'],   'score' => $row['gold_score']],
            'cyber'  => ['raw' => $row['cyber_raw'],  'score' => $row['cyber_score']],
            'energy' => ['raw' => $row['energy_raw'], 'score' => $row['energy_score']],
            'social' => ['raw' => $row['social_raw'], 'score' => $row['social_score']],
        ]
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'DB error']);
}
