<?php

namespace App\Services\Customer;

use App\Entities\Customer\AccountEntity;
use App\Helpers\Customer\AccountHelper;
use App\Models\Customer\AccountModel;

class AccountService extends CustomerService
{
    private ?ClientService $_clientService = null;
    public function __construct()
    {
        parent::__construct(new AccountModel(), new AccountHelper());
        $this->addClassName('Account');
    }
    public function getFormFields(): array
    {
        return [
            "clientinfo_uid",
            "bank",
            "title",
            "alias",
            "issue_at",
            "amount",
            "status",
        ];
    }
    public function getFormFilters(): array
    {
        return [
            "clientinfo_uid",
            "bank",
            "status",
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['status'];
    }
    final public function getClientService(): ClientService
    {
        if (!$this->_clientService) {
            $this->_clientService = new ClientService();
        }
        return $this->_clientService;
    }
    //기본 기능부분

    //고객예치금처리
    private function setBalance(array $formDatas): void
    {
        //account_balance 체크
        $entity = $this->getClientService()->getEntity($formDatas['clientinfo_uid']);
        if (!$entity) {
            throw new \Exception("{$formDatas['clientinfo_uid']}에 대한 고객정보를 찾을수 없습니다.");
        }
        $amount = intval($formDatas['amount']);
        if ($formDatas['status'] === AccountEntity::DEFAULT_STATUS) { //입금, 쿠폰추가
            $entity = $this->getClientService()->deposit($entity, 'account_balance',   $amount);
        } else { // 출금, 쿠폰사용
            $entity = $this->getClientService()->withdrawal($entity, 'account_balance',   $amount);
        }
    }
    //생성
    public function create(array $formDatas): AccountEntity
    {
        // 관리자 UID는 현재 인증된 사용자로 설정
        $formDatas['user_uid'] = $this->getMyAuth()->getUIDByAuthInfo();
        $this->setBalance($formDatas);
        return parent::create($formDatas);
    }
    //수정
    public function modify(mixed $entity, array $formDatas): AccountEntity
    {
        // 관리자 UID는 현재 인증된 사용자로 설정
        $formDatas['user_uid'] = $this->getMyAuth()->getUIDByAuthInfo();
        $this->setBalance($formDatas);
        return parent::modify($entity, $formDatas);
    }
    //List 검색용
    public function index_condition_filterWord(string $word): void
    {
        $this->getModel()->orLike($this->getModel()->getTable() . '.alias', $word, 'both');
        parent::index_condition_filterWord($word);
    }
}
