<?php
	class Cookie {
		
		private $security;
		private $config;
		public $isSecure;
		
		function __construct() {
			global $config, $security;
			
			$this->config = $config;
			$this->isSecure = $this->config['settings']['encrypt-cookie'];
			$this->security = $security;
		}
		
		public function refreshCookie($key, $data=null, $expire=0, $path='/', $domain='', $secure=false, $httponly=false) {
			$saveData = (is_array($data) || is_object($data) || is_bool($data)) ? json_encode($data) : $data;
			
			if (isset($_COOKIE[$key])) unset($_COOKIE[$key]);
			
			if ($this->isSecure) {
				$saveData = $this->security->secureString($saveData, 'e');
			}
			
			return setcookie($key, $saveData, $expire, $path, $domain, $secure, $httponly);
		}
		
		public function readCookie($key=null) {
			
			if (isset($_COOKIE[$key])) {
				
				$cookieData = $_COOKIE[$key];
				
				if ($this->isSecure) {
					$cookieData = $this->security->secureString($cookieData, 'd');
				}
								
				if ($this->isJson($cookieData)) {
					return json_decode($cookieData, true);
				} else {
					return $cookieData;
				}
				
			}
			
			return false;
		}
		
		public function deleteCookie($key=null) {
			if (isset($_COOKIE[$key])) {
				unset($_COOKIE[$key]);
				setcookie($key, null, time()-3600, '/');
			}
			
			return !isset($_COOKIE[$key]);
		}
		
		private function isJson($string) {
			return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
		}
	}