<?php

namespace App\Controllers\Admin\Customer;

use App\Entities\Customer\CouponEntity;
use App\Helpers\Customer\CouponHelper;
use App\Services\Customer\CouponService;

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

class CouponController 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(): CouponService
    {
        if (!$this->_service) {
            $this->_service = new CouponService($this->request);
        }
        return $this->_service;
    }
    public function getHelper(): CouponHelper
    {
        if (!$this->_helper) {
            $this->_helper = new CouponHelper($this->request);
        }
        return $this->_helper;
    }
    //Index,FieldForm관련.
    protected function create_process(): CouponEntity
    {
        //coupon_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, ['coupon_balance' => $clientEntity->getCouponBalance() + $amount]);
        } else { // 출금
            if ($clientEntity->getCouponBalance() < $amount) {
                throw new \Exception("쿠폰수:{$clientEntity->getCouponBalance()} < 사용수:{$amount} 쿠폰사용이 불가합니다.");
            }
            $this->getClientService()->modify($clientEntity, ['coupon_balance' => $clientEntity->getCouponBalance() - $amount]);
        }
        return parent::create_process();
    }
}
