<?php

namespace App\Services;

use App\Entities\Customer\ClientEntity;
use App\Entities\Customer\ServiceEntity;
use App\Entities\Equipment\ServerEntity;
use App\Entities\Equipment\ServerPartEntity;
use App\Entities\PaymentEntity;
use App\Forms\PaymentForm;
use App\Helpers\PaymentHelper;
use App\Models\PaymentModel;
use App\Services\Customer\Wallet\WalletService;
use DateTime;
use RuntimeException;

class PaymentService extends CommonService
{
    protected string $formClass = PaymentForm::class;
    protected string $helperClass = PaymentHelper::class;

    public function __construct(PaymentModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('Payment');
    }

    public function getEntityClass(): string
    {
        return PaymentEntity::class;
    }

    //총 미납건수, 금액
    final public function getUnPaids(string $group, array $where = []): array
    {
        $builder = $this->model->groupBy($group)
            ->select("{$group},COUNT(uid) as cnt, SUM(amount) as amount")
            ->where(['status' => STATUS['UNPAID']])
            ->where($where)
            ->builder();

        $unPaids = [];
        foreach ($builder->get()->getResult() as $row) {
            $unPaids[$row->$group] = ['cnt' => $row->cnt, 'amount' => $row->amount];
        }
        return $unPaids;
    }

    protected function getEntity_process(mixed $entity): PaymentEntity
    {
        return $entity;
    }

    //FormFilter 조건절 처리
    public function setFilter(string $field, mixed $filter_value): void
    {
        switch ($field) {
            case 'role':
                $where = "FIND_IN_SET(" . $this->model->escape($filter_value) . ", {$this->model->getTable()}.{$field}) > 0";
                $this->model->where($where, null, false);
                break;
            default:
                parent::setFilter($field, $filter_value);
                break;
        }
    }

    //검색어조건절처리
    public function setSearchWord(string $word): void
    {
        $this->model->orLike($this->model->getTable() . '.id', $word, 'both');
        $this->model->orLike($this->model->getTable() . '.email', $word, 'both');
        parent::setSearchWord($word);
    }

    //pay방식에따른 WalletService 등록
    private function getWalletService($pay): WalletService
    {
        $walletService = null;
        switch ($pay) {
            case PAYMENT['PAY']['ACCOUNT']:
                $walletService = service('customer_wallet_accountservice');
                break;
            case PAYMENT['PAY']['COUPON']:
                $walletService = service('customer_wallet_couponservice');
                break;
            case PAYMENT['PAY']['POINT']:
                $walletService = service('customer_wallet_pointservice');
                break;
            default:
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$pay}는 지정되지 않은 지불방식입니다.");
        }
        return $walletService;
    }

    //일회성,선결제,쿠폰,포인트 입력 관련
    protected function create_process(array $formDatas): PaymentEntity
    {
        if (!array_key_exists('serviceinfo_uid', $formDatas)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서비스가 정의되지 않았습니다.");
        }

        $serviceEntity = service('customer_serviceservice')->getEntity($formDatas['serviceinfo_uid']);
        if (!$serviceEntity instanceof ServiceEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$formDatas['serviceinfo_uid']}에 해당하는 서비스정보를 찾을 수 없습니다.");
        }

        $formDatas['clientinfo_uid'] = $serviceEntity->getClientInfoUid();

        $entity = parent::create_process($formDatas);
        if (!$entity instanceof PaymentEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 PaymentEntity만 가능");
        }

        if ($entity->getStatus() === STATUS['PAID']) {
            $this->getWalletService($entity->getPay())->withdrawalByPayment($entity);
        }

        if ($entity->getBilling() === PAYMENT['BILLING']['PREPAYMENT']) {
            service('customer_serviceservice')->updateBillingAt($entity->getServiceInfoUid(), $entity->getBillingAt());
        }

        return $entity;
    }

    protected function modify_process($entity, array $formDatas): PaymentEntity
    {
        if ($entity->getStatus() === STATUS['PAID']) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 이미 지불된 결제정보는 수정이 불가합니다.");
        }

        $serviceEntity = service('customer_serviceservice')->getEntity($entity->getServiceInfoUid());
        if (!$serviceEntity instanceof ServiceEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$entity->getServiceInfoUid()}에 해당하는 서비스정보를 찾을 수 없습니다.");
        }

        $entity = parent::modify_process($entity, $formDatas);
        if (!$entity instanceof PaymentEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 PaymentEntity만 가능");
        }

        if ($entity->getStatus() === STATUS['PAID']) {
            $this->getWalletService($entity->getPay())->withdrawalByPayment($entity);
        }

        if ($entity->getBilling() === PAYMENT['BILLING']['PREPAYMENT']) {
            service('customer_serviceservice')->updateBillingAt($entity->getServiceInfoUid(), $entity->getBillingAt());
        }

        return $entity;
    }

    protected function delete_process($entity): PaymentEntity
    {
        if ($entity->getStatus() === STATUS['PAID']) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 이미 지불된 결제정보는 수정이 불가합니다.");
        }
        return parent::delete_process($entity);
    }

    //청구서 관련
    public function getInvoices(ClientEntity $clientEntity, ServiceEntity $serviceEntity, PaymentEntity $entity, array $rows): array
    {
        if (!array_key_exists($clientEntity->getPK(), $rows)) {
            $rows[$clientEntity->getPK()] = [
                'name' => $clientEntity->getName(),
                'total_amount' => 0,
                'services' => [],
            ];
        }

        if (!array_key_exists($serviceEntity->getPK(), $rows[$clientEntity->getPK()]['services'])) {
            $serverEntity = service('equipment_serverservice')->getEntity($serviceEntity->getServerInfoUid());
            if (!$serverEntity instanceof ServerEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:[{$serviceEntity->getServerInfoUid()}]에 대한 서버정보를 찾을 수 없습니다.");
            }
            $rows[$clientEntity->getPK()]['services'][$serviceEntity->getPK()] = [
                'ip' => $serverEntity->getIP(),
                'billing_at' => $serviceEntity->getBillingAt(),
                'amount' => 0,
                'items' => [],
            ];
        }

        $rows[$clientEntity->getPK()]['services'][$serviceEntity->getPK()]['items'][] = [
            'title' => $entity->getTitle(),
            'amount' => $entity->getAmount()
        ];

        $rows[$clientEntity->getPK()]['services'][$serviceEntity->getPK()]['amount'] += $entity->getAmount();
        $rows[$clientEntity->getPK()]['total_amount'] += $entity->getAmount();

        return $rows;
    }

    //서비스관련
    private function getFormDatasFromService(ServiceEntity $serviceEntity, array $formDatas = []): array
    {
        $formDatas['serviceinfo_uid'] = $serviceEntity->getPK();
        $formDatas["clientinfo_uid"] = $serviceEntity->getClientInfoUid();
        $formDatas['amount'] = $serviceEntity->getAmount();
        $formDatas['billing'] = $formDatas['billing'] ?? PAYMENT['BILLING']['MONTH'];
        $formDatas['billing_at'] = $serviceEntity->getBillingAt();
        $formDatas['pay'] = $formDatas['pay'] ?? PAYMENT['PAY']['ACCOUNT'];
        $formDatas['status'] = $formDatas['status'] ?? STATUS['UNPAID'];
        $formDatas['title'] = sprintf(
            "%s %s 서비스비용",
            $formDatas['title'] ?? $serviceEntity->getTitle(),
            DateTime::createFromFormat('Y-m-d', $formDatas['billing_at'])->format('Y년 m월')
        );
        return $formDatas;
    }

    public function createByService(ServiceEntity $serviceEntity): PaymentEntity
    {
        $formDatas = $this->getFormDatasFromService($serviceEntity);
        return $this->create_process($formDatas);
    }
    //서비스정보로 결제정보 생성 또는 수정 (일반 운영용: upsert 유지)
    public function modifyByService(ServiceEntity $oldServiceEntity, ServiceEntity $serviceEntity): PaymentEntity
    {
        $entity = $this->getEntity([
            'serviceinfo_uid' => $oldServiceEntity->getPK(),
            'billing' => PAYMENT['BILLING']['MONTH'],
            'billing_at' => $oldServiceEntity->getBillingAt(),
            'status' => STATUS['UNPAID']
        ]);
        if (!$entity instanceof PaymentEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 ServiceEntity만 가능");
        }
        //매칭되는게 있으면(기존 서비스인경우) 아니면 신규등록
        $formDatas = $this->getFormDatasFromService($serviceEntity);
        return $this->modify_process($entity, $formDatas);
    }


    //서버파트별 일회성 관련
    private function getFormDatasFromServerPart(ServerPartEntity $serverPartEntity, array $formDatas = []): array
    {
        if ($serverPartEntity->getServiceInfoUid() === null) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서비스정보가 정의되지 않아 일회성 상품을 설정하실수 없습니다.");
        }
        $formDatas['serviceinfo_uid'] = $serverPartEntity->getServiceInfoUid();
        $formDatas["clientinfo_uid"] = $serverPartEntity->getClientInfoUid();
        $formDatas["serverpartinfo_uid"] = $serverPartEntity->getPK();
        $formDatas['amount'] = $serverPartEntity->getCalculatedAmount();
        $formDatas['billing'] = $formDatas['billing'] ?? PAYMENT['BILLING']['ONETIME'];
        $formDatas['billing_at'] = $serverPartEntity->getBillingAt();
        $formDatas['pay'] = $formDatas['pay'] ?? PAYMENT['PAY']['ACCOUNT'];
        $formDatas['status'] = $formDatas['status'] ?? STATUS['UNPAID'];
        $formDatas['title'] = sprintf("%s 일회성비용", $formDatas['title'] ?? $serverPartEntity->getCustomTitle());
        return $formDatas;
    }

    public function createByServerPart(ServerPartEntity $serverPartEntity): PaymentEntity
    {
        $formDatas = $this->getFormDatasFromServerPart($serverPartEntity);
        return parent::create_process($formDatas);
    }

    public function modifyByServerPart(ServerPartEntity $oldServerPartEntity, ServerPartEntity $serverPartEntity): PaymentEntity
    {
        $entity = $this->getEntity([
            'serverpartinfo_uid' => $oldServerPartEntity->getPK(),
            'serviceinfo_uid' => $oldServerPartEntity->getServiceInfoUid(),
            'billing' => $oldServerPartEntity->getBilling(),
            'billing_at' => $oldServerPartEntity->getBillingAt(),
            'status' => STATUS['UNPAID']
        ]);

        if (!$entity instanceof PaymentEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 기존 서버파트정보의 {$oldServerPartEntity->getTitle()}에 해당하는 결제정보가 존재하지 않습니다.");
        }

        $formDatas = $this->getFormDatasFromServerPart($serverPartEntity);
        return parent::modify_process($entity, $formDatas);
    }

    // ✅ 서비스 해지(서버 분리) 시: 월비용 파트정보는 고객만 연결
    public function terminateByServerPart(ServiceEntity $oldServiceEntity): void
    {
        $entity = $this->getEntity([
            'serviceinfo_uid' => $oldServiceEntity->getPK(),
            'billing' => PAYMENT['BILLING']['MONTH'],
            'billing_at' => $oldServiceEntity->getBillingAt(),
            'status' => STATUS['UNPAID'],
        ]);
        if (!$entity instanceof PaymentEntity) {
            return;
        }
        //매칭되는게 있으면(기존 파트정보서비스인경우) 
        parent::modify_process($entity, ['status' => STATUS['TERMINATED']]);
    }
}
