<?php

namespace App\Services\Customer;

use App\Entities\Customer\ServiceEntity;
use App\Entities\Customer\ServiceItemEntity;
use App\Entities\Customer\ServicePaymentEntity;
use App\Models\Customer\ServicePaymentModel;
use App\Services\Customer\ServiceService;
use App\Services\UserService;

class ServicePaymentService extends CustomerService
{
    private ?UserService $_userService = null;
    private ?ServiceService $_serviceService = null;
    public function __construct(mixed $request = null)
    {
        parent::__construct($request);
        $this->addClassName('ServicePayment');
    }
    public function getModelClass(): ServicePaymentModel
    {
        return new ServicePaymentModel();
    }
    public function getEntityClass(): ServicePaymentEntity
    {
        return new ServicePaymentEntity();
    }
    public function getFormFields(): array
    {
        return [
            "serviceinfo_uid",
            "ownerinfo_uid",
            "item_type",
            "item_uid",
            "billing_cycle",
            "amount",
            "billing_at",
            "issue_at",
            "status",
        ];
    }
    public function getFilterFields(): array
    {
        return ["serviceinfo_uid", "ownerinfo_uid", 'user_uid', 'item_type', 'item_uid', 'billing_cycle', 'status'];
    }
    public function getBatchJobFields(): array
    {
        return ['status'];
    }
    public function getIndexFields(): array
    {
        return ['serviceinfo_uid', "ownerinfo_uid", 'item_type', 'item_uid', 'billing_cycle',  'amount', 'billing_at', 'issue_at', 'countdown', 'status', 'user_uid'];
    }
    public function getUSerService(): UserService
    {
        if (!$this->_userService) {
            $this->_userService = new UserService($this->request);
        }
        return $this->_userService;
    }
    public function getServiceService(): ServiceService
    {
        if (!$this->_serviceService) {
            $this->_serviceService = new ServiceService($this->request);
        }
        return $this->_serviceService;
    }
    //Entity의 관련객체정의용
    //기본 기능부분
    //FieldForm관련용
    public function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            case 'serviceinfo_uid':
                $options = $this->getServiceService()->getEntities();
                break;
            case 'ownerinfo_uid':
                $options = $this->getClientService()->getEntities();
                break;
            case 'user_uid':
                $options = $this->getUserService()->getEntities();
                break;
            case 'item_uid':
                $options = [];
                break;
            default:
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    //미납서비스 정보
    final public function getUnPaidCountByService(): array
    {
        $sql = sprintf("SELECT serviceinfo_uid,COUNT(*) as CNT
                FROM serviceinfo_payment 
                WHERE billing_at < NOW() AND amount > 0 AND status = '%s'
                GROUP BY serviceinfo_uid", DEFAULTS['STATUS']);
        $unpaids = [];
        foreach ($this->getModel()->query($sql)->getResult() as $row) {
            $unpaids[$row->serviceinfo_uid] = $row->CNT;
        }
        return $unpaids;
    }
    //결체처리정보 등록 : ServiceItemService에서 사용
    public function createByServiceItem(ServiceItemEntity $serviceItemEntity): ServicePaymentEntity
    {
        $serviceEntity = $this->getServiceService()->getEntity($serviceItemEntity->getServiceUid());
        if (!$serviceEntity) {
            throw new \Exception("{$serviceItemEntity->getServiceUid()}에 대한 서비스정보를 찾을수 없습니다.");
        }
        $formDatas = [
            'serviceinfo_uid' => $serviceItemEntity->getServiceUid(),
            'ownerinfo_uid' => $serviceEntity->getOwnerUid(),
            'item_type' => $serviceItemEntity->getItemType(),
            'item_uid' => $serviceItemEntity->getItemUid(),
            'billing_cycle' => $serviceItemEntity->getBillingCycle(),
            'amount' => $serviceItemEntity->getAmount(),
            'billing_at' => $serviceEntity->getBillingAt(),
            'issue_at' => date('Y-m-d'),
        ];
        //금액(amount)가 0원일경우는 바로 결제완료 및 결제자 등록 처리함.
        if ($serviceItemEntity->getAmount() === 0) {
            $formDatas['user_uid'] = $this->getMyAuth()->getUIDByAuthInfo();
            $formDatas['status'] = 'paid';
        }
        return $this->create($formDatas);
    }
    //Service정보 와 관리자가 기존 정보과 같고, 결제가 아직 완료되지 않은 결제정보의 관리자 변경
    public function modifyOwnerByService(ServiceEntity $serviceEntity, int $ownerinfo_uid)
    {
        $wheres = [
            'serviceinfo_uid' => $serviceEntity->getPK(),
            'ownerinfo_uid' => $serviceEntity->getOwnerUID(),
            'status' => DEFAULTS['STATUS']
        ];
        foreach ($this->getEntities($wheres) as $entity) {
            $this->modify($entity, ['ownerinfo_uid' => $ownerinfo_uid]);
        }
    }
}
