<?php

namespace App\Controllers\Admin\Customer;

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

class PaymentController extends CustomerController
{
    private ?ClientService $_clientService = null;
    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;
    }
    public function getClientService(): ClientService
    {
        if (!$this->_clientService) {
            $this->_clientService = new ClientService();
        }
        return $this->_clientService;
    }
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        switch ($this->getService()->getAction()) {
            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관련
    //생성관련
    protected function create_process(array $formDatas): PaymentEntity
    {
        // 관리자 UID는 현재 인증된 사용자로 설정
        $formDatas['user_uid'] = $this->getService()->getMyAuth()->getUIDByAuthInfo();
        return parent::create_process($formDatas);
    }
    //수정관련
    protected function modify_process(mixed $entity, array $formDatas): PaymentEntity
    {
        // 관리자 UID는 현재 인증된 사용자로 설정
        $formDatas['user_uid'] = $this->getService()->getMyAuth()->getUIDByAuthInfo();
        return parent::modify_process($entity, $formDatas);
    }
    //Invoice 관련
    private function invoice_process(): array
    {
        //변경할 UIDS
        $uids = $this->request->getPost('batchjob_uids[]');
        if (!is_array($uids) || !count($uids)) {
            throw new \Exception("청구서에 적용될 리스트를 선택하셔야합니다.");
        }
        $entities = [];
        foreach ($uids as $uid) {
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception(__METHOD__ . "에서 {$uid}에 대한 결제정보를 찾을수 없습니다.");
            }
            //entities에 고객 설정
            $clientEntity = $this->getClientService()->getEntity($entity->getClientInfoUID());
            if (!$clientEntity instanceof ClientEntity) {
                throw new \Exception(__METHOD__ . "에서 {$entity->getClientInfoUID()}에 대한 고객정보를 찾을수 없습니다.");
            }
            if (!array_key_exists($clientEntity->getPK(), $entities)) {
                $entities[$clientEntity->getPK()] = [
                    'name' => $clientEntity->getName(),
                    'total_amount' => 0,
                    'services' => []
                ];
            }
            //entities에 서비스 설정
            $serviceEntity = $this->getServiceService()->getEntity($entity->getServiceUid());
            if (!$serviceEntity instanceof ServiceEntity) {
                throw new \Exception(__METHOD__ . "에서 {$entity->getServiceUid()}에 대한 서비스정보를 찾을수 없습니다.");
            }
            if (!array_key_exists($serviceEntity->getPK(), $entities[$clientEntity->getPK()]['services'])) {
                $entities[$clientEntity->getPK()]['services'][$serviceEntity->getPK()] = [
                    'code' => $serviceEntity->getTitle(),
                    'billing_at' => $serviceEntity->getBillingAt(),
                    'items' => []
                ];
            }
            //entities에 총 결제금액 설정
            $entities[$clientEntity->getPK()]['total_amount'] += $entity->getAmount();
        }
        // dd($entities);
        return $entities;
    }
    public function invoice(): RedirectResponse|string
    {
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->entities = $this->invoice_process();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
}
