<?php

namespace lib\Controllers;

use lib\Services\AddDbService;
use lib\Services\ClientService;
use lib\Services\HistoryService;
use lib\Services\KCSService;
use lib\Services\MemberService;
use lib\Services\ServiceService;
use lib\Services\VPCService;
use lib\Helpers\ServiceHelper;

class SiteController extends CommonController
{
    private ?ServiceService $_service = null;
    private ?MemberService $_memberService = null;
    private ?ClientService $_clientService = null;
    private ?VPCService $_vpcService = null;
    private ?KCSService $_kcsService = null;
    private ?HistoryService $_historyService = null;
    private ?AddDbService $_addDbService = null;
    public function __construct()
    {
        parent::__construct();
        $this->helper = new ServiceHelper();
    } //

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

    public function getMemberService(): MemberService
    {
        if ($this->_memberService === null) {
            $this->_memberService = new MemberService();
        }
        return $this->_memberService;
    }

    public function getClientService(): ClientService
    {
        if ($this->_clientService === null) {
            $this->_clientService = new ClientService();
        }
        return $this->_clientService;
    }

    public function getVPCService(): VPCService
    {
        if ($this->_vpcService === null) {
            $this->_vpcService = new VPCService();
        }
        return $this->_vpcService;
    }
    public function getKCSService(): KCSService
    {
        if ($this->_kcsService === null) {
            $this->_kcsService = new KCSService();
        }
        return $this->_kcsService;
    }
    public function getHistoryService(): HistoryService
    {
        if ($this->_historyService === null) {
            $this->_historyService = new HistoryService();
        }
        return $this->_historyService;
    }
    public function getAddDbService(): AddDbService
    {
        if ($this->_addDbService === null) {
            $this->_addDbService = new AddDbService();
        }
        return $this->_addDbService;
    }

    //Dashboard , default_alert.php 
    //CLI 접속방법 : php index.php SiteController/dashboard
    //WEB 접속방법 : http://localhost/SiteController/dashboard
    public function dashboard()
    {
        // 최근7일 신규서버수
        //예외,service_line = "test","substitution"
        $excepts          = ["test", "substitution"];
        $this->day = intval($_ENV['SITE_DASHBOARD_DAY'] ?? $_SERVER['SITE_DASHBOARD_DAY'] ?? 7);
        $this->newServers = $this->getService()->getNewServerCount($this->day, $excepts);
        // 금일기준 미납서버수
        //예외,service_line = "test","substitution",C012:게임윙,C116:WinIDC,C219:IDC-JP        
        $excepts          = ["test", "substitution", 'C116', 'C012', 'C219'];
        $this->unPayments = $this->getService()->getUnPaymentCount($excepts);
        return $this->render(__FUNCTION__);
    }

    //서비스카운팅 , total_counting.php 
    //CLI 접속방법 : php index.php site/totalcount/sitekey/dbms.prime-idc.jp
    //WEB 접속방법 : http://localhost/site/totalcount/sitekey/dbms.prime-idc.jp
    public function totalcount(mixed $sitekey = null): string
    {
        if ($sitekey === null) {
            $sitekey = $this->getSegments('sitekey');
            if ($sitekey === null) {
                throw new \Exception("sitekey 값이 정의되지 않았습니다.");
            }
        }

        $this->siteInfo = $this->getConfig()->getSiteInfo($sitekey);
        if (!$this->siteInfo) {
            throw new \Exception("[{$sitekey}] 값에 해당하는 사이트정보가 존재하지 않습니다.");
        }
        $this->totalcount = $this->getService()->getTotalCount($this->siteInfo);
        // echo $sitekey;
        // dd($this->siteInfo);
        $summary = array();
        foreach ($this->siteInfo['totalcount_types'] as $type) {
            $summary[$type] = array("Tokyo" => 0, "Chiba" => 0);
        }
        foreach ($this->totalcount as $company => $service) {
            $summary[$company] = array("Tokyo" => 0, "Chiba" => 0);
            foreach ($service as $name => $location) {
                $summary[$company]['Tokyo'] += $location['Tokyo'];
                $summary[$name]['Tokyo'] += $location['Tokyo'];
                $summary[$company]['Chiba'] += $location['Chiba'];
                $summary[$name]['Chiba'] += $location['Chiba'];
            }
        }
        $total = array("Tokyo" => 0, "Chiba" => 0);
        foreach ($this->siteInfo['totalcount_types'] as $type) {
            $total['Tokyo'] += $summary[$type]['Tokyo'];
            $total['Chiba'] += $summary[$type]['Chiba'];
        }
        $this->summary = $summary;
        $this->total = $total;
        return $this->render(__FUNCTION__);
    }

    //신규서버현황 new_server_list.php
    //CLI 접속방법 : php index.php SiteController/newservices/limit/5
    //WEB 접속방법 : http://localhost/SiteController/newservices/limit/5    
    public function newservices(mixed $limit = 5): string
    {
        //신규서버정보
        $this->limit = intval($limit);
        $this->entitys = $this->getService()->getNews($this->limit);
        // echo $this->getService()->getModel()->getLastQuery();
        // 배열 초기화를 명시적으로 수행
        $users = [];
        $clients = [];
        $vpcs = [];
        $kcss = [];
        $cnt     = 1;
        foreach ($this->entitys as $entity) {
            $serviceCode = $entity->getServiceCode();
            //관리자정보(등록자)
            $users[$serviceCode] = $entity->getMemberCode() ? $this->getMemberService()->getEntitById($entity->getMemberCode()) : "";
            //고객정보
            $clients[$serviceCode] = $this->getClientService()->getEntitByCode($entity->getClientCode());
            //VPC정보
            $vpcs[$serviceCode] = $this->getVPCService()->getCountByServiceCode($serviceCode);
            //KCS정보
            $kcss[$serviceCode] = $this->getKCSService()->getCountByServiceCode($serviceCode);
            $cnt++;
        }
        // dd($this->entitys);
        // 루프가 끝난 후 한번에 속성 할당
        $this->users = $users;
        $this->clients = $clients;
        $this->vpcs = $vpcs;
        $this->kcss = $kcss;
        return $this->render(__FUNCTION__);
    }
    //CLI 접속방법 : php index.php SiteController/newhistorys/limit/5
    //WEB 접속방법 : http://localhost/SiteController/newhistorys/limit/5    
    public function newhistorys(mixed $limit = 5): string
    {
        //신규서버정보
        $this->limit = intval($limit);
        $this->entitys = $this->getHistoryService()->getNews($this->limit);
        // 배열 초기화를 명시적으로 수행
        $services = [];
        $clients = [];
        foreach ($this->entitys as $entity) {
            $pk = $entity->getPK();
            //서비스정보가져오기
            $service = $this->getService()->getServiceByServiceCode($entity->getServiceCode());
            if ($service) {
                //고객정보
                $clients[$pk] = $this->getClientService()->getEntitByCode($service->getClientCode());
                //서비스정보
                $services[$pk] = $service;
            }
        }
        // 루프가 끝난 후 한번에 속성 할당
        $this->services = $services;
        $this->clients  = $clients;
        return $this->render(__FUNCTION__);
    }
    //청구서페이지, depositbillpaper.php 
    //CLI 접속방법 : php index.php SiteController/billpaper/sitekey/dbms.prime-idc.jp/client_code/코드번호
    //WEB 접속방법 : http://localhost/SiteController/billpaper/sitekey/dbms.prime-idc.jp/client_code/코드번호
    public function billpaper(mixed $sitekey = null, mixed $client_code = null): string
    {
        if ($sitekey === null) {
            $sitekey = $this->getSegments('sitekey');
            if ($sitekey === null) {
                throw new \Exception("sitekey 값이 정의되지 않았습니다.");
            }
        }
        if ($client_code === null) {
            $client_code = $this->getSegments('client_code');
            if ($client_code === null) {
                throw new \Exception("client_code 값이 정의되지 않았습니다.");
            }
        }
        $this->siteInfo = $this->getConfig()->getSiteInfo($sitekey);
        if (!$this->siteInfo) {
            throw new \Exception("[{$sitekey}] 값에 해당하는 사이트정보가 존재하지 않습니다.");
        }
        $this->client = $this->getClientService()->getEntitByCode($client_code);
        if (!$this->client) {
            throw new \Exception("[{$client_code}] 값에 해당하는 고객정보가 존재하지 않습니다.");
        }
        return $this->render(__FUNCTION__);
    }
    //부가서비스 : 닷디펜더,딥파인더 등, deepfinder_list.php,dotdefender_list.php 
    //CLI 접속방법 : php index.php SiteController/extraservice/client_code/코드번호
    //WEB 접속방법 : http://localhost/SiteController/extraservice/sitekey/dbms.prime-idc.jp/client_code/코드번호
    public function extraservice(mixed $addb_code = null,): string
    {
        if ($addb_code === null) {
            $addb_code = $this->getSegments('addb_code');
            if ($addb_code === null) {
                throw new \Exception("addb_code 값이 정의되지 않았습니다.");
            }
        }
        //segment의 값이 한글인경우 urldecode가 필요
        $adddb_code = urldecode($addb_code);
        $service_codes = $this->getAddDbService()->getServiceCodesByCode($adddb_code);
        if (!count($service_codes)) {
            throw new \Exception("[{$adddb_code}] 값에 해당하는 부가서비스정보가 존재하지 않습니다.");
        }
        $this->services = $this->getService()->getExtras($service_codes);
        return $this->render(__FUNCTION__);
    }
} //Class
