<?php
/**
 * Statistics API Endpoint
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../config/database.php';

try {
    $pdo = getDBConnection();
    
    // Use GROUP BY to ensure unique IDs (in case of duplicates in DB)
    $stmt = $pdo->query("
        SELECT id, value, suffix, label, icon_class, color, display_order
        FROM statistics 
        WHERE status = 'active'
        GROUP BY id
        ORDER BY display_order ASC, id ASC
    ");
    
    $statistics = [];
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $seenIds = [];
    
    foreach ($rows as $row) {
        $id = (int)$row['id'];
        // Skip duplicates (extra safety check)
        if (in_array($id, $seenIds)) {
            continue;
        }
        $seenIds[] = $id;
        
        $statistics[] = [
            'id' => $id,
            'value' => (int)$row['value'],
            'suffix' => $row['suffix'] ?: '',
            'label' => $row['label'],
            'icon_class' => $row['icon_class'],
            'color' => $row['color'] ?: '#00B4D8',
            'display_order' => (int)$row['display_order']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'statistics' => $statistics
    ]);
    
} catch (Exception $e) {
    error_log("Statistics API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'statistics' => []
    ]);
}

