<?php

namespace lib\Controllers\DBMS;

use lib\Services\AddDbService;
use lib\Services\ClientService;
use lib\Utils\Pagination;

class ServiceController extends DBMSController
{

    private ?ClientService $_clientService = null;
    private ?AddDbService $_addDbService = null;

    public function __construct()
    {
        parent::__construct();
        $this->getView()->setPath('service');
    } //
    public function getClientService(): ClientService
    {
        if ($this->_clientService === null) {
            $this->_clientService = new ClientService();
        }
        return $this->_clientService;
    }
    public function getAddDbService(): AddDbService
    {
        if ($this->_addDbService === null) {
            $this->_addDbService = new AddDbService();
        }
        return $this->_addDbService;
    }

    //부가서비스 : 닷 디펜더,딥 파인더 ,M307-1,M394-2등, deepfinder_list.php,dotdefender_list.php 
    //CLI 접속방법 : php index.php site/service//extra/adddb_code/코드번호
    //WEB 접속방법 : http://localhost/site/service/extra/adddb_code/코드번호
    public function extra(array $params): string
    {
        if (!array_key_exists('adddb_code', $params)) {
            throw new \Exception("adddb_code 값이 정의되지 않았습니다.");
        }
        $this->adddb_code = urldecode($params['adddb_code']);
        //해당 부가서비스의 services_code 목록 가져오기
        //segment의 값이 한글인경우 urldecode가 필요 
        $addDbEntities = $this->getAddDbService()->getEntitiesByCode($this->adddb_code);
        $service_codes = [];
        foreach ($addDbEntities as $entity) {
            $service_codes[] = $entity->getServiceCode();
        }
        if (!count($service_codes)) {
            throw new \Exception("[{$this->adddb_code}] 값에 해당하는 부가서비스정보가 존재하지 않습니다.");
        }
        //전체 사용자정보
        $this->clients = $this->getClientService()->getEntities();
        //부가서비스용 서비스목록 가져오기
        $this->curPage = intval($params['curPage'] ?? $this->request->get('curPage') ?? 1);
        $this->perPage = intval($params['perPage'] ?? $this->request->get('perPage') ?? VIEW_LIST_PERPAGE);
        [$this->total, $this->entities] = $this->getServiceService()->getEntitiesForExtra($this->curPage, $this->perPage, $service_codes);
        $this->pagination = new Pagination($this->total, (int)$this->curPage, (int)$this->perPage);
        return $this->render(__FUNCTION__);
    }
} //Class
