<?php
// /api/status.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]
    );

    // Статистика данных
    $stats = $pdo->query("
        SELECT 
            COUNT(*) as total_records,
            MAX(timestamp) as last_update,
            AVG(security_index) as avg_index,
            SUM(is_manual) as manual_adjustments
        FROM readings
    ")->fetch();

    // Последние 6 записей для тренда
    $trend = $pdo->query("
        SELECT security_index, timestamp 
        FROM readings 
        ORDER BY timestamp DESC 
        LIMIT 6
    ")->fetchAll();

    $trend_values = array_column($trend, 'security_index');
    $current = $trend_values[0] ?? 0;
    $previous = $trend_values[1] ?? $current;
    $trend_direction = $current > $previous ? 'up' : ($current < $previous ? 'down' : 'stable');

    echo json_encode([
        'success' => true,
        'system_status' => 'operational',
        'data_stats' => [
            'total_records' => (int)$stats['total_records'],
            'last_update' => $stats['last_update'],
            'average_index' => round($stats['avg_index'], 2),
            'manual_adjustments' => (int)$stats['manual_adjustments']
        ],
        'trend' => $trend_direction,
        'update_frequency' => 'hourly'
    ]);

} catch (Exception $e) {
    http_response_code(500);
    error_log("API status error: " . $e->getMessage());
    echo json_encode(['error' => 'Status check failed']);
}
?>