<?php

namespace App\Services\Customer;

use App\Entities\Customer\ServiceEntity;
use App\Helpers\Customer\ServiceHelper;
use App\Models\Customer\ServiceModel;
use App\Processors\Customer\ServiceV1Processor as Proceessor;
use App\Services\Equipment\ServerService;
use App\Services\PaymentService;
use DateTimeImmutable;
use DateTimeZone;

class ServiceService extends CustomerService
{
    private ?ServerService $_serverService = null;
    private ?PaymentService $_paymentService = null;
    public function __construct()
    {
        parent::__construct(new ServiceModel(), new ServiceHelper());
        $this->addClassName('Service');
    }
    public function getFormFields(): array
    {
        return [
            "site",
            "location",
            "clientinfo_uid",
            'serverinfo_uid',
            "rack",
            "line",
            "title",
            "start_at",
            "billing_at",
            "status",
            'sale',
            'amount',
            "history",
        ];
    }
    public function getFormFilters(): array
    {
        return [
            'site',
            'location',
            'clientinfo_uid',
            'serverinfo_uid',
            'rack',
            'line',
            'status',
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'site',
            'location',
            'clientinfo_uid',
            'serverinfo_uid',
            'sale',
            'amount',
            'billing_at',
            'status',
            'start_at',
            'updated_at',
        ];
    }
    public function getIndexFilters(): array
    {
        return [
            'site',
            'location',
            'clientinfo_uid',
            'serverinfo_uid',
            'user_uid', //home의 최신신규서버현황에서 사용
            'status',
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['site', 'location', 'clientinfo_uid', 'status'];
    }
    final public function getBatchjobButtons(): array
    {
        return [
            'batchjob' => '일괄 처리 ',
        ];
    }
    public function getFormRule(string $action, string $field): string
    {
        if (is_array($field)) {
            throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
        }
        switch ($field) {
            case "serverinfo_uid":
                $rule  = "required|numeric";
                break;;
            default:
                $rule = parent::getFormRule($action, $field);
                break;
        }
        return $rule;
    }
    final public function getPaymentService(): PaymentService
    {
        if (!$this->_paymentService) {
            $this->_paymentService = new PaymentService();
        }
        return $this->_paymentService;
    }
    public function getServerService(): ServerService
    {
        if (!$this->_serverService) {
            $this->_serverService = new ServerService();
        }
        return $this->_serverService;
    }
    //interval을 기준으로 최근 신규 서비스정보 가져오기
    final public function getNewServiceEntities(int $interval, string $status = ServiceEntity::DEFAULT_STATUS): array
    {
        return $this->getEntities(sprintf("start_at >= NOW()-INTERVAL {$interval} DAY AND status = '%s'", $status));
    }
    //서비스별 총 금액
    final public function getTotalAmounts($where = []): array
    {
        $rows = $this->getModel()->groupBy('clientinfo_uid')->select("clientinfo_uid,SUM(amount) AS amount")
            ->where($where)
            ->get()->getResult();
        $amounts = [];
        foreach ($rows as $row) {
            $amounts[$row->clientinfo_uid] = $row->amount;
        }
        return $amounts;
    }
    //다음 달로 결제일 가져오기.
    final public function getNextMonthDate(ServiceEntity $entity): string
    {
        // $sql = "UPDATE serviceinfo SET billing_at =
        //         IF(DAY(billing_at) > DAY(LAST_DAY(billing_at)),
        //             LAST_DAY(DATE_ADD(billing_at, INTERVAL 1 MONTH)),
        //             DATE_ADD(billing_at, INTERVAL 1 MONTH)
        //         ) WHERE uid = ?";
        // return $this->getModel()->query($sql, [$entity->getPK()]);
        // 입력된 날짜를 DateTime 객체로 변환
        $date = new DateTimeImmutable($entity->getBillingAt(), new DateTimeZone('Asia/Tokyo'));
        // 현재 일(day)을 저장
        $day = (int)$date->format('d');
        // 다음달로 이동 (DateInterval 사용)
        $date->modify('first day of next month');
        // 다음달의 마지막 날 계산
        $lastDayOfNextMonth = (int)$date->format('t');
        // 현재 날짜가 다음달의 마지막 날보다 크면 -> 마지막 날로 설정
        if ($day > $lastDayOfNextMonth) {
            $day = $lastDayOfNextMonth;
        }
        // 일(day)을 설정
        $date->setDate((int)$date->format('Y'), (int)$date->format('m'), $day);
        // 최종 결과 리턴 (YYYY-MM-DD)
        return $date->format('Y-m-d');
    }
    //서비스금액관련처리
    public function setAmount(ServiceEntity $entity, int $calculatedServerAmount, string $callBack = "updateForService"): ServiceEntity
    {
        //기본:상면비+회선비+서버금액(price)+서버파트연결(월비용)-할인액
        $amount = $entity->getRack() + $entity->getLine() + $calculatedServerAmount - $entity->getSale();
        //결제정보 반영
        $paymentEntity = $this->getPaymentService()->$callBack($entity, $amount);
        return $this->getModel()->modify($entity, ['amount' => $amount, 'payment_uid' => $paymentEntity->getPK()]);
    }
    //기본 기능부분
    //FieldForm관련용
    public function getFormOption(string $field, array $options = []): array
    {
        switch ($field) {
            case 'serverinfo_uid':
                $options = $this->getServerService()->getEntities();
                break;
            default:
                $options = parent::getFormOption($field, $options);
                break;
        }
        return $options;
    }
    //생성
    protected function create_process(array $formDatas): ServiceEntity
    {
        if (!isset($formDatas['serverinfo_uid'])) {
            throw new \Exception('변경할 서버가 지정되지 않았습니다.');
        }
        $processor = new Proceessor(
            \Config\Database::connect(),
            $this,
            $this->getServerService(),
            $this->getPaymentService(),
            $this->getMylogService()
        );
        return $processor->create($formDatas);
    }
    //수정
    protected function modify_process(mixed $entity, array $formDatas): ServiceEntity
    {
        $processor = new Proceessor(
            \Config\Database::connect(),
            $this,
            $this->getServerService(),
            $this->getPaymentService(),
            $this->getMylogService()
        );
        return $processor->modify($entity, $formDatas);
    }
    //삭제
    public function delete(mixed $entity): ServiceEntity
    {
        $processor = new Proceessor(
            \Config\Database::connect(),
            $this,
            $this->getServerService(),
            $this->getPaymentService(),
            $this->getMylogService()
        );
        return $processor->delete($entity);
    }
    //대체서버추가
    public function addeAlternativeServer(ServiceEntity $entity, array $formDatas): ServiceEntity
    {
        if (!array_key_exists('serverinfo_uid', $formDatas)) {
            throw new \Exception(__METHOD__ . "에서 오류발생:대체서버가 지정되지 않았습니다.");
        }
        $processor = new Proceessor(
            \Config\Database::connect(),
            $this,
            $this->getServerService(),
            $this->getPaymentService(),
            $this->getMylogService()
        );
        return $processor->addeAlternativeServer($entity, $formDatas['serverinfo_uid']);
    }
    public function replaceMainServer(ServiceEntity $entity, array $formDatas): ServiceEntity
    {
        if (!array_key_exists('serverinfo_uid', $formDatas)) {
            throw new \Exception(__METHOD__ . "에서 오류발생:메인서버로 전환할 대체서버가 지정되지 않았습니다.");
        }
        $processor = new Proceessor(
            \Config\Database::connect(),
            $this,
            $this->getServerService(),
            $this->getPaymentService(),
            $this->getMylogService()
        );
        return $processor->replaceMainServer($entity, $formDatas['serverinfo_uid']);
    }

    public function terminateServer(ServiceEntity $entity, array $formDatas): ServiceEntity
    {
        if (!array_key_exists('serverinfo_uid', $formDatas)) {
            throw new \Exception(__METHOD__ . "에서 오류발생:메인서버로 전환할 대체서버가 지정되지 않았습니다.");
        }
        $this->getServerService()->detachFromService($formDatas['serverinfo_uid']);
        return $entity;
    }
    //비고(History)설정
    public function history(mixed $entity, array $formDatas): ServiceEntity
    {
        return $this->getModel()->modify($entity, $formDatas);
    }
}
