<?php

namespace lib\Controllers;

use lib\Controllers\CommonController;
use lib\Services\ServiceService;
use lib\Services\MemberService;

abstract class DBMSController extends CommonController
{
    private ?ServiceService $_service = null;
    private ?MemberService $_memberService = null;
    protected function __construct(array $params = [])
    {
        parent::__construct($params);
        //View의 추가디렉토리
        $this->setPath('dbms');
        $this->setLayout('dbms_layout.php');
    } //

    final public function getServiceService(): ServiceService
    {
        if ($this->_service === null) {
            $this->_service = new ServiceService();
        }
        return $this->_service;
    }

    final public function getMemberService(): MemberService
    {
        if ($this->_memberService === null) {
            $this->_memberService = new MemberService();
        }
        return $this->_memberService;
    }
    //자식Controller에서 기본적으로 필요한  client_code, mkid, service_code를 설정합니다.
    final protected function setDefaultRequestData($client = null, $member = null, $service = null): array
    {
        //사용자정보
        $this->client_code = $this->request->get('client_code');
        if ($client && !$this->client_code) {
            throw new \Exception("[client_code]가 정의되지 않았습니다.");
        }
        if ($this->client_code) {
            $this->getClientService()->getModel()->where('Client_Code', $this->client_code);
            $client = $this->getClientService()->getEntity();
            if (!$client) {
                throw new \Exception("[$this->client_code]에 해당하는 고객정보가 존재하지 않습니다.");
            }
        }
        //관리자정보(등록자)
        $this->member_code = $this->request->get('member_code');
        if ($member && !$this->member_code) {
            throw new \Exception("[member_code]가 정의되지 않았습니다.");
        }
        if ($this->member_code) {
            $this->getMemberService()->getModel()->where('id', $this->member_code);
            $member = $this->getMemberService()->getEntity();
            if (!$member) {
                throw new \Exception("[$this->member_code]에 해당하는 관리자정보가 존재하지 않습니다.");
            }
        }
        //서비스정보
        $this->service_code = $this->request->get('service_code');
        if ($service && !$this->service_code) {
            throw new \Exception("[service_code]가 정의되지 않았습니다.");
        }
        if ($this->service_code) {
            $this->getServiceService()->getModel()->where('service_code', $this->service_code);
            $service = $this->getServiceService()->getEntity();
            if (!$service) {
                throw new \Exception("[$this->service_code]에 해당하는 서비스정보가 존재하지 않습니다.");
            }
        }
        return [$client, $member, $service];
    }
} //Class
