<?php

namespace App\Models;

use App\Entities\DeviceEntity;

class DeviceModel extends BaseModel
{
    const STATUS_OUTOFSTOCK = "outofstock";
    const STATUS_SOLDOUT = "soldout";
    protected $table = "tw_device";
    protected $useAutoIncrement = false;
    protected $returnType = DeviceEntity::class;
    protected $useSoftDeletes   = true;
    public function __construct()
    {
        parent::__construct('Device');
        $this->allowedFields = [
            ...$this->allowedFields,
            'category', 'name', "cost", "price", "status"
        ];
        $this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
    }
    public function getTitleField(): string
    {
        return 'name';
    }

    public function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case $this->getTitleField():
                $rules[$field] =  "required|trim|string";
                break;
            case 'category':
                $rules[$field] =  "required|string";
                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 'cost':
            case 'price':
            case 'stock':
                $rules[$field] =  "required|numeric";
                break;
            case 'sale':
                $rules[$field] =  "if_exist|numeric";
                break;
            case "content":
                $rules[$field] =  "required|string";
                break;
            default:
                $rules = parent::getFieldRule($field, $rules, $action);
                break;
        }
        return $rules;
    }

    //Form 선택용 Options Data용
    public function getOptions(array $conditions = [], $options = []): array
    {
        //대분류 부분은 선택이 되지 않게 하기위해 따로 만듬 (form_dropdown의 optgroup 기능)
        foreach ($this->getEntitys($conditions) as $entity) {
            if (!array_key_exists($entity->getCategory(), $options)) {
                $options[$entity->getCategory()] = [];
            }
            $options[$entity->getCategory()][$entity->getPrimaryKey()] = $entity->getTitle();
        }
        return $options;
    }

    public function getEntity($conditions): DeviceEntity
    {
        return $this->where($conditions)->first() ?: throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 해당 데이터가 없습니다.");
    }
    public function getEntitys(array $conditions = array(), array $orderBys = array()): array
    {
        $orderBys = ["category ASC", "price DESC", ...$orderBys];
        return parent::getEntitys($conditions, $orderBys);
    }
    public function create(array $formDatas): DeviceEntity
    {
        return $this->create_process(new DeviceEntity(), $formDatas);
    }
    public function modify(DeviceEntity $entity, array $formDatas): DeviceEntity
    {
        return $this->modify_process($entity, $formDatas);
    }

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