<?php

namespace App\Models;

use App\Entities\UserEntity;

class UserModel extends CommonModel
{
    protected $table            = 'tw_user';
    // protected $primaryKey       = 'uid';
    protected $useAutoIncrement = false;
    protected $allowedFields    = ['uid', 'id', 'email', 'passwd', 'name',  'role', 'status', 'updated_at'];
    protected $validationRules      = [
        'uid'               => 'required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]',
        'id'                => 'required|min_length[4]|max_length[20]',
        'passwd'            => 'required|trim|min_length[4]|max_length[150]',
        'name'              => 'required|min_length[2]|max_length[20]',
        'email'             => 'required|valid_email',
        'role'              => 'required|string',
        'status'            => 'if_exist|string',
        'updated_at'        => 'if_exist|valid_date',
        'created_at'        => 'if_exist|valid_date',
    ];

    public function getEntityByField($field, $value): ?UserEntity
    {
        $entity = $this->asObject(UserEntity::class)->where($field, $value)->first();
        if (is_null($entity)) {
            throw new \Exception("해당 데이터가 없습니다.\n {$field}->{$value}");
        }
        return $entity;
    }
    public function getEntity($uid): ?UserEntity
    {
        return $this->getEntityByField($this->primaryKey, $uid);
    }
    public function getFieldFormOptions(array $wheres = array(), $temps = array()): array
    {
        foreach ($this->asObject(UserEntity::class)->where($wheres)->findAll() as $entity) {
            $temps[$entity->getPrimaryKey()] = $entity->getTitle();
        }
        return $temps;
    }
    public function create(array $formDatas): UserEntity
    {
        $entity = new UserEntity($formDatas);
        foreach ($formDatas as $field => $value) {
            $entity->$field = $field === 'passwd' ? password_hash($value, PASSWORD_DEFAULT) : $value;
        }
        return parent::create_process($entity);
    }
    public function modify(UserEntity $entity, array $formDatas): UserEntity
    {
        foreach ($formDatas as $field => $value) {
            if ($entity->$field != $formDatas[$field]) {
                $entity->$field = $field === 'passwd' ? password_hash($value, PASSWORD_DEFAULT) : $value;
            }
        }
        return parent::modify_process($entity);
    }

    //Index관련
    public function setIndexWordFilter(string $word)
    {
        parent::setIndexWordFilter($word);
        $this->orLike('id', $word, 'both');
        $this->orLike('name', $word, 'both'); //befor , after , both
    }
    public function setIndexOrderBy($field, $order = 'ASC')
    {
        $this->orderBy("name", "ASC");
        parent::setIndexOrderBy($field, $order);
    }
}
