<?php

namespace App\Controllers\Admin\Customer;

use App\Entities\Customer\PointEntity;
use App\Helpers\Customer\PointHelper;
use App\Services\Customer\PointService;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class PointController 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(): PointService
    {
        if (!$this->_service) {
            $this->_service = new PointService($this->request);
        }
        return $this->_service;
    }
    public function getHelper(): PointHelper
    {
        if (!$this->_helper) {
            $this->_helper = new PointHelper($this->request);
        }
        return $this->_helper;
    }
    //Index,FieldForm관련.

    protected function create_process(): PointEntity
    {
        //point_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, ['point_balance' => $clientEntity->getPointBalance() + $amount]);
        } else { // 출금
            if ($clientEntity->getPointBalance() < $amount) {
                throw new \Exception("포인트금액:{$clientEntity->getPointBalance()} < 사용금액:{$amount} 포인트사용이 불가합니다.");
            }
            $this->getClientService()->modify($clientEntity, ['point_balance' => $clientEntity->getPointBalance() - $amount]);
        }
        return parent::create_process();
    }
}
