<?php

include("GnutecaWebServices.class.php");

class gnuteca3WebServicesPenalties
{
    private $webService;
    private $MIOLO;

    public function __construct() 
    {
        $this->webService = new GWebServices();
        $this->MIOLO = MIOLO::getInstance();
    }

    /**
     * WebService que lista as penalidades do usuário
     * @param int $clientId
     * @param string $clientPassword
     * @param int $personId
     * @param int $pageNumber
     * @return string|null JSON com as penalidades do usuário
     */
    public function listPenalties(
        $clientId,
        $clientPassword,
        $personId,
        $pageNumber = null
        ) {
        $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("listPenalties", false)) 
        {
            return $this->createJsonMessageResponse($this->webService->__getErrorStr());
        }

        if (empty($personId))
        {
            return $this->createJsonMessageResponse("Usuário não informado");
        }

        $busPenalty = $this->MIOLO->getBusiness('gnuteca3', 'BusPenalty');

        $busPenalty->personIdS = $personId;
        $penalties = $busPenalty->searchPenalty(true);

        if(!empty($pageNumber))
        {
            $paginatedPenalties = array_chunk($penalties, LISTING_NREGS);
            $penalties = $paginatedPenalties[$pageNumber - 1];
            $retorno->numberOfPages = count($paginatedPenalties);
        }

        $retorno->penalties = array_map(function($penalty)
        {
            return 
            [
                "penaltyId" => $penalty->penaltyId,
                "observation" => $penalty->observation ?? '-',
                "penaltyDate" => $penalty->penaltyDate ?? '-',
                "penaltyEndDate" => $penalty->penaltyEndDate ?? '-',
                "libraryUnit" => $penalty->libraryName ?? '-'
            ];
        }, $penalties);

        return json_encode($retorno);
    }

    private function createJsonMessageResponse($message)
    {
        return json_encode((object) [
            "message" => $message,
        ]);
    }
}