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

$server_id = $_GET['server_id'] ?? 0;
if (!$server_id) {
    echo json_encode(['success' => false, 'error' => 'Server ID required']);
    exit;
}

$user_id = $_SESSION['user_id'];

// Check if user is member of the server
$stmt = db()->prepare("SELECT 1 FROM server_members WHERE server_id = ? AND user_id = ?");
$stmt->execute([$server_id, $user_id]);
if (!$stmt->fetch()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

try {
    // Total members
    $stmt = db()->prepare("SELECT COUNT(*) as count FROM server_members WHERE server_id = ?");
    $stmt->execute([$server_id]);
    $total_members = $stmt->fetch()['count'];

    // Total messages in all channels of this server
    $stmt = db()->prepare("
        SELECT COUNT(*) as count 
        FROM messages m 
        JOIN channels c ON m.channel_id = c.id 
        WHERE c.server_id = ?
    ");
    $stmt->execute([$server_id]);
    $total_messages = $stmt->fetch()['count'];

    // Messages per day (last 7 days)
    $stmt = db()->prepare("
        SELECT DATE(m.created_at) as date, COUNT(*) as count 
        FROM messages m 
        JOIN channels c ON m.channel_id = c.id 
        WHERE c.server_id = ? AND m.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
        GROUP BY DATE(m.created_at)
        ORDER BY date ASC
    ");
    $stmt->execute([$server_id]);
    $history = $stmt->fetchAll();

    // Top active users
    $stmt = db()->prepare("
        SELECT u.display_name as username, u.username as login_name, COUNT(*) as message_count
        FROM messages m
        JOIN channels c ON m.channel_id = c.id
        JOIN users u ON m.user_id = u.id
        WHERE c.server_id = ?
        GROUP BY m.user_id
        ORDER BY message_count DESC
        LIMIT 5
    ");
    $stmt->execute([$server_id]);
    $top_users = $stmt->fetchAll();

    echo json_encode([
        'success' => true,
        'stats' => [
            'total_members' => $total_members,
            'total_messages' => $total_messages,
            'history' => $history,
            'top_users' => $top_users
        ]
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
