<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class BoardMeta extends Model
{
    protected $table = 'tb_board_meta';
    protected $primaryKey = 'board_id';

    public $keyType = 'int';
    public $incrementing = false;
    public $timestamps = false;

    public string $metaKey = 'key';
    public string $metaValue = 'value';
    public string $cachePrefix = 'board-meta-';

    public function __set($name, $value)
    {
        $this->{$name} = $value;
    }

    public function __get($name)
    {
        return ($this->{$name} ?? null);
    }

    /**
     * 게시판 설정 정보 조회
     */
    public function data($boardID = 0): BoardMeta|null
    {
        $res = $this->where($this->primaryKey, $boardID)->get();
        if ($res->count() > 0) {
            foreach ($res as $val) {
                $this->{$val[$this->metaKey]} = $val[$this->metaValue];
            }
            return $this;
        }
        return null;
    }

    /**
     * 캐시된 설정 값 조회
     */
    public function getAllMeta($boardID = 0): ?BoardMeta
    {
        $cacheName = ($this->cachePrefix . $boardID);
        if (!$ret = Cache::get($cacheName)) {
            $ret = $this->data($boardID);
            Cache::forever($cacheName, $ret);
        }
        return $ret;
    }

    /**
     * 저장
     */
    public function save($boardID = 0, $saveData = []): void
    {
        if ($saveData && is_array($saveData)) {
            foreach ($saveData as $column => $value) {
                $this->_metaUpdate($boardID, $column, $value);
            }
        }

        Cache::forget($this->cachePrefix . $boardID);
        $this->getAllMeta($boardID);
    }

    /**
     * 삭제
     */
    public function deleteMeta($boardID = 0): void
    {
        $this->where($this->primaryKey, $boardID)->delete();
        Cache::forget($this->cachePrefix . $boardID);
    }

    /**
     * 조회
     */
    public function item($column = '', $default = null): mixed
    {
        if (empty($column)) {
            return false;
        }

        $return = $default;
        if (property_exists($this, $column)) {
            $return = $this->{$column};
        }

        return $return;
    }

    /**
     * 등록/수정 처리
     */
    private function _metaUpdate($boardID = 0, $column = '', $value = null): mixed
    {
        if(!$boardID) {
            return false;
        }

        $column = trim($column);
        if (empty($column)) {
            return false;
        }

        $items = $this->data($boardID);
        if($items) {
            $oldValue = property_exists($items, $column) ? $items->{$column} : false;
        }else{
            $oldValue = false;
        }

        if (empty($value) && $value != 0) {
            $value = '';
        }

        if ($value === $oldValue) {
            return false;
        }

        if (false === $oldValue) {
            return $this->_addMeta($boardID, $column, $value); // 새로 추가
        }

        return $this->_updateMeta($boardID, $column, $value); // 수정
    }

    /**
     * 등록
     */
    private function _addMeta($boardID = 0, $column = '', $value = ''): mixed
    {
        if(!$boardID) {
            return false;
        }

        $column = trim($column);
        if (empty($column)) {
            return false;
        }

        $insertData = [
            $this->primaryKey => $boardID,
            $this->metaKey => $column,
            $this->metaValue => $value
        ];

        return $this->insert($insertData);
    }

    /**
     * 수정
     */
    private function _updateMeta($boardID = 0, $column = '', $value = ''): mixed
    {
        if(!$boardID) {
            return false;
        }

        $column = trim($column);
        if (empty($column)) {
            return false;
        }

        $updateData = [
            $this->metaValue => $value
        ];

        return $this->where($this->primaryKey, $boardID)->where($this->metaKey, $column)->update($updateData);
    }
}
