<?php

namespace App\Controllers\Admin;

use App\Entities\Customer\ClientEntity;
use App\Entities\Customer\ServiceEntity;
use App\Entities\PaymentEntity;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;

class PaymentController extends AdminController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        if ($this->service === null) {
            $this->service = service('paymentservice');
        }
        $this->addActionPaths('payment');
    }
    //Action작업관련
    //기본 함수 작업
    //Custom 추가 함수
    final public function onetime_form(): string|RedirectResponse
    {
        try {
            $uid = $this->request->getVar('serviceinfo_uid');
            if (!$uid) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서비스정보 번호가 정의되지 않았습니다..");
            }
            $serviceEntity = service('customer_serviceservice')->getEntity($uid);
            if (!$serviceEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$uid}에 해당하는 서비스정보을 찾을수 없습니다.");
            }
            $action = __FUNCTION__;
            $formDatas = [];
            $formDatas['serviceinfo_uid'] = $uid;
            $formDatas['title'] = $serviceEntity->getTitle() . " 일회성 결제";
            $formDatas['billing'] = PAYMENT['BILLING']['ONETIME'];
            $formDatas['billing_at'] = date('Y-m-d');
            $formDatas['pay']        = PAYMENT['PAY']['ACCOUNT'];
            $formDatas['status']     = STATUS['UNPAID'];
            $this->action_init_process($action, $formDatas);
            $this->addViewDatas('formDatas', $formDatas);
            return $this->action_render_process($action, $this->getViewDatas(), $this->request->getVar('ActionTemplate'));
        } catch (\Throwable $e) {
            return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 생성폼 오류:" . $e->getMessage());
        }
    }
    final public function prepayment_form(): string|RedirectResponse
    {
        try {
            $uid = $this->request->getVar('serviceinfo_uid');
            if (!$uid) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: 서비스정보 번호가 정의되지 않았습니다..");
            }
            $serviceEntity = service('customer_serviceservice')->getEntity($uid);
            if (!$serviceEntity) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생: {$uid}에 해당하는 서비스정보을 찾을수 없습니다.");
            }
            $action = __FUNCTION__;
            $formDatas = [];
            $formDatas['serviceinfo_uid'] = $uid;
            $formDatas['title'] = $serviceEntity->getTitle() . " 선결제";
            $formDatas['amount'] = $serviceEntity->getAmount();
            $formDatas['billing'] = PAYMENT['BILLING']['PREPAYMENT'];
            $formDatas['billing_at'] = $serviceEntity->getBillingAt();
            $formDatas['pay']        = PAYMENT['PAY']['ACCOUNT'];
            $formDatas['status']     = STATUS['PAID'];
            $this->action_init_process($action, $formDatas);
            $this->addViewDatas('formDatas', $formDatas);
            return $this->action_render_process($action, $this->getViewDatas(), $this->request->getVar('ActionTemplate'));
        } catch (\Throwable $e) {
            return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 생성폼 오류:" . $e->getMessage());
        }
    }
    //단일 지불 완료처리
    final public function paid($uid): string|RedirectResponse
    {
        try {
            $entity = $this->service->modify($uid, ['status' => STATUS['PAID']]);
            return $this->action_redirect_process('info', "{$this->getTitle()}에서 {$entity->getTitle()} 결체처리가 완료되었습니다.");
        } catch (\Throwable $e) {
            return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 결제 오류:" . $e->getMessage());
        }
    }
    //청구서 발행관련
    final public function invoice(): string|RedirectResponse
    {
        try {
            $action = __FUNCTION__;
            $this->action_init_process($action);
            //변경할 UIDS
            $uids = $this->request->getPost('batchjob_uids') ?? [];
            if (empty($uids)) {
                throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 청구서에 적용될 리스트를 선택하셔야합니다");
            }
            $rows = [];
            $clientEntities = [];
            $serviceEntities = [];
            foreach ($uids as $uid) {
                //기존 Entity 가져오기
                $entity = $this->service->getEntity($uid);
                if (!$entity instanceof PaymentEntity) {
                    throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 {$uid}에 대한 결제정보를 찾을수 없습니다.");
                }
                //지급기한일이 오늘보다 작거나 같고 미지급인경우
                if ($entity->getBillingAt() <= date("Y-m-d") && $entity->getStatus() === STATUS['UNPAID']) {
                    //고객 정보가져오기
                    if (array_key_exists($entity->getClientInfoUid(), $clientEntities)) {
                        $clientEntity = $clientEntities[$entity->getClientInfoUid()];
                    } else {
                        $clientEntity = service('customer_clientservice')->getEntity($entity->getClientInfoUid());
                        if (!$clientEntity instanceof ClientEntity) {
                            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 오류발생:{$entity->getClientInfoUid()}에 대한 고객정보를 찾을수 없습니다.");
                        }
                        $clientEntities[$entity->getClientInfoUid()] = $clientEntity;
                    }
                    //서비스 정보가져오기
                    if (array_key_exists($entity->getServiceInfoUid(), $serviceEntities)) {
                        $serviceEntity = $serviceEntities[$entity->getServiceInfoUid()];
                    } else {
                        $serviceEntity = service('customer_serviceservice')->getEntity($entity->getServiceInfoUid());
                        if (!$serviceEntity instanceof ServiceEntity) {
                            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서  오류발생:{$entity->getServiceInfoUid()}에 대한 서비스정보를 찾을수 없습니다.");
                        }
                        $serviceEntities[$entity->getServiceInfoUid()] = $serviceEntity;
                    }
                    //Invoice Data 가져오기
                    $rows = $this->service->getInvoices($clientEntity, $serviceEntity, $entity, $rows);
                }
            }
            // dd($rows);
            $this->addViewDatas('rows', $rows);
            return $this->action_render_process($action, $this->getViewDatas(), $this->request->getVar('ActionTemplate') ?? 'payment');
        } catch (\Throwable $e) {
            return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 청구서발행 오류:" . $e->getMessage());
        }
    }
}
