<?php

namespace App\Models;

use App\Entities\ProductEntity;

class ProductModel extends BaseModel
{
    const STATUS_OUTOFSTOCK = "outofstock";
    private $_category_options = null;
    protected $table = "tw_product";
    protected $useAutoIncrement = false;
    protected $returnType = ProductEntity::class;
    protected $useSoftDeletes   = true;
    public function __construct()
    {
        parent::__construct('Product');
        $this->allowedFields = [
            ...$this->allowedFields,
            "category_uid", "user_uid",
            'name', "photo", "cost", "price", "sale",
            "stock", "view_cnt",  "content", "status"
        ];
        $this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
    }
    public function getTitleField(): string
    {
        return 'name';
    }

    protected function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case "category_uid":
                $rules[$field] =  "required|numeric";
                break;
            case "user_uid":
                $rules[$field] = "required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]";
                break;
            case $this->getTitleField():
                $rules[$field] =  "required|trim|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},100]|max_dims[{$field},1024,768]";
                break;
            case 'cost':
            case 'price':
                $rules[$field] =  "required|numeric";
                break;
            case 'sale':
            case 'stock':
                $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 = array(), $options = array()): array
    {
        foreach ($this->getEntitys($conditions) as $entity) {
            // STATUS가 use가 아닐때 option을 disabled되게 하기위함
            if ($entity->getStatus() != DEFAULTS['STATUS']) {
                $options[$entity->getPrimaryKey() . "\" disabled=\"disabled"] = $entity->getTitle();
            } else {
                $options[$entity->getPrimaryKey()] = $entity->getTitle();
            }
        }
        return $options;
    }
    //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): ProductEntity
    {
        return parent::getEntity($conditions);
    }
    public function create(array $formDatas): ProductEntity
    {
        return $this->create_process(new ProductEntity(), $formDatas);
    }
    public function modify(ProductEntity $entity, array $formDatas): ProductEntity
    {
        return $this->modify_process($entity, $formDatas);
    }

    //Index관련
    public function setIndexWordFilter(string $word)
    {
        parent::setIndexWordFilter($word);
        $this->orLike($this->getTitleField(), $word, "both");
        $this->orLike("content", $word, "both"); //befor , after , both
    }

    //장바구니에 넣기
    final public function addCart(ProductEntity $entity, int $quantity): ProductEntity
    {
        if ($entity->getStock() == $quantity) {
            $entity->status = self::STATUS_OUTOFSTOCK;
        }
        $entity->stock -= $quantity;
        return $this->save_process($entity);
    }
    //장바구니에 빼기
    public function cancelCart(ProductEntity $entity, int $quantity)
    {
        if ($entity->getStatus() == self::STATUS_OUTOFSTOCK) {
            $entity->status = DEFAULTS['STATUS'];
        }
        $entity->stock += $quantity;
        return $this->save_process($entity);
    }
}
