<?php

namespace App\Models;

use App\Entities\LoggerEntity;

class LoggerModel extends CommonModel
{
    protected $table            = 'tw_logger';
    // protected $primaryKey       = 'uid';
    // protected $useAutoIncrement = true;
    protected $allowedFields    = ['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
    {
        $entity = $this->asObject(LoggerEntity::class)->where($field, $value)->first();
        if (is_null($entity)) {
            throw new \Exception("해당 데이터가 없습니다.\n {$field}->{$value}");
        }
        return $entity;
    }
    public function getEntity($uid): ?LoggerEntity
    {
        return $this->getEntityByField($this->primaryKey, $uid);
    }
    public function getFieldFormOptions(array $wheres = array(), $temps = array()): array
    {
        foreach ($this->asObject(LoggerEntity::class)->where($wheres)->findAll() as $entity) {
            $temps[$entity->getPrimaryKey()] = $entity->getTitle();
        }
        return $temps;
    }
    public function create(array $formDatas): LoggerEntity
    {
        $entity = new LoggerEntity($formDatas);
        //로그인 여부 확인후 필요한 데이터 저장
        if (session()->get(SESSION_NAMES['USER'])) {
            $userSessions = session()->get(SESSION_NAMES['USER']);
            $entity->user_uid = $userSessions[SESSION_USER_FIELDS['PK']];
        }
        return parent::create_process($entity);
    }
    public function modify(LoggerEntity $entity, array $formDatas): LoggerEntity
    {
        foreach ($formDatas as $field => $value) {
            if ($entity->$field != $formDatas[$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
    }
}
