<?php

	class System {

		protected $db;
		protected $opts = array();

		protected function loadKeysAndValues($db){
			$this->opts = null;
			$this->opts = array();
			$search = $db->query("SELECT * FROM adm_settings");

			foreach ($search->fetchAll(PDO::FETCH_ASSOC) as $value) {

				if(array_key_exists($value['_key'], $this->opts)){
					if( is_array( $this->opts[ $value['_key'] ] ) ){
						array_push( $this->opts[ $value['_key'] ], $value['value'] );
					}else{
						$beforeValue = $this->opts[ $value['_key'] ];
						$this->opts[ $value['_key'] ] = array( $beforeValue, $value['value'] );
					}
				}else{
						$this->opts[ $value['_key'] ] = $value['value'];
				}
			}

		}

		function __construct(){
			global $db;
			if(isset($db)){
				$this->db = $db;
				$this->loadKeysAndValues($db);
			}else{
				die("Necessário uma conexão com o banco de dados");
			}
		}

		public function getOption($key){
			if(array_key_exists($key, $this->opts)){
				return $this->opts[$key];
			}else{
				return null;
			}
		}

		public function setOption($key, $value){
			$c = $this->db;
			$search = $c->query("SELECT * FROM adm_settings WHERE _key = ?", $key);
			if($search && $search->rowCount() > 0){
				$search = $search->fetch(PDO::FETCH_ASSOC);
				$execute = $c->query("UPDATE adm_settings SET _key = ?, value = ? WHERE id = ?", $key, $value, $search['id']);
			}else{
				$execute = $c->query("INSERT INTO adm_settings (_key, value) VALUES (?, ?)", $key, $value);
			}
			$this->loadKeysAndValues($c);
			return $execute ? true : false;
		}

		public function setOptions($key, $value){
			$c = $this->db;
			$execute = $c->query("INSERT INTO adm_settings (_key, value) VALUES (?, ?)", $key, $value);
			$this->loadKeysAndValues($c);
			return $execute ? true : false;
		}

	}
