<?php

namespace App\Models;
use App\Entities\UserEntity;
use CodeIgniter\Model;

class UserModel extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'user';
    protected $primaryKey       = 'uid';
    protected $useAutoIncrement = true;
    protected $insertID         = 0;
    protected $returnType       = 'array'; //object,array,entity명::class
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = ['id','passwd','name','email','role','status','updated_at','created_at'];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules      = [
        'uid'               => 'if_exist|numeric',
        'id'                => 'if_exist|min_length[4]|max_length[20]',
        'passwd'            => 'if_exist|trim|min_length[4]|max_length[150]',
        'confirmpassword'   => 'if_exist|trim|matches[passwd]',
        'name'              => 'if_exist|min_length[2]|max_length[20]',
        'email'             => 'if_exist|valid_email',
        'role'              => 'if_exist|in_list[member,manager,cloudflare,director,master]',
        'status'            => 'if_exist|in_list[use,unuse]',
        'updated_at'        => 'if_exist|valid_date',
        'created_at'        => 'if_exist|valid_date',
    ];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    public function getEntity(int $uid): null|UserEntity
    {
        $entity = $this->asObject(UserEntity::class)->where('uid',$uid)->first();
        if(is_null($entity)){ throw new \Exception(__METHOD__."에서 {$uid} 해당 정보가 없습니다."); }
        return $entity;;
    }

    public function setIndexWordFilter(string $word)
    {
        $this->orLike('id', $word, 'both');
        $this->orLike('name', $word, 'both'); //befor , after , both
    }
    public function setIndexDateFilter($start,$end)
    {
        $this->where('created_at >=', $start);
        $this->where('created_at <=', $end);
    }
}
