<?php

namespace App\Services\Customer;

use App\Entities\Customer\ServiceEntity;
use App\Entities\Equipment\CodeEntity;
use App\Models\Customer\ServiceModel;

use App\Services\Equipment\CodeService;

class ServiceService extends CustomerService
{
    private ?CodeService $_codeService = null;
    private ?string $_searchIP = null;
    public function __construct(mixed $request = null)
    {
        parent::__construct($request);
        $this->addClassName('Service');
    }
    public function getModelClass(): ServiceModel
    {
        return new ServiceModel();
    }
    public function getEntityClass(): ServiceEntity
    {
        return new ServiceEntity();
    }
    public function getFormFields(): array
    {
        return [
            "clientinfo_uid",
            "ownerinfo_uid",
            "type",
            "location",
            "switch",
            "code",
            "raid",
            "billing_at",
            "start_at",
            "status"
        ];
    }
    public function getFilterFields(): array
    {
        return ["clientinfo_uid", 'ownerinfo_uid', 'type', 'location', 'switch', 'code',  'raid', 'status'];
    }
    public function getBatchJobFields(): array
    {
        return ['status'];
    }
    public function getIndexFields(): array
    {
        return ['clientinfo_uid', 'ownerinfo_uid', 'type', 'location', 'switch', 'code', 'raid', 'billing_at', 'start_at', 'updated_at', 'status'];
    }
    public function getCodeService(): CodeService
    {
        if (!$this->_codeService) {
            $this->_codeService = new CodeService($this->request);
        }
        return $this->_codeService;
    }
    //Entity의 관련객체정의용
    public function setSearchIp(string $ip): void
    {
        $this->_searchIP = $ip;
    }
    public function getSearchIp(): string|null
    {
        return $this->_searchIP;
    }
    protected function findAllDatas(array $columns = ['*']): mixed
    {
        $ip = $this->getSearchIp();
        if ($ip) {
            $sql = "SELECT serviceinfo.* FROM serviceinfo
            LEFT JOIN serviceinfo_items ON serviceinfo.uid = serviceinfo_items.serviceinfo_uid
            WHERE serviceinfo_items.item_type = ?
            AND serviceinfo_items.item_uid IN (SELECT uid FROM ipinfo WHERE ip = ?)";
            return $this->getModel()->query($sql, ['IP', $ip])->getResult(ServiceEntity::class);
        }
        return parent::findAllDatas($columns);
    }
    //기본 기능부분
    //FieldForm관련용
    public function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            case 'ownerinfo_uid':
                $options = $this->getClientService()->getEntities();
                break;
            case 'code':
                $options = $this->getCodeService()->getEntities();
                break;
            default:
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    //다음 달로 결제일을 연장합니다.
    final public function extendBillingAt(string $billing_at, string $status): bool
    {
        $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 billing_at = ? AND status = ?";
        return $this->getModel()->query($sql, [$billing_at, $status]);
    }
    public function create(array $formDatas, mixed $entity = null): ServiceEntity
    {
        //code의 경우 서비스중으로 설정작업
        $this->getCodeService()->setStatus($formDatas['code'], CodeEntity::STATUS_OCCUPIED);
        return parent::create($formDatas, $entity);
    }
    public function modify(mixed $entity, array $formDatas): ServiceEntity
    {
        //code가 기존과 다를경우 //toggle,batchjob의 경우 $formDatas에 code가 없을수도 있음
        if (array_key_exists('code', $formDatas) && $formDatas['code'] !== $entity->getCode()) {
            //code의 경우 기존code는 사용가능으로 설정작업
            $this->getCodeService()->setStatus($entity->getCode(), CodeEntity::STATUS_AVAILABLE);
            //coded의 경우 변경된 code는 서비스중으로 설정작업
            $this->getCodeService()->setStatus($formDatas['code'], CodeEntity::STATUS_OCCUPIED);
        }
        return parent::modify($entity, $formDatas);
    }
    final public function delete(mixed $entity): bool
    {
        //code의 경우 기존code는 사용가능으로 설정작업
        $this->getCodeService()->setStatus($entity->getCode(), CodeEntity::STATUS_AVAILABLE);
        return parent::delete($entity);
    }
}
