<?php
require "../config/database.php";
require "../includes/auth.php";
require "../includes/rbac.php";

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

if (!hasPermission("view_admin")) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "forbidden"]);
    exit;
}

$workersByStatus = $pdo->query("
    SELECT status, COUNT(*) total
    FROM workers
    GROUP BY status
")->fetchAll(PDO::FETCH_ASSOC);

$messagesPerDay = $pdo->query("
    SELECT DATE(created_at) day, COUNT(*) total
    FROM messages
    GROUP BY DATE(created_at)
    ORDER BY day ASC
    LIMIT 14
")->fetchAll(PDO::FETCH_ASSOC);

$newUsersPerMonth = $pdo->query("
    SELECT DATE_FORMAT(created_at,'%Y-%m') month, COUNT(*) total
    FROM users
    GROUP BY DATE_FORMAT(created_at,'%Y-%m')
    ORDER BY month ASC
    LIMIT 12
")->fetchAll(PDO::FETCH_ASSOC);

$totalUsers = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalWorkers = (int)$pdo->query("SELECT COUNT(*) FROM workers")->fetchColumn();
$totalMessages = (int)$pdo->query("SELECT COUNT(*) FROM messages")->fetchColumn();
$totalRequests = (int)$pdo->query("SELECT COUNT(*) FROM requests")->fetchColumn();
$totalMatches = (int)$pdo->query("SELECT COUNT(*) FROM matches")->fetchColumn();

echo json_encode([
    "success" => true,
    "data" => [
        "totals" => [
            "users" => $totalUsers,
            "workers" => $totalWorkers,
            "messages" => $totalMessages,
            "requests" => $totalRequests,
            "matches" => $totalMatches
        ],
        "workersByStatus" => $workersByStatus,
        "messagesPerDay" => $messagesPerDay,
        "newUsersPerMonth" => $newUsersPerMonth
    ]
]);
