<?php

namespace App\Models;

use App\Entities\LoggerEntity;

class LoggerModel extends CommonModel
{
    protected $table            = 'tw_logger';
    // protected $primaryKey       = 'uid';
    // protected $useAutoIncrement = true;
    protected $allowedFields    = ['tw_user_uid', 'title', 'content', 'status', 'updated_at'];
    protected $validationRules      = [
        'uid'               => 'if_exist|numeric',
        'user_uid'          => 'required|string',
        'title'             => 'required|string',
        'content'           => 'if_exist|string',
        'status'            => 'if_exist|string',
        'updated_at'        => 'if_exist|valid_date',
        'created_at'        => 'if_exist|valid_date',
    ];

    public function getEntityByField($field, $value): ?LoggerEntity
    {
        return $this->asObject(LoggerEntity::class)->where($field, $value)->first();
    }
    public function getEntity(int $uid): ?LoggerEntity
    {
        return $this->getEntityByField($this->primaryKey, $uid);
    }
    public function create(array $datas): LoggerEntity
    {
        $entity = new LoggerEntity($datas);
        $entity->user_uid = session()->get('uid');
        return parent::create_process($entity);
    }
    public function modify(LoggerEntity $entity, array $datas): LoggerEntity
    {
        foreach ($datas as $field => $value) {
            if ($entity->$field != $datas[$field]) {
                $entity->$field =  $value;
            }
        }
        return parent::modify_process($entity);
    }

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