<?php
require_once '../../config.php';
require_once '../../functions.php';

header('Content-Type: application/json');

check_admin_auth();

$filter = $_GET['filter'] ?? 'week'; // today, week, custom
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$whereClause = "WHERE 1=1";
$params = [];

// Date Filtering Logic
if ($filter === 'today') {
    $whereClause .= " AND DATE(sl.created_at) = CURDATE()";
} elseif ($filter === 'week') {
    $whereClause .= " AND YEARWEEK(sl.created_at, 1) = YEARWEEK(CURDATE(), 1)";
} elseif ($filter === 'custom' && $start_date && $end_date) {
    $whereClause .= " AND DATE(sl.created_at) BETWEEN ? AND ?";
    $params[] = $start_date;
    $params[] = $end_date;
} else {
    // Default to last 30 days if no valid filter
    // actually default to week as per above, but valid fallback is good
}

try {
    // Top 10 Users by SMS Count
    $sql = "
        SELECT 
            u.username as label, 
            COUNT(sl.id) as value
        FROM sms_logs sl
        JOIN users u ON sl.user_id = u.id
        $whereClause
        GROUP BY u.username
        ORDER BY value DESC
        LIMIT 10
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Add Colors (Simple Palette)
    $colors = ['#6c5ffc', '#05c3fb', '#09ad95', '#1170e4', '#f82649', '#ecb403', '#17a2b8', '#ff7e5f', '#7158e2', '#3ae374'];

    $formattedData = [];
    foreach ($data as $index => $row) {
        $row['color'] = $colors[$index % count($colors)];
        $formattedData[] = $row;
    }

    // NVD3 expects specific structure for Discrete Bar
    $response = [
        [
            'key' => "SMS Traffic",
            'values' => $formattedData
        ]
    ];

    echo json_encode($response);

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