<?php

namespace App\Controllers\Admin\Customer;

use App\Entities\Customer\AccountEntity;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

use App\Helpers\Customer\AccountHelper;
use App\Services\Customer\AccountService;

class AccountController extends CustomerController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->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(): AccountService
    {
        if (!$this->_service) {
            $this->_service = new AccountService($this->request);
        }
        return $this->_service;
    }
    public function getHelper(): AccountHelper
    {
        if (!$this->_helper) {
            $this->_helper = new AccountHelper($this->request);
        }
        return $this->_helper;
    }
    //Index,FieldForm관련.

    protected function create_process(): AccountEntity
    {
        //account_balance 체크
        $clientEntity = $this->getClientService()->getEntity($this->formDatas['clientinfo_uid']);
        //입금
        $amount = intval($this->formDatas['amount']);
        if ($this->formDatas['status'] === DEFAULTS['STATUS']) {
            if ($amount < 0) {
                throw new \Exception("입금액이 0보다 작습니다.");
            }
            $this->getClientService()->modify($clientEntity, ['account_balance' => $clientEntity->getAccountBalance() + $amount]);
        } else { // 출금
            if ($clientEntity->getAccountBalance() < $amount) {
                throw new \Exception("예치금:{$clientEntity->getAccountBalance()} < 출금액:{$amount} 출금이 불가합니다.");
            }
            $this->getClientService()->modify($clientEntity, ['account_balance' => $clientEntity->getAccountBalance() - $amount]);
        }
        return parent::create_process();
    }
}
