<?php

include("GnutecaWebServices.class.php");

class gnuteca3WebServicesProfile
{
    private $webService;
    private $busPerson;
    private $MIOLO;

    public function __construct()
    {
        $this->webService = new GWebServices();
        $this->MIOLO = MIOLO::getInstance();
        $this->busPerson = $this->MIOLO->getBusiness('gnuteca3', 'BusPerson');
    }

    /**
     * WebService que lista os dados do usuário
     * @param int $clientId
     * @param string $clientPassword
     * @param int $personId
     * @return bool|string
     */
    public function getProfile($clientId, $clientPassword, $personId)
    {
        $retorno = new stdClass();

        // Define acesso ao método e define a classe do Webservice
        $this->webService->__setClient($clientId, $clientPassword);
        $this->webService->setClassName(get_class($this));

        // Verifica se usuário possui acesso ao WebService.
        if (!$this->webService->__checkMethod("getProfile", false)) 
        {
            $retorno->message = $this->webService->__getErrorStr();
            return json_encode($retorno);
        }

        $this->busPerson->personIdS = $personId;
        $profile = $this->busPerson->searchPerson(TRUE);
        !empty($profile) && $profile = $profile[0];

        $profile = [
            "Nome" => $profile->personName,
            "Endereço e Número" => $profile->location . ', ' . $profile->number ?? '-',
            "Complemento" => $profile->complement ?? '-',
            "Cidade" => $profile->name ?? '-',
            "CEP" => $profile->zipCode ?? '-',
            "E-mail" => $profile->email ?? '-',
            "Telefone" => $profile->phones ?? '-',
        ];

        // Obtém a imagem do usuário
        $busFile = $this->MIOLO->getBusiness("gnuteca3", "BusFile");
        $busFile->folder = 'person';
        $busFile->fileName = "$personId.";
        $image = $busFile->searchFile(true)[0];
        $imageName = $image->basename ?? 'default.png';

        $retorno->profile = $profile;
        $retorno->profileLabel = LABEL_PERSON_DATA;
        $retorno->profilePicture = $this->MIOLO->getAbsoluteURL(null) . "miolo25/html/file.php?folder=person&file=$imageName";
        $retorno->politics = $this->listPolicy($personId);
        
        return json_encode($retorno);
    }

    /**
     * Webservice que lista as políticas da unidade
     * @param int $clientId
     * @param string $clientPassword
     * @param int $personId
     * @param int $libraryUnitId
     * @return bool|string
     */
    private function listPolicy($personId)
    {
        $busOperationLoan = $this->MIOLO->getBusiness('gnuteca3', 'BusOperationLoan');
        $busLibraryUnit = $this->MIOLO->getBusiness('gnuteca3', 'BusLibraryUnit');

        $libraries = $busLibraryUnit->listLibraryUnitForSearch(true);
        $libraryUnitPrivilegeGroups = array();

        // Lógica pega do método getPolicy da classe FrmMyInformation
        if ($libraries) {
            foreach ($libraries as $library) 
            {
                if (isset($library[3])) 
                {
                    $libraryUnitPrivilegeGroups[$library[3]][] = $library;
                }
            }
        }

        if(!empty($libraryUnitPrivilegeGroups)) 
        {
            foreach($libraryUnitPrivilegeGroups as $privilegeGroup) 
            {
                $libraryUnits = array();
                $libraryUnitId = null;

                foreach ( $privilegeGroup as $units )
                {
                    if ( $this->busPerson->checkAccessLibraryUnit($personId, $units[0]) )
                    {
                        $libraryUnits[] = $units[1];

                        if ( !$libraryUnitId )
                        {
                            $libraryUnitId = $units[0];
                        }
                    }
                }
            }
        }

        $busOperationLoan->setLibraryUnit($libraryUnitId);
        $busOperationLoan->setPerson($personId);
        
        $person = $busOperationLoan->getPerson();
        $politicas = $person->policy;
        
        foreach ($politicas as $politica) 
        {
            $policy[] = [
                "materialGender" => $politica->materialGenderDescription,
                "loanDays" => $politica->loanDays,
                "loanLimit" => $politica->loanLimit,
                "openLoans" => $politica->loanOpenOfAssociation,
                "delayedLoans" => $politica->delayLoan,
                "reserves" => $politica->reserves,
                "answeredReserves" => $politica->answeredReserves
            ];
        }

        return $policy;
    }
}
