<?php

use MintyPHP\Service\User\UserServicesFactory;
use MintyPHP\Support\Guard;

Guard::requireLogin();
$userAccountService = (new UserServicesFactory())->createUserAccountService();

$currentUserId = (int) ($_SESSION['user']['id'] ?? 0);

$search = trim((string) ($_GET['search'] ?? ''));
$order = (string) ($_GET['order'] ?? 'id');
$dir = strtolower((string) ($_GET['dir'] ?? 'desc')) === 'asc' ? 'asc' : 'desc';
$active = $_GET['active'] ?? 'all';
$createdFrom = trim((string) ($_GET['created_from'] ?? ''));
$createdTo = trim((string) ($_GET['created_to'] ?? ''));
$tenant = trim((string) ($_GET['tenant'] ?? ''));
$roles = $_GET['roles'] ?? '';
$departments = $_GET['departments'] ?? '';

$allowedOrder = ['id', 'uuid', 'first_name', 'last_name', 'email', 'locale', 'theme', 'created', 'modified', 'active'];
if (!in_array($order, $allowedOrder, true)) {
    $order = 'id';
}

$limit = (int) ($_GET['limit'] ?? 5000);
if ($limit < 1) {
    $limit = 5000;
}
if ($limit > 5000) {
    $limit = 5000;
}

$result = $userAccountService->listPaged([
    'limit' => $limit,
    'offset' => 0,
    'search' => $search,
    'order' => $order,
    'dir' => $dir,
    'active' => $active,
    'created_from' => $createdFrom,
    'created_to' => $createdTo,
    'tenant' => $tenant,
    'roles' => $roles,
    'departments' => $departments,
    'tenantUserId' => $currentUserId,
]);

$exportRows = $result['rows'] ?? [];
$exportFilename = 'users-' . date('Ymd-His') . '.csv';
