<?php

namespace WoWPress\Database;

use Wenprise\Eloquent\Model;

class Cache extends Model{ 

    protected $table = "wowpress_cache";
    public $timestamps = false;
    protected $primaryKey = 'ID';
    protected $guarded = [ 'ID' ];


    public static function buildKey(array $key_parts){
        return md5(implode(";",$key_parts));
    }
    

    public function isExpired($expiration){
        return ((time() - $this->expiration) / 60) >= $expiration;
    }


    public function getValueAttribute(){
        $value =  base64_decode($this->p_value);
        $value = preg_replace('/[[:cntrl:]]/', '', $value);
        $value = json_decode($value,true);
        return $value;
    }


    public static function upsert($p_key,$p_value){
        if(!\json_validate($p_value)){
            $p_value = json_encode($p_value);
        }
        $p_value = base64_encode($p_value);
        $c = new Cache();
        $c->p_key = $p_key;
        $c->p_value = $p_value;
        $c->expiration = time();
        $c->save();
        return $c;
    }

}