<?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 추가 함수
    //일회성 추가용
    public function create_form_process(array $formDatas = []): array
    {
        $formDatas = parent::create_form_process($formDatas);
        $formDatas['billing'] = PAYMENT['BILLING']['ONETIME'];
        $formDatas['billing_at'] = date('Y-m-d');
        $formDatas['pay']        = PAYMENT['PAY']['ACCOUNT'];
        $formDatas['status']     = STATUS['UNPAID'];
        return $formDatas;
    }
    //청구서 발행관련
    private function invoice_pre_process(): array
    {
        $postDatas = $this->request->getPost();
        $uids = $postDatas['batchjob_uids'] ?? [];
        if (empty($uids)) {
            throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 청구서에 적용될 리스트를 선택하셔야합니다");
        }
        return $uids;
    }
    private function invoice_result_process(string $action): string|RedirectResponse
    {
        return $this->action_render_process($action, $this->getViewDatas(), $this->request->getVar('ActionTemplate') ?? 'payment');
    }
    public function invoice(): string|RedirectResponse
    {
        try {
            $action = __FUNCTION__;
            $this->action_init_process($action);
            //변경할 UIDS
            $uids = $this->invoice_pre_process();
            $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->invoice_result_process($action);
        } catch (\Throwable $e) {
            return $this->action_redirect_process('error', static::class . '->' . __FUNCTION__ . "에서 {$this->getTitle()} 청구서발행 오류:" . $e->getMessage());
        }
    }
    public function paid($uid): string|RedirectResponse
    {
        try {
            $entity = $this->service->paid($uid);
            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());
        }
    }
}
