<?php

namespace App\Services\Customer;

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

class AccountService extends CustomerService
{
    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",
            "content"
        ];
    }
    public function getFormFilters(): array
    {
        return [
            "clientinfo_uid",
            "bank",
            "status",
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['status'];
    }
    //고객예치금처리
    private function setBalance(array $formDatas): ClientEntity
    {
        if (!array_key_exists('clientinfo_uid', $formDatas)) {
            throw new \Exception("고객정보가 필요합니다.");
        }
        $entity = $this->getClientService()->getEntity($formDatas['clientinfo_uid']);
        if (!$entity instanceof ClientEntity) {
            throw new \Exception("{$formDatas['clientinfo_uid']}에 대한 고객정보를 찾을수 없습니다.");
        }
        return $this->getClientService()->setAccount($formDatas['status'], $entity, intval($formDatas['amount']));
    }
    //결제관련 예치금 차감 처리용
    public function setPaymentPaid(PaymentEntity $paymentEntity): AccountEntity
    {
        $formDatas = [
            'clientinfo_uid' => $paymentEntity->getClientInfoUID(),
            'bank'           => null,
            'title'          => "[결제차감] {$paymentEntity->getTitle()}",
            'issue_at'       => date('Y-m-d H:i:s'),
            'amount'         => $paymentEntity->getAmount(),
            'status'         => STATUS['WITHDRAWAL'],
        ];
        $this->setBalance($formDatas);
        return parent::create($formDatas);
    }
    //기본 기능부분
    //생성
    public function create(array $formDatas): AccountEntity
    {
        $this->setBalance($formDatas);
        $entity = parent::create($formDatas);
        //Log처리
        $this->getMylogService()->create(['title' => "[{$entity->getTitle()}] 예치금 처리", 'status' => $entity->getStatus()]);
        return $entity;
    }
    //List 검색용
    public function index_condition_filterWord(string $word): void
    {
        $this->getModel()->orLike($this->getModel()->getTable() . '.alias', $word, 'both');
        parent::index_condition_filterWord($word);
    }
}
