<?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;

class ServicePaymentService extends CustomerService
{
    public function __construct()
    {
        parent::__construct();
        $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', 'billing_cycle', 'status'];
    }
    public function getBatchJobFields(): array
    {
        return ['status'];
    }
    public function getIndexFields(): array
    {
        return ["ownerinfo_uid", 'serviceinfo_uid', 'item_type', 'item_uid', 'billing_cycle',  'amount', 'billing_at', 'issue_at', 'countdown', 'status', 'user_uid'];
    }
    public function getBatchJobButtons(): array
    {
        return [
            'invoice' => '청구서 발행',
        ];
    }
    //기본 기능부분
    //FieldForm관련용
    public function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            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 createByServiceItemService(array $formDatas, ServiceItemEntity $serviceItemEntity): ServicePaymentEntity
    {
        $serviceEntity = $this->getServiceService()->getEntity($serviceItemEntity->getServiceUid());
        if (!$serviceEntity) {
            throw new \Exception("{$serviceItemEntity->getServiceUid()}에 대한 서비스정보를 찾을수 없습니다.");
        }
        $formDatas['serviceinfo_uid'] = $serviceItemEntity->getServiceUid();
        $formDatas['ownerinfo_uid'] = $serviceEntity->getOwnerUid();
        $formDatas['item_type'] = $serviceItemEntity->getItemType();
        $formDatas['item_uid'] = $serviceItemEntity->getItemUid();
        $formDatas['billing_cycle'] = $serviceItemEntity->getBillingCycle();
        $formDatas['amount'] = $serviceItemEntity->getAmount();
        $formDatas['billing_at'] = $serviceEntity->getBillingAt();
        $formDatas['issue_at'] = date('Y-m-d');
        return $this->create($formDatas);
    }

    //Service정보 와 관리자가 기존 정보과 같고, 결제가 아직 완료되지 않은 결제정보의 관리자 변경
    public function modifyOwnerByService(ServiceEntity $serviceEntity, int $ownerinfo_uid)
    {
        foreach (
            $this->getEntities([
                'serviceinfo_uid' => $serviceEntity->getPK(),
                'ownerinfo_uid' => $serviceEntity->getOwnerUID(),
                'status' => DEFAULTS['STATUS']
            ]) as $entity
        ) {
            $this->modify($entity, ['ownerinfo_uid' => $ownerinfo_uid]);
        }
    }
    //List 검색용
    //OrderBy 처리
    public function setOrderBy(mixed $field = null, mixed $value = null): void
    {
        $this->getModel()->orderBy('billing_at ASC');
        parent::setOrderBy($field, $value);
    }
}
