<?php

namespace App\Models;

use App\Entities\UserEntity;
use App\Models\CommonModel;

class UserModel extends CommonModel
{
    protected $table            = 'users';
    protected $primaryKey       = 'uid';
    protected $returnType       = UserEntity::class;
    protected $allowedFields = [
        "id",
        "passwd",
        "name",
        "email",
        "pohne",
        "mobild",
        "role",
        "status"
    ];
    public function __construct()
    {
        parent::__construct();
    }
    public function getTitleField(): string
    {
        return 'name';
    }
    public function getFieldRule(string $field, array $rules): array
    {
        switch ($field) {
            case "id":
                if ($this->getAction() == DB_ACTION["CREATE"]) {
                    $rules[$field] = "required|trim|min_length[4]|max_length[20]|is_unique[{$this->table}.{$field}]";
                } else {
                    $rules[$field] = "required|trim|min_length[4]|max_length[20]";
                }
                break;
            case $this->getTitleField():
                $rules[$field] = "required|trim|string";
                break;
            case "email":
                $rules[$field] = "if_exist|trim|valid_email";
                break;
            case "role":
                //아래 Rule은 입력시에는 되는데 수정시에는 않됨 이유를 ?
                // $rules[$field] =   "required|in_list[master,director,cloudflare,manager,gold,silver,brone,vip,user]";
                //아래 Rule은 checkbox를 사용시에는 required만 우선 써야 수정시 validate문제없음
                $rules[$field] = "if_exist|trim|string";
                break;
            case "passwd":
            default:
                $rules = parent::getFieldRule($field, $rules);
                break;
        }
        return $rules;
    }

    public function getEntityByPK(int $uid): null|UserEntity
    {
        $this->where($this->getPKField(), $uid);
        return $this->getEntity();
    }
    public function getEntityByID(string $id): null|UserEntity
    {
        $this->where('id', $id);
        return $this->getEntity();
    }

    //create용
    public function create(array $formDatas = []): UserEntity
    {
        return $this->create_process(new UserEntity(), $formDatas);
    }

    //modify용
    public function modify(UserEntity $entity, array $formDatas): UserEntity
    {
        return $this->modify_process($entity, $formDatas);
    }
}
