<?php

namespace App\Services\Customer;

use App\Entities\Customer\ClientEntity;
use App\Helpers\Customer\ClientHelper;
use App\Models\Customer\ClientModel;
use App\Services\Customer\ServiceService;
use App\Services\Equipment\ServerService;
use App\Services\PaymentService;

class ClientService extends CustomerService
{
    private ?ServiceService $_serviceService = null;
    private ?ServerService $_serverService = null;
    private ?PaymentService $_paymentService = null;
    public function __construct()
    {
        parent::__construct(new ClientModel(), new ClientHelper());
        $this->addClassName('Client');
    }
    public function getFormFields(): array
    {
        return [
            'site',
            'name',
            'email',
            'phone',
            'role',
        ];
    }
    public function getFormFilters(): array
    {
        return [
            'site',
            'role',
            'status',
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'site',
            'name',
            'email',
            'phone',
            'role',
            'account_balance',
            'coupon_balance',
            'point_balance',
            'status',
            'created_at',
            'updated_at',
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['site', 'role', 'status'];
    }
    final public function getServiceService(): ServiceService
    {
        if ($this->_serviceService === null) {
            $this->_serviceService = new ServiceService();
        }
        return $this->_serviceService;
    }
    public function getServerService(): ServerService
    {
        if (!$this->_serverService) {
            $this->_serverService = new ServerService();
        }
        return $this->_serverService;
    }
    final public function getPaymentService(): PaymentService
    {
        if (!$this->_paymentService) {
            $this->_paymentService = new PaymentService();
        }
        return $this->_paymentService;
    }
    //예치금처리
    final public function setAccount(string $action, ClientEntity $entity, int $amount): ClientEntity
    {
        switch ($action) {
            case STATUS['DEPOSIT']:
                if ($amount < 0) {
                    throw new \Exception("예치금이 0보다 작습니다.");
                }
                $amount += $entity->getAccountBalance();
                break;
            case STATUS['WITHDRAWAL']:
                if ($entity->getAccountBalance() < $amount) {
                    throw new \Exception("예치금액[{$entity->getAccountBalance()}]이  출금액:{$amount}보다 부족합니다.");
                }
                $amount = $entity->getAccountBalance() - $amount;
                break;
            default:
                throw new \Exception("{$action}는 지정되지 않은 작업입니다.");
                // break;
        }
        return parent::modify($entity,  ['account_balance' => $amount]);
    }
    //쿠폰처리
    final public function setCoupon(string $action, ClientEntity $entity, int $cnt): ClientEntity
    {
        switch ($action) {
            case STATUS['DEPOSIT']:
                if ($cnt < 0) {
                    throw new \Exception("쿠폰수가 0보다 작습니다.");
                }
                $cnt += $entity->getCouponBalance();
                break;
            case STATUS['WITHDRAWAL']:
                if ($entity->getCouponBalance() < $cnt) {
                    throw new \Exception("쿠폰수[{$entity->getCouponBalance()}]가 사용쿠폰:{$cnt}보다 부족합니다.");
                }
                $cnt = $entity->getCouponBalance() - $cnt;
                break;
            default:
                throw new \Exception("{$action}는 지정되지 않은 작업입니다.");
                // break;
        }
        return parent::modify($entity,  ['coupon_balance' => $cnt]);
    }
    //포인트처리
    final public function setPoint(string $action, ClientEntity $entity, int $amount): ClientEntity
    {
        switch ($action) {
            case STATUS['DEPOSIT']:
                if ($amount < 0) {
                    throw new \Exception("포인트가 0보다 작습니다.");
                }
                $amount += $entity->getPointBalance();
                break;
            case STATUS['WITHDRAWAL']:
                if ($entity->getPointBalance() < $amount) {
                    throw new \Exception("포인트금액[{$entity->getPointBalance()}]이  사용포인트:{$amount}보다 부족합니다.");
                }
                $amount = $entity->getPointBalance() - $amount;
                break;
            default:
                throw new \Exception("{$action}는 지정되지 않은 작업입니다.");
                // break;
        }
        return parent::modify($entity,  ['point_balance' => $amount]);
    }
    //기본 기능부분
    //생성
    public function create(array $formDatas): ClientEntity
    {
        $formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']);
        return parent::create($formDatas);
    }
    public function modify(mixed $entity, array $formDatas): ClientEntity
    {
        //Role을 지정이 있을경우에만 , toggle이나 batcjhjob에서는 없을수도 있으므로
        if (isset($formDatas['role'])) {
            $formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']);
        }
        return parent::modify($entity, $formDatas);
    }
    //비고(History)설정
    public function history(mixed $entity, array $formDatas): ClientEntity
    {
        return parent::modify($entity, $formDatas);
    }

    //List 검색용
    //FormFilter 조건절 처리
    public function index_condition_filterField(string $field, mixed $filter_value): void
    {
        switch ($field) {
            case 'role':
                $where = "FIND_IN_SET(" . $this->getModel()->escape($filter_value) . ", {$this->getModel()->getTable()}.{$field}) > 0";
                //FIND_IN_SET()은 MySQL 함수이므로 CodeIgniter가 이를 일반 컬럼명으로 착각하고 escape하게 되면 오류가 발생합니다. 따라서 ->where($sql, null, false)로 명시하여 escape를 꺼줘야 정상 작동
                $this->getModel()->where($where, null, false);
                break;
            default:
                parent::index_condition_filterField($field, $filter_value);
                break;
        }
    }
    //검색어조건절처리
    public function index_condition_filterWord(string $word): void
    {
        $this->getModel()->orLike($this->getModel()->getTable() . '.email', $word, 'both');
        parent::index_condition_filterWord($word);
    }
    //OrderBy 처리
    public function setOrderBy(mixed $field = null, mixed $value = null): void
    {
        $this->getModel()->orderBy("site ASC,name ASC");
        parent::setOrderBy($field, $value);
    }
}
