<?php
header('Content-Type: application/json');
require_once 'config.php';

// Get current user to restrict access
$user = getCurrentUser();

try {
    $db = getDB();

    // Get current statistics
    $currentStats = $db->query('
        SELECT 
            COUNT(*) as total,
            AVG(skr) as avg_score
        FROM household_scores
    ')->fetch(PDO::FETCH_ASSOC);

    // Generate realistic placeholder trend data (last 12 months declining trend)
    // This simulates poverty reduction over time
    $months = [];
    $scores = [];
    $householdCounts = [];
    
    for ($i = 11; $i >= 0; $i--) {
        $date = new DateTime("-$i months");
        $months[] = $date->format('M Y');
        
        // Simulate declining poverty trend (improvement over time)
        $baseScore = 7.8;
        $trend = ($i / 12) * 0.3; // 0-30% improvement
        $score = $baseScore * (0.8 + $trend) + (rand(-5, 5) / 100);
        $scores[] = round(max(5.0, min(9.0, $score)), 2);
        $householdCounts[] = rand(450, 550);
    }

    $response = [
        'success' => true,
        'trend' => [
            'months' => $months,
            'scores' => $scores,
            'household_counts' => $householdCounts,
            'current_avg' => round($currentStats['avg_score'] ?? 0, 2),
            'current_total' => $currentStats['total'] ?? 0,
            'note' => 'Trend data is simulated based on current poverty scores'
        ]
    ];

    http_response_code(200);
    die(json_encode($response));

} catch (PDOException $e) {
    http_response_code(500);
    die(json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]));
} catch (Exception $e) {
    http_response_code(400);
    die(json_encode([
        'success' => false,
        'error' => 'Error: ' . $e->getMessage()
    ]));
}
?>

