<?php

namespace App\Models;

use App\Entities\SitepageEntity;

class SitepageModel extends BaseModel
{
    private $_category_options = null;
    protected $table = "tw_sitepage";
    protected $returnType = SitepageEntity::class;
    public function __construct()
    {
        parent::__construct('Sitepage');
        $this->allowedFields = [
            ...$this->allowedFields,
            "category_uid",
            "user_uid", 'title', "content",
            "status"
        ];
        $this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
    }
    public function getTitleField(): string
    {
        return 'title';
    }
    public function getContentField(): string
    {
        return 'content';
    }
    public function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case "category_uid":
                $rules[$field] =  "required|numeric";
                break;
            case $this->getTitleField():
            case "content":
                $rules[$field] =  "required|string";
                break;
            default:
                $rules = parent::getFieldRule($field, $rules, $action);
                break;
        }
        return $rules;
    }
    //Field별 Form Option용
    public function getFieldFormOption(string $field): array
    {
        switch ($field) {
            case 'category_uid':
                if (is_null($this->_category_options)) {
                    $categoryModel = new CategoryModel();
                    $this->_category_options = $categoryModel->getOptions();
                }
                $options = $this->_category_options;
                break;
            default:
                return 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): SitepageEntity
    {
        return $this->where($conditions)->first() ?: throw new \Exception("해당 데이터가 없습니다.\n" . var_export($conditions, true));
    }

    public function create(array $formDatas): SitepageEntity
    {
        return $this->create_process(new SitepageEntity(), $formDatas);
    }
    public function modify(SitepageEntity $entity, array $formDatas): SitepageEntity
    {
        return $this->modify_process($entity, $formDatas);
    }

    //Index관련
    public function setIndexWordFilter(string $word)
    {
        if ($word !== DEFAULTS['EMPTY']) {
            parent::setIndexWordFilter($word);
            $this->orLike($this->getTitleField(), $word, "both");
            $this->orLike("content", $word, "both"); //befor , after , both
        }
    }
}
