<?php

namespace App\Services;

use App\DTOs\PaymentDTO;
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 CodeIgniter\Database\Exceptions\DatabaseException;
use DateTime;
use RuntimeException;

class PaymentService extends CommonService
{
    private $_form = null;
    private $_helper = null;
    public function __construct(PaymentModel $model)
    {
        parent::__construct($model);
        $this->addClassPaths('Payment');
    }
    protected function getDTOClass(): string
    {
        return PaymentDTO::class;
    }
    public function getEntityClass(): string
    {
        return PaymentEntity::class;
    }
    public function createDTO(array $formDatas): PaymentDTO
    {
        return new PaymentDTO($formDatas);
    }
    public function getFormService(): PaymentForm
    {
        if ($this->_form === null) {
            $this->_form = new PaymentForm();
            $this->_form->setAttributes([
                'pk_field'         => $this->model->getPKField(),
                'title_field'      => $this->model->getTitleField(),
                'table'            => $this->model->getTable(),
                'useAutoIncrement' => $this->model->useAutoIncrement(),
                'class_path' => $this->getClassPaths(false)
            ]);
        }
        return $this->_form;
    }
    public function getHelper(): PaymentHelper
    {
        if ($this->_helper === null) {
            $this->_helper = new PaymentHelper();
            $this->_helper->setAttributes([
                'pk_field'         => $this->model->getPKField(),
                'title_field'      => $this->model->getTitleField(),
                'table'            => $this->model->getTable(),
                'useAutoIncrement' => $this->model->useAutoIncrement(),
                'class_path' => $this->getClassPaths(false)
            ]);
        }
        return $this->_helper;
    }
    public function action_init_process(string $action, array $formDatas = []): void
    {
        $fields          = [
            "serviceinfo_uid",
            "title",
            "amount",
            "billing",
            "billing_at",
            "pay",
            "status",
            "content",
        ];
        $filters = ['user_uid', 'clientinfo_uid', 'serviceinfo_uid', 'status', 'billing', 'pay'];
        $indexFilter     = ['clientinfo_uid', 'serviceinfo_uid', 'status', 'billing', 'pay'];
        $batchjobFilters = ['status'];
        $actionButtons = ['view' => ICONS['SEARCH'], 'paid' => '결제'];
        $batchjobButtons = ['batchjob' => '일괄결제', 'invoice' => '청구서발행'];
        switch ($action) {
            case 'create':
            case 'create_form':
                break;
            case 'modify':
            case 'modify_form':
                break;
            case 'view':
                $fields = [
                    'clientinfo_uid',
                    "serviceinfo_uid",
                    'billing',
                    'title',
                    'amount',
                    'billing_at',
                    'pay',
                    'status',
                    'updated_at',
                    'countdown',
                    'user_uid',
                    'created_at',
                    'content'
                ];
                break;
            case 'index':
            case 'download':
                $fields = [
                    'clientinfo_uid',
                    "serviceinfo_uid",
                    'billing',
                    'title',
                    'amount',
                    'billing_at',
                    'pay',
                    'status',
                    'updated_at',
                    'countdown',
                    'user_uid',
                    'created_at'
                ];
                break;
        }
        $this->getFormService()->setFormFields($fields);
        $this->getFormService()->setFormRules($action, $fields);
        $this->getFormService()->setFormFilters($filters);
        $this->getFormService()->setFormOptions($action, $filters, $formDatas);
        $this->getFormService()->setIndexFilters($indexFilter);
        $this->getFormService()->setActionButtons($actionButtons);
        $this->getFormService()->setBatchjobFilters($batchjobFilters);
        $this->getFormService()->setBatchjobButtons($batchjobButtons);
    }
    //총 미납건수, 금액
    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();
        // echo $builder->getCompiledSelect(false); //초기화 없이 SQL만 보고 싶을 때: getCompiledSelect(false) ← 꼭 false!            
        $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;
    }
    //List 검색용
    //FormFilter 조건절 처리
    public function setFilter(string $field, mixed $filter_value): void
    {
        switch ($field) {
            case 'role':
                //FIND_IN_SET()은 MySQL 함수이므로 CodeIgniter가 이를 일반 컬럼명으로 착각하고 escape하게 되면 오류가 발생
                // 따라서 ->where($sql, null, false)로 명시하여 escape를 꺼줘야 정상 작동
                $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);
    }
    //추가기능
    //일회성 입력용
    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']);
        $formDatas['clientinfo_uid'] = $serviceEntity->getClientInfoUID();
        $entity = parent::create_process($formDatas);
        if (!$entity instanceof PaymentEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 PaymentEntity만 가능");
        }
        //선결제인경우 서비스정보에 결제일 변경용
        if ($formDatas['billing'] === PAYMENT['BILLING']['PREPAYMENT'] && array_key_exists('billing_at', $formDatas)) {
            service('customer_serviceservice')->updateBillingAt($entity->getServiceInfoUID(), $entity->getBillingAt());
        }
        return $entity;
    }

    protected function modify_process($entity, array $formDatas): PaymentEntity
    {
        $entity = parent::modify_process($entity, $formDatas);
        if (!$entity instanceof PaymentEntity) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:Return Type은 PaymentEntity만 가능");
        }
        //선결제인경우 서비스정보에 결제일 변경용
        if ($formDatas['billing'] === PAYMENT['BILLING']['PREPAYMENT'] && array_key_exists('billing_at', $formDatas)) {
            service('customer_serviceservice')->updateBillingAt($entity->getServiceInfoUID(), $entity->getBillingAt());
        }
        return $entity;
    }

    //지불 관련
    //일괄 지불용
    protected function batchjob_process($entity, array $formDatas): object
    {
        // modify_process를 호출하여 로직 재사용 (PK 로드 및 PK 제거/방어 로직 포함)
        $entity = parent::batchjob_process($entity, $formDatas);
        //지불방식에 따른 고객 예치금,쿠폰,포인트 처리
        service('customer_clientservice')->updateWalletByPayment($entity);
        return $entity;
    }
    //단일 지불용
    public function paid($uid): PaymentEntity
    {
        $db = \Config\Database::connect();
        try {
            //트랜잭션 도중 DB 오류가 발생하면 DatabaseException을 던지도록 설정 
            $db->transException(true)->transStart();
            $entity = $this->getEntity($uid);
            if (!$entity instanceof PaymentEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:[{$uid}]에 대한 결제정보를 찾을 수 없습니다.");
            }
            //결제 완료 처리 후 추가정보 처리
            $entity = parent::modify_process($entity, ['status' => STATUS['PAID']]);
            //지불방식에 따른 고객 예치금,쿠폰,포인트 처리
            service('customer_clientservice')->updateWalletByPayment($entity);
            $db->transComplete();
            return $entity;
        } catch (DatabaseException $e) {
            // DatabaseException을 포착하면 자동으로 롤백 처리됨
            throw new RuntimeException(sprintf(
                "\n----[%s]에서 트랜잭션 실패: DB 오류----\n%s\n%s\n------------------------------\n",
                __METHOD__,
                $this->model->getLastQuery(),
                $e->getMessage()
            ), $e->getCode(), $e);
        } catch (\Throwable $e) {
            $db->transRollback(); // 예외 발생 시 수동으로 롤백
            throw new RuntimeException($e->getMessage(), 0, $e);
        }
    }

    //청구서 관련
    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'      => [],
            ];
        }
        //entities에 총 결제금액 설정
        $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 getFormDatasByService(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->getFormDatasByService($serviceEntity);
        $fields = array_keys($formDatas);
        $this->getFormService()->setFormFields($fields);
        $this->getFormService()->setFormRules('create', $fields);
        return parent::create_process($formDatas);
    }
    public function modifyByService(ServiceEntity $serviceEntity): PaymentEntity
    {
        //서비스정보의 청구방식이 Month이고 지급기한일과 같고,상태가 UNPAID인 결제정보 가져와서 결제정보 수정
        $entity = $this->getEntity([
            'serviceinfo_uid' => $serviceEntity->getPK(),
            'billing' => PAYMENT['BILLING']['MONTH'],
            'billing_at' =>  $serviceEntity->getBillingAt(),
            'status' =>  STATUS['UNPAID']
        ]);
        if (!$entity instanceof PaymentEntity) { //해당조건에 맞는게 없으면 생성
            $entity = $this->createByService($serviceEntity);
        } else {
            $formDatas = $this->getFormDatasByService($serviceEntity);
            $fields = array_keys($formDatas);
            $this->getFormService()->setFormFields($fields);
            $this->getFormService()->setFormRules('modify', $fields);
            $entity = parent::modify_process($entity, $formDatas);
        }
        return $entity;
    }
    //서버파트별 일회성 관련
    private function getFormDatasByServerPart(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['amount']          = $serverPartEntity->getAmount();
        $formDatas['billing']         = $formDatas['billing'] ?? PAYMENT['BILLING']['ONETIME'];
        $formDatas['billing_at']      = date('Y-m-d');
        $formDatas['pay']             = $formDatas['pay'] ?? PAYMENT['PAY']['ACCOUNT'];
        $formDatas['status']          = $formDatas['status'] ?? STATUS['UNPAID'];
        $formDatas['title']         = sprintf("%s 일회성비용", $formDatas['title'] ?? $serverPartEntity->getTitle());
        return $formDatas;
    }
    public function createByServerPart(ServerPartEntity $serverPartEntity): PaymentEntity
    {
        $formDatas = $this->getFormDatasByServerPart($serverPartEntity);
        $fields = array_keys($formDatas);
        $this->getFormService()->setFormFields($fields);
        $this->getFormService()->setFormRules('create', $fields);
        return parent::create_process($formDatas);
    }
    public function modifyByServerPart(ServerPartEntity $serverPartEntity): PaymentEntity
    {
        if ($serverPartEntity->getServiceInfoUID() === null) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서비스정보가 정의되지 않아 일회성 상품을 설정하실수 없습니다.");
        }
        //서버파트정보의 서비스번호가 같고, 청구방식이 onetime이고 상태가 UNPAID인 결제정보 가져와서 결제정보 수정
        $entity = $this->getEntity([
            'serverpartinfo_uid' => $serverPartEntity->getPK(),
            'serviceinfo_uid' => $serverPartEntity->getServiceInfoUID(),
            'billing' => PAYMENT['BILLING']['ONETIME'],
            'status' =>  STATUS['UNPAID']
        ]);
        if (!$entity instanceof PaymentEntity) {
            $entity = $this->createByServerPart($serverPartEntity);
        } else {
            $formDatas = $this->getFormDatasByServerPart($serverPartEntity);
            $fields    = array_keys($formDatas);
            $this->getFormService()->setFormFields($fields);
            $this->getFormService()->setFormRules('modify', $fields);
            $entity = parent::modify_process($entity, $formDatas);
        }
        return $entity;
    }
}
