<?php

namespace App\Models;

use CodeIgniter\Model;
use App\Libraries\Log\Log;
use App\Trait\CommonTrait;

class CommonModel extends Model
{
    use CommonTrait;

    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    = [];

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

    protected $validationRules      = [];
    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    = [];

    final protected function create_process($entity)
    {
        if (!$this->save($entity)) {
            Log::add("error", __FUNCTION__ . "에서 호출:" . $this->getLastQuery());
            Log::add("error", implode("\n", $this->errors()));
            throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->errors(), true));
        }
        if ($this->useAutoIncrement === true) {
            $pk = $this->primaryKey;
            $entity->$pk = $this->insertID();
        }
        return $entity;
    }
    final protected function modify_process($entity)
    {
        if ($entity->hasChanged()) {
            if (!$this->save($entity)) {
                Log::add("error", __FUNCTION__ . "에서 호출:" . $this->getLastQuery());
                Log::add("error", implode("\n", $this->errors()));
                throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->errors(), true));
            }
        } else {
            throw new \Exception(__FUNCTION__ . " 오류 발생.\n 기존정보와 동일하여 수정되지 않았습니다.");
        }
        return $entity;
    }

    //Index관련
    public function setIndexWordFilter(string $word)
    {
    }
    public function setIndexDateFilterTrit($start, $end)
    {
        $this->where('created_at >=', $start);
        $this->where('created_at <=', $end);
    }
    public function setIndexOrderBy($field, $order = 'ASC')
    {
        $this->orderBy($field, $order);
    }
}
