<?php

namespace App\Controllers\Admin\Customer;

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

class PaymentController extends CustomerController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->content_title = lang("{$this->getService()->getClassName()}.title");
        $this->class_path .= $this->getService()->getClassName();
        $this->uri_path .= strtolower($this->getService()->getClassName('/')) . '/';
        // $this->view_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
    }
    public function getService(): PaymentService
    {
        if (!$this->_service) {
            $this->_service = new PaymentService();
        }
        return $this->_service;
    }
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        switch ($this->getService()->getAction()) {
            case 'index':
            case 'invoice':
                $this->service = $this->getService();
                $this->control = $this->getService()->getControlDatas();
                $this->getService()->getHelper()->setViewDatas($this->getViewDatas());
                $actionTemplate = $this->request->getVar('ActionTemplate') ?? $actionTemplate ?? 'payment';
                if ($actionTemplate) {
                    $view_file = $this->view_path . $actionTemplate . DIRECTORY_SEPARATOR . $this->getService()->getAction();
                } else {
                    $view_file = $this->view_path . $this->getService()->getAction();
                }
                $result = view($view_file, ['viewDatas' => $this->getViewDatas()]);
                break;
            default:
                $result = parent::getResultSuccess($message, $actionTemplate);
                break;
        }
        return $result;
    }
    //Index,FieldForm관련
    //Invoice 관련
    public function invoice(): RedirectResponse|string
    {
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            //변경할 UIDS
            $uids = $this->request->getPost('batchjob_uids[]');
            if (!is_array($uids) || !count($uids)) {
                throw new \Exception("청구서에 적용될 리스트를 선택하셔야합니다.");
            }
            $rows = [];
            $clientEntities = [];
            $serviceEntities = [];
            foreach ($uids as $uid) {
                //기존 Entity 가져오기
                $entity = $this->getService()->getEntity($uid);
                if (!$entity instanceof PaymentEntity) {
                    throw new \Exception(__METHOD__ . "에서 {$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 = $this->getService()->getClientService()->getEntity($entity->getClientInfoUID());
                        if (!$clientEntity instanceof ClientEntity) {
                            throw new \Exception(__METHOD__ . "에서 {$entity->getClientInfoUID()}에 대한 고객정보를 찾을수 없습니다.");
                        }
                        $clientEntities[$entity->getClientInfoUID()] = $clientEntity;
                    }
                    //서비스 정보가져오기
                    if (array_key_exists($entity->getServiceInfoUid(), $serviceEntities)) {
                        $serviceEntity = $serviceEntities[$entity->getServiceInfoUid()];
                    } else {
                        $serviceEntity = $this->getService()->getServiceService()->getEntity($entity->getServiceInfoUid());
                        if (!$serviceEntity instanceof ServiceEntity) {
                            throw new \Exception(__METHOD__ . "에서 {$entity->getServiceInfoUid()}에 대한 서비스정보를 찾을수 없습니다.");
                        }
                        $serviceEntities[$entity->getServiceInfoUid()] = $serviceEntity;
                    }
                    //Invoice Data 가져오기
                    $rows = $this->getService()->getInvoiceData($clientEntity, $serviceEntity, $entity, $rows);
                }
            }
            // dd($rows);
            $this->rows = $rows;
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }

    //일회성결제작업
    protected function create_form_process(): void
    {
        $formDatas = $this->getService()->getFormDatas();
        $formDatas['billing'] = PAYMENT['BILLING']['ONETIME'];
        $formDatas['billing_at'] = date("Y-m-d");
        $this->getService()->setFormDatas($formDatas);
        parent::create_form_process();
    }
}
