<?php

namespace App\Services\Customer;

use App\Entities\Customer\ClientEntity;
use App\Models\Customer\ClientModel;

class ClientService extends CustomerService
{
    public function __construct()
    {
        parent::__construct(new ClientModel());
        $this->addClassName('Client');
    }
    public function getFormFields(): array
    {
        return [
            'fields' => [
                'site',
                'name',
                'email',
                'phone',
                'role',
            ],
            'filters' => [
                'site',
                'role',
                'status',
            ],
        ];
    }
    public function getIndexFields(): array
    {
        return [
            'fields' => [
                'site',
                'name',
                'email',
                'phone',
                'role',
                'account_balance',
                'coupon_balance',
                'point_balance',
                'status',
                'created_at',
                'updated_at',
            ],
            'filters' => [
                'site',
                'role',
                'status',
            ],
        ];
    }
    public function getBatchjobFields(): array
    {
        return ['site', 'role', 'status'];
    }
    //기본 기능부분

    //압금(쿠폰:추가)처리
    public function deposit(ClientEntity $entity, string $field, int $amount): ClientEntity
    {
        switch ($field) {
            case 'account_balance':
                if ($amount < 0) {
                    throw new \Exception("입금액이 0보다 작습니다.");
                }
                $amount += $entity->getAccountBalance();
                break;
            case 'coupon_balance':
                if ($amount < 0) {
                    throw new \Exception("쿠폰 추가갯수가 0보다 작습니다.");
                }
                $amount += $entity->getCouponBalance();
                break;
            case 'point_balance':
                if ($amount < 0) {
                    throw new \Exception("포인트 입금액 0보다 작습니다.");
                }
                $amount += $entity->getPointBalance();
                break;
            default:
                throw new \Exception("{$field}는 알수없는 Field가 정의되었습니다.");
        }
        $formDatas = [$field => $amount];
        // dd($formDatas);
        return $this->getClientService()->modify($entity, $formDatas);
    }
    //출금(쿠폰:사용)처리
    public function withdrawal(ClientEntity $entity, string $field, int $amount): ClientEntity
    {
        switch ($field) {
            case 'account_balance':
                if ($entity->getAccountBalance() < $amount) {
                    throw new \Exception("예치금[{$entity->getAccountBalance()}]이  출금액:{$amount}보다 부족합니다.");
                }
                $amount = $entity->getAccountBalance() - $amount;
                break;
            case 'coupon_balance':
                if ($entity->getCouponBalance() < $amount) {
                    throw new \Exception("쿠폰[{$entity->getCouponBalance()}]이  사용수:{$amount}보다 부족합니다.");
                }
                $amount = $entity->getCouponBalance() - $amount;
                break;
            case 'point_balance':
                if ($entity->getPointBalance() < $amount) {
                    throw new \Exception("포인트금액[{$entity->getPointBalance()}]이  출금액:{$amount}보다 부족합니다.");
                }
                $amount = $entity->getPointBalance() - $amount;
                break;
            default:
                throw new \Exception("{$field}는 알수없는 Field가 정의되었습니다.");
                // break;
        }
        $formDatas = [$field => $amount];
        return $this->getClientService()->modify($entity, $formDatas);
    }

    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);
    }

    //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);
    }
}
