<?php

namespace App\Models;

use App\Entities\BillingEntity;

class BillingModel extends BaseModel
{
    private $_order_options = null;
    protected $table = "tw_billing";
    protected $returnType = BillingEntity::class;
    public function __construct()
    {
        parent::__construct('Billing');
        $this->allowedFields = [
            ...$this->allowedFields,  "user_uid", "type", "email", "phone",
            "title", "price", "response", "status"
        ];
        $this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
    }
    final public function getTitleField(): string
    {
        return 'title';
    }
    public function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case "email":
                $rules[$field] =  "required|trim|valid_email";
                break;
            case "phone":
                $rules[$field] =  "if_exist|string";
                break;
            case $this->getTitleField():
                $rules[$field] =  "required|trim|string";
                break;
            case "response":
                $rules[$field] =  "if_exist|string";
                break;
            default:
                $rules = parent::getFieldRule($field, $rules, $action);
                break;
        }
        return $rules;
    }
    //Field별 Form Option용
    public function getFieldFormOption(string $field): array
    {
        switch ($field) {
            case 'order_uid':
                if (is_null($this->_order_options)) {
                    $orderModel = new OrderModel();
                    $this->_order_options = $orderModel->getOptions();
                }
                $options = $this->_order_options;
                break;
            default:
                $options = parent::getFieldFormOption($field);
                break;
        }
        if (!is_array($options)) {
            throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
        }
        return $options;
    }
    public function getEntity($conditions): BillingEntity
    {
        return $this->where($conditions)->first() ?: throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 해당 데이터가 없습니다.");
    }
    public function create(array $formDatas): BillingEntity
    {
        return $this->create_process(new BillingEntity(), $formDatas);
    }
    public function modify(BillingEntity $entity, array $formDatas): BillingEntity
    {
        return $this->modify_process($entity, $formDatas);
    }
}
