<?php

namespace App\Models;

use App\Entities\CategoryEntity;

class CategoryModel extends BaseHierarchyModel
{
    protected $table = "tw_category";
    protected $useAutoIncrement = false;
    protected $returnType = CategoryEntity::class;
    public function __construct()
    {
        parent::__construct("Category");
        $this->allowedFields = [
            ...$this->allowedFields,
            "name", "linkurl", "photo", "isaccess", "isread", "iswrite", "isreply", "isupload", "isdownload",
            "head", "tail", "status"
        ];
        $this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
    }
    public function getTitleField(): string
    {
        return "name";
    }
    public function getContentField(): string
    {
        return "head";
    }
    public function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case $this->primaryKey:
                $rules[$field] =  "required|string";
                break;
            case $this->getTitleField():
                $rules[$field] = "required|trim|string";
                $rules[$field] .= $action == "insert" ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case "photo":
                $rules[$field] = !$action ? "if_exist|string" : "is_image[{$field}]|mime_in[{$field},image/jpg,image/jpeg,image/gif,image/png,image/webp]|max_size[{$field},300]|max_dims[{$field},2048,768]";
                break;
            case "isaccess":
            case "isread":
            case "iswrite":
            case "isreply":
            case "isupload":
            case "isdownload":
                //아래 Rule은 입력시에는 되는데 수정시에는 않됨 이유를 ?
                // $rules[$field] =   "required|in_list[master,director,cloudflare,manager,gold,silver,brone,vip,user,guest]";
                //아래 Rule은 checkbox를 사용시에는 required만 우선 써야 수정시 validate문제없음
                $rules[$field] = "required";
                break;
            default:
                $rules = parent::getFieldRule($field, $rules, $action);
                break;
        }
        return $rules;
    }
    //Form 선택용 Options Data용
    public function getOptions(array $conditions = [], $options = []): array
    {
        //대분류 부분은 선택이 되지 않게 하기위해 따로 만듬 (form_dropdown의 optgroup 기능)
        $old = "";
        foreach ($this->getEntitys($conditions) as $entity) {
            if ($entity->getHierarchy_Depth() == 1) {
                $old = $entity->getTitle();
                $options[$entity->getTitle()] = [];
            } else {
                $options[$old][$entity->getPrimaryKey()] = $entity->getTitle();
            }
        }
        return $options;
    }

    public function getMenus(array $conditions = []): array
    {
        $old = "";
        $menus = array();
        foreach ($this->getEntitys($conditions) as $entity) {
            if ($entity->getHierarchy_Depth() == 1) {
                $old = $entity->getPrimaryKey();
                $menus[$old] = ["entity" => $entity, "childs" => []];
            } else {
                $menus[$old]["childs"][] = $entity;
            }
        }
        return $menus;
    }

    //Field별 Form Option용
    protected function changeFormData(string $action, string $field, array $formDatas, $entity): CategoryEntity
    {
        switch ($field) {
            case "isaccess":
            case "isread":
            case "iswrite":
            case "isreply":
            case "isupload":
            case "isdownload":
                if (array_key_exists($field, $formDatas) && $formDatas[$field]) {
                    $entity->$field = is_array($formDatas[$field]) ? implode(DEFAULTS["DELIMITER_ROLE"], $formDatas[$field]) : $formDatas[$field];
                }
                break;
            case "head":
            case "tail":
                if (array_key_exists($field, $formDatas) && $formDatas[$field]) {
                    $entity->$field = htmlentities($formDatas[$field]);
                }
                break;
            default:
                $entity = new CategoryEntity(parent::changeFormData($action, $field, $formDatas, $entity)->toArray());
                break;
        }
        return $entity;
    }

    public function getEntity($conditions): CategoryEntity
    {
        return $this->where($conditions)->first() ?: throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 해당 데이터가 없습니다.");
    }
    public function create(array $formDatas): CategoryEntity
    {
        return $this->create_process(new CategoryEntity(), $formDatas);
    }
    public function modify(CategoryEntity $entity, array $formDatas): CategoryEntity
    {
        return $this->modify_process($entity, $formDatas);
    }
    public function reply($parent_entity, array $formDatas): CategoryEntity
    {
        return $this->reply_process($parent_entity, new CategoryEntity(), $formDatas);
    }

    //Index관련
    public function setIndexWordFilter(string $word): void
    {
        if ($word !== DEFAULTS['EMPTY']) {
            parent::setIndexWordFilter($word);
            $this->orLike("head", $word, "both");
            $this->orLike("tail", $word, "both");
        }
    }
    public function setIndexOrderBy(?string $field, ?string $order): void
    {
        //계단식의 경우는 먼저 다른것보다 먼저 orderBy가 수행되어야 하므로
        $this->orderBy("grpno", "DESC");
        $this->orderBy("grporder", "ASC");
        parent::setIndexOrderBy($field, $order);
    }
}
