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

    $days = min(30, max(1, (int)($_GET['days'] ?? 7)));
    
    $stmt = $pdo->prepare("
        SELECT timestamp, security_index, aal_level, is_manual
        FROM readings 
        WHERE timestamp >= DATE_SUB(NOW(), INTERVAL ? DAY)
        ORDER BY timestamp ASC
    ");
    $stmt->execute([$days]);
    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'days' => $days,
        'data' => $history
    ]);

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