<?php

namespace App\Services\Customer;

use CodeIgniter\HTTP\IncomingRequest;

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

class ClientService extends CustomerService
{

    protected ?IncomingRequest $request = null;
    public function __construct(?IncomingRequest $request = null)
    {
        parent::__construct($request);
        $this->addClassName('Client');
    }
    public function getModelClass(): ClientModel
    {
        return new ClientModel();
    }
    public function getEntityClass(): ClientEntity
    {
        return new ClientEntity();
    }
    public function getFormFields(): array
    {
        return ['name', 'email', 'phone', 'role'];
    }
    public function getFilterFields(): array
    {
        return ['role', 'status'];
    }
    public function getBatchJobFields(): array
    {
        return ['status'];
    }
    public function getIndexFields(): array
    {
        return ['name', 'email', 'phone', 'role', 'account_balance', 'coupon_balance', 'point_balance', 'status'];
    }
    //압금(쿠폰:추가)처리
    public function deposit(ClientEntity $entity, string $field, int $amount): ClientEntity
    {
        if ($amount < 0) {
            throw new \Exception("입금액 , 쿠폰 추가갯수가 0보다 작습니다.");
        }
        return $this->getClientService()->modify($entity, [$field => $entity->getAccountBalance() + $amount]);
    }
    //출금(쿠폰:사용)처리
    public function withdrawal(ClientEntity $entity, string $field, int $amount): ClientEntity
    {
        if ($entity->getAccountBalance() < $amount) {
            throw new \Exception("잔여액,잔여 쿠폰갯수:{$entity->getAccountBalance()} < 출금액 , 사용쿠폰갯수: {$amount}보다 작습니다.");
        }
        return $this->getClientService()->modify($entity, [$field => $entity->getAccountBalance() - $amount]);
    }

    public function create(array $formDatas, mixed $entity = new ClientEntity()): ClientEntity
    {
        $formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']);
        return parent::create($formDatas, $entity ?? new ClientEntity());
    }
    public function modify(mixed $entity, array $formDatas): ClientEntity
    {
        // die(var_export($formDatas, true));
        //Role을 지정이 있을경우에만 , toggle이나 batcjhjob에서는 없을수도 있으므로
        if (isset($formDatas['role'])) {
            $formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']);
        }
        // die(var_export($formDatas, true));
        return parent::modify($entity, $formDatas);
    }
}
