<?php

use MintyPHP\Router;
use MintyPHP\Service\User\UserServicesFactory;
$userServicesFactory = new UserServicesFactory();
$userAccountService = $userServicesFactory->createUserAccountService();
$userAvatarService = $userServicesFactory->createUserAvatarService();

if (!isset($_SESSION['user'])) {
    http_response_code(401);
    Router::json(['data' => [], 'total' => 0]);
}

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

$limit = (int) ($_GET['limit'] ?? 10);
$offset = (int) ($_GET['offset'] ?? 0);
$search = trim((string) ($_GET['search'] ?? ''));
$order = (string) ($_GET['order'] ?? 'last_name');
$dir = (string) ($_GET['dir'] ?? 'asc');
$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'] ?? '';
$emailVerified = $_GET['email_verified'] ?? 'all';
$loginStatus = $_GET['login_status'] ?? 'all';

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

$rows = [];
foreach ($result['rows'] as $row) {
    $tenantLabels = $row['tenant_labels'] ?? [];
    if (is_string($tenantLabels)) {
        $tenantList = $tenantLabels !== ''
            ? array_values(array_filter(array_map('trim', explode('||', $tenantLabels))))
            : [];
    } elseif (is_array($tenantLabels)) {
        $tenantList = array_values(array_filter(array_map('trim', $tenantLabels)));
    } else {
        $tenantList = [];
    }
    $roleLabels = $row['role_labels'] ?? [];
    if (is_string($roleLabels)) {
        $roleList = $roleLabels !== ''
            ? array_values(array_filter(array_map('trim', explode('||', $roleLabels))))
            : [];
    } elseif (is_array($roleLabels)) {
        $roleList = array_values(array_filter(array_map('trim', $roleLabels)));
    } else {
        $roleList = [];
    }
    $departmentLabels = $row['department_labels'] ?? [];
    if (is_string($departmentLabels)) {
        $departmentList = $departmentLabels !== ''
            ? array_values(array_filter(array_map('trim', explode('||', $departmentLabels))))
            : [];
    } elseif (is_array($departmentLabels)) {
        $departmentList = array_values(array_filter(array_map('trim', $departmentLabels)));
    } else {
        $departmentList = [];
    }
    $primaryTenantLabel = (string) ($row['primary_tenant_label'] ?? '');
    if ($primaryTenantLabel === '' && count($tenantList) === 1) {
        $primaryTenantLabel = (string) $tenantList[0];
    }
    $uuid = (string) ($row['uuid'] ?? '');
    $rows[] = [
        'id' => $row['id'] ?? null,
        'uuid' => $uuid,
        'first_name' => $row['first_name'] ?? '',
        'last_name' => $row['last_name'] ?? '',
        'email' => $row['email'] ?? '',
        'phone' => $row['phone'] ?? '',
        'mobile' => $row['mobile'] ?? '',
        'short_dial' => $row['short_dial'] ?? '',
        'tenants' => [
            'items' => $tenantList,
            'primary' => $primaryTenantLabel,
        ],
        'departments' => $departmentList,
        'roles' => $roleList,
        'created' => dt($row['created'] ?? ''),
        'modified' => dt($row['modified'] ?? ''),
        'last_login' => dt($row['last_login_at'] ?? ''),
        'active' => (int) ($row['active'] ?? 0),
        'has_avatar' => $uuid !== '' && $userAvatarService->hasAvatar($uuid),
    ];
}

Router::json([
    'data' => $rows,
    'total' => $result['total'] ?? 0,
]);
