<?php

namespace App;

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

class Option extends Model
{
    public $timestamps = false;

    protected $fillable = ['name', 'value'];

    protected $key_cache = 'mopie.option';

    public static function boot()
    {
        parent::boot();

        $flushCache = function (self $optionLine) {
            $optionLine->flushCache();
        };

        static::saved($flushCache);
    }

    public function setValueAttribute($value)
    {
        if ( is_array($value) ) {
            $this->attributes['value'] = serialize($value);
        }elseif ( is_serialized($value, false) ) {
            $this->attributes['value'] = serialize($value);
        }else{
            $this->attributes['value'] = $value;
        }
    }

    public function getValueAttribute($value)
    {
        if ( is_serialized($value) ) {
            return @unserialize($value);
        }

        return $value;
    }

    public function scopeGetSetting($query, string $name = '')
    {
        if (Cache::has($this->key_cache)) {
            return Cache::get($this->key_cache)->where('name', $name)->first()->value ?? '';
        }

        return $query->whereName($name)->first()->value ?? '';
    }

    public function scopeIsCache($query)
    {
        return $query->whereName('is_cache')->first()->value;
    }

    private function flushCache()
    {
        if (Cache::has($this->key_cache)) {
            Cache::forget($this->key_cache);
        }

        Cache::forever($this->key_cache, $this->all());
    }
}
