<?php

namespace App\Models;

use App\Entities\BoardEntity;

class BoardModel extends BaseModel
{
    protected $table            = 'tw_board';
    // protected $primaryKey       = 'uid';
    // protected $useAutoIncrement = true;
    protected $allowedFields    = ['grpno', 'grporder', 'grpdepth', 'board_category',  'user_uid', 'title', 'content', 'passwd', 'view_cnt', 'status', 'updated_at'];
    protected $validationRules      = [
        'grpno'               => 'if_exist|numeric',
        'grporder'            => 'if_exist|numeric',
        'grpdepth'            => 'if_exist|numeric',
        'board_category'      => 'required|string',
        'user_uid'            => 'if_exist|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]',
        'title'               => 'required|string',
        'content'             => 'required|string',
        'passwd'              => 'if_exist|trim|string',
        'view_cnt'            => 'if_exist|numeric',
        'status'              => 'if_exist|string',
        'updated_at'          => 'if_exist|valid_date',
        'created_at'          => 'if_exist|valid_date',
    ];

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

    public function create(array $formDatas): BoardEntity
    {
        $entity = new BoardEntity($formDatas);
        //로그인 여부 확인후 필요한 데이터 저장
        if (session()->get(SESSION_NAMES['ISLOGIN'])) {
            $auth = session()->get(SESSION_NAMES['AUTH']);
            $entity->user_uid = $auth[AUTH_FIELDS['ID']];
        }
        foreach ($formDatas as $field => $value) {
            $entity->$field = $this->changeFormData($field, $value);
        }
        $entity = parent::create_process($entity);
        //계층형
        $entity = $this->setHierarchyCreate($entity);
        return $entity;
    }
    public function modify(BoardEntity $entity, array $formDatas): BoardEntity
    {
        foreach ($formDatas as $field => $value) {
            $entity->$field = $this->changeFormData($field, $value);
        }
        return parent::modify_process($entity);
    }
    public function reply(BoardEntity $entity, array $formDatas): BoardEntity
    {
        $replyEntity = new BoardEntity($formDatas);
        //로그인 여부 확인후 필요한 데이터 저장
        if (session()->get(SESSION_NAMES['ISLOGIN'])) {
            $auth = session()->get(SESSION_NAMES['AUTH']);
            $replyEntity->user_uid = $auth[AUTH_FIELDS['ID']];
        }
        $replyEntity->title = "RE:" . $entity->title;
        foreach ($formDatas as $field => $value) {
            $replyEntity->$field = $this->changeFormData($field, $value);
        }
        //계층형
        $replyEntity = $this->setHierarchyReply($entity, $replyEntity);
        // echo var_export($replyEntity, true);
        // exit;
        return $this->create_process($replyEntity);
    }

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