<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php';
require_once '../../services/analytics/DashboardUserAccessAdminService.php';

require_login();
require_permission('admin.users.edit');

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$pdo = db();

header('Content-Type: application/json; charset=utf-8');
if ($id <= 0) {
    http_response_code(422);
    echo json_encode(array('success' => false, 'message' => 'ID de usuario inválido.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$stmt = $pdo->prepare("SELECT email, name, role, status, module_permissions FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
    http_response_code(404);
    echo json_encode(array('success' => false, 'message' => 'Usuario no encontrado.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$dashboardAccess = new DashboardUserAccessAdminService($pdo);
$user['dashboard_access'] = $dashboardAccess->getAccessMatrix($id, $user['role']);
$user['success'] = true;
echo json_encode($user, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
