<?php
session_start();
include('../includes/config.php');

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

$chart = isset($_GET['chart']) ? $_GET['chart'] : '';
$response = array('success' => false);

if ($chart == 'role_distribution') {
    // Get activities by admin role
    $sql = "SELECT admin_role, COUNT(*) as count 
            FROM admin_activities 
            GROUP BY admin_role 
            ORDER BY count DESC";
    $result = mysqli_query($conn, $sql);
    
    $labels = array();
    $series = array();
    
    while ($row = mysqli_fetch_assoc($result)) {
        $labels[] = ucfirst(str_replace('_', ' ', $row['admin_role']));
        $series[] = intval($row['count']);
    }
    
    $response = array(
        'success' => true,
        'labels' => $labels,
        'series' => $series
    );
    
} elseif ($chart == 'module_distribution') {
    // Get activities by module (top 10)
    $sql = "SELECT COALESCE(module, 'Other') as module, COUNT(*) as count 
            FROM admin_activities 
            GROUP BY module 
            ORDER BY count DESC 
            LIMIT 10";
    $result = mysqli_query($conn, $sql);
    
    $labels = array();
    $series = array();
    
    while ($row = mysqli_fetch_assoc($result)) {
        $labels[] = $row['module'];
        $series[] = intval($row['count']);
    }
    
    $response = array(
        'success' => true,
        'labels' => $labels,
        'series' => $series
    );
    
} elseif ($chart == 'hourly_activity') {
    // Get activities by hour for last 24 hours
    $labels = array();
    $data = array();
    
    for ($i = 23; $i >= 0; $i--) {
        $hour_start = date('Y-m-d H:00:00', strtotime("-$i hours"));
        $hour_end = date('Y-m-d H:59:59', strtotime("-$i hours"));
        
        $sql = "SELECT COUNT(*) as count 
                FROM admin_activities 
                WHERE created_at BETWEEN '$hour_start' AND '$hour_end'";
        $result = mysqli_query($conn, $sql);
        $row = mysqli_fetch_assoc($result);
        
        $labels[] = date('H:00', strtotime($hour_start));
        $data[] = intval($row['count']);
    }
    
    $response = array(
        'success' => true,
        'labels' => $labels,
        'data' => $data
    );
}

echo json_encode($response);
?>