<?php
class Vars{
	public $site        = [];
	public $personal    = [];
	private $db         = null;
	private $sid        = 0;
	private $state      = 0; # default (0) | force-save (1)
	public function __construct($db, $sid){
		$this->db       = $db;
		$this->sid      = $sid;
        $this->Load();
		return true;
	}

    public function __destruct(){
        if ($this->state == 1){
            $this->Save();
        }
    }

    public function GetLocalKey($key){
        if ($key == "module_avatar")    return '<code>'.$key.'</code> [Модуль] [Смена аватара] Включен ли модуль';
        if ($key == "page_auth")        return '<code>'.$key.'</code> [HTML] Указывает на шаблон для страницы авторизации';
        
        return '<code>'.$key.'</code>';
    }

	public function Default(){
		$this->DefS("module_avatar", 0);
	}

	public function Load(){
		$data = $this->db->getObject("SELECT * FROM `vars` WHERE `sid` = '".$this->sid."' LIMIT 1");
		if ($data != NULL){
            $this->site = json_decode($data->site, true);
            $this->personal = json_decode($data->personal, true);
            if ($this->site == NULL || !is_array($this->site)) $this->site = [];
            if ($this->personal == NULL || !is_array($this->personal)) $this->personal = [];
        } else {
            $this->db->Query("INSERT INTO `vars`(`sid`) VALUES ('".$this->sid."');");
            $this->Save();
        }
        $this->Default();
	}

	public function Save(){
        $this->db->Query("UPDATE `vars` SET `site`='".json_encode($this->site)."' WHERE `sid` = '".$this->sid."' LIMIT 1");
        $this->db->Query("UPDATE `vars` SET `personal`='".json_encode($this->personal)."' WHERE `sid` = '".$this->sid."' LIMIT 1");
	}

    function GetS($key){
        return (isset($this->site[$key])?$this->site[$key]:NULL);
    }

    function GetP($key){
        return (isset($this->personal[$key])?$this->personal[$key]:NULL);
    }

    function SetS($key, $val){
        $this->site[$key] = $val;
    }

    function SetP($key, $val){
        $this->personal[$key] = $val;
    }

    function DefS($key, $val){
        if (!isset($this->site[$key])){
            $this->site[$key] = $val;
            $this->state = 1;
            return $val;
        }
        return $this->site[$key];
    }

    function DefP($key, $val){
        if (!isset($this->personal[$key])){
            $this->personal[$key] = $val;
            $this->state = 1;
            return $val;
        }
        return $this->personal[$key];
    }

    function DelS($key){
        if (isset($this->site[$key])){
            unset($this->site[$key]);
        }
    }

    function DelP($key){
        if (isset($this->personal[$key])){
            unset($this->personal[$key]);
        }
    }
}