<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Template\TemplateVariables;

use isys_application;
use isys_auth;
use isys_auth_cmdb_objects;

class UserTemplate
{
    private ?array $data = null;

    public function __construct(private string $userId)
    {
    }

    public function getData(): ?array
    {
        return $this->data;
    }

    private function resolveUserData(): array
    {
        if (!$this->data) {
            if (!isys_auth_cmdb_objects::instance()->is_allowed_to(isys_auth::VIEW, "OBJ_ID/{$this->userId}")){
                return [];
            }

            $db = isys_application::instance()->container->get('database');
            $dao = \isys_component_dao_user::instance($db);
            $this->data = $dao->get_user($this->userId)->get_row();
        }
        return $this->data;
    }

    public function __get(string $name)
    {
        $this->resolveUserData();
        return $this->data[$name] ?? $this->data['isys_cats_person_list__' . $name] ?? null;
    }

    public function __isset(string $name): bool
    {
        $this->resolveUserData();
        return isset($this->data[$name]) || isset($this->data['isys_cats_person_list__' . $name]);
    }
}
