<?php

namespace App\Controllers\Admin\Customer;

use App\Entities\Customer\ClientEntity;
use App\Entities\Customer\PaymentEntity;
use App\Entities\Customer\ServiceEntity;
use App\Helpers\Customer\PaymentHelper;

use App\Libraries\LogCollector;
use App\Services\Customer\ClientService;

use App\Services\Customer\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 getHelper(): PaymentHelper
    {
        if (!$this->_helper) {
            $this->_helper = new PaymentHelper();
        }
        return $this->_helper;
    }
    public function getClientService(): ClientService
    {
        if (!$this->_clientService) {
            $this->_clientService = new ClientService();
        }
        return $this->_clientService;
    }
    protected function getResultSuccess_process(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        switch ($this->getAction()) {
            case 'invoice':
                $this->control = $this->getControlDatas();
                $this->getHelper()->setViewDatas($this->getViewDatas());
                $actionTemplate = $this->request->getVar('ActionTemplate') ?? $actionTemplate ?? 'payment';
                if ($actionTemplate) {
                    $view_file = $this->view_path . $actionTemplate . DIRECTORY_SEPARATOR . $this->getAction();
                } else {
                    $view_file = $this->view_path . $this->getAction();
                }
                $result = view($view_file, ['viewDatas' => $this->getViewDatas()]);
                break;
            default:
                $result = parent::getResultSuccess_process($message, $actionTemplate);
                break;
        }
        return $result;
    }
    //Index,FieldForm관련
    //생성관련
    protected function create_process(array $formDatas): PaymentEntity
    {
        // 관리자 UID는 현재 인증된 사용자로 설정
        $formDatas['user_uid'] = $this->getMyAuth()->getUIDByAuthInfo();
        return parent::create_process($formDatas);
    }
    //수정관련
    protected function modify_process(mixed $entity, array $formDatas): PaymentEntity
    {
        // 관리자 UID는 현재 인증된 사용자로 설정
        $formDatas['user_uid'] = $this->getMyAuth()->getUIDByAuthInfo();
        return parent::modify_process($entity, $formDatas);
    }
    //Invoice 관련
    private function getOwnersForInvoice(ClientEntity $clientEntity): array
    {
        $temps = [
            'name' => $clientEntity->getName(),
            'total_amount' => 0,
            'services' => []
        ];
        return $temps;
    }
    private function invoice_process(): void
    {
        //변경할 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) {
                LogCollector::debug(__METHOD__ . "에서 {$uid}에 대한 결제정보를 찾을수 없습니다.");
            }
            //entities에 고객 설정
            $clientEntity = $this->getClientService()->getEntity($entity->getClientCode());
            if (!$clientEntity) {
                LogCollector::debug(__METHOD__ . "에서 {$entity->getClientCode()}에 대한 고객정보를 찾을수 없습니다.");
            }
            if (!array_key_exists($clientEntity->getPK(), $entities)) {
                $entities[$clientEntity->getPK()] = $this->getOwnersForInvoice($clientEntity);
            }
            //entities에 서비스 설정
            $serviceEntity = $this->getServiceService()->getEntity($entity->getServiceUid());
            if (!$serviceEntity) {
                LogCollector::debug(__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);
        $this->entities = $entities;
    }
    public function invoice(): RedirectResponse|string
    {
        try {
            //각 Field 초기화
            $this->setAction(__FUNCTION__);
            //각 Field 초기화
            $this->initAction($this->getService()->getFormFields());
            $this->invoice_process();
            return $this->getResultSuccess_process();
        } catch (\Exception $e) {
            return $this->getResultFail_process($e->getMessage());
        }
    }
}
