<?php

namespace App\Models;

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

class PostMeta extends Model
{
    protected $table = 'tb_post_meta';
    protected $primaryKey = 'post_id';

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

    public string $metaKey = 'key';
    public string $metaValue = 'value';
    public string $cachePrefix = 'post-meta-';
    public int $cacheTime = CACHE_EXPIRE_TIME;

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

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

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

    /**
     * 게시글 설정 값 조회
     */
    public function getAllMeta($postID = 0): ?PostMeta
    {
        $cacheName = ($this->cachePrefix . $postID);
        if (!$ret = Cache::get($cacheName)) {
            $ret = $this->data($postID);
            Cache::put($cacheName, $ret, $this->cacheTime);
        }
        return $ret;
    }

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

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

    /**
     * 조회
     */
    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($postID = 0, $column = '', $value = null): mixed
    {
        if(!$postID) {
            return false;
        }

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

        $items = $this->data($postID);
        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($postID, $column, $value); // 새로 추가
        }

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

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

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

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

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

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

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

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

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