<?php
/*
	DevSaver Web Framework
	Copyright (c) 2002-2018 DevSaver. 
	All rights reserved.
		web:  www.devsaver.com
		mail: support@devsaver.com
*/

if (!defined("STPBase")) {
	die("This file can't be accessed directly!");
}

define("STB_COOKIES_NAME" , "_core");
define("STB_COOKIES_EXPIRE" , "+2 years");
define("STB_COOKIES_TABLE" , "site_core_cookies");

/**
* description
*
* @library	
* @author	
* @since	
*/
class CCookies{
	
	function __construct(&$db) {
		$this->db = $db;

		//check if the cookie exists
		if (!$_COOKIE[STB_COOKIES_NAME]) {
			setcookie ( 
				STB_COOKIES_NAME , 
				uniqid(),
				strtotime(STB_COOKIES_EXPIRE),
				"/", 
				false
			);				
		} else {

			//update the expire time fo the cookie
			setcookie ( 
				STB_COOKIES_NAME , 
				$_COOKIE[STB_COOKIES_NAME],
				strtotime(STB_COOKIES_EXPIRE),
				"/", 
				false
			);				
		}		

		$this->cookie = $_COOKIE[STB_COOKIES_NAME];

		$this->load();

	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function getName() {
		return $this->cookie;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	private function load() {
		$info = $this->db->QFetchRowArray(
			"SELECT * FROM site_core_cookies WHERE cookie_parent LIKE '%s' AND (cookie_expire = 0 OR ( cookie_expire > 0 AND cookie_expire > %d))" ,
			array($this->cookie , time())
		);

		if (is_array($info)) {
			foreach ($info as $key => $val) {
				$this->data[$val["cookie_code"]] = unserialize($val["cookie_value"]);
			}			
		}		
	}

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function set($name , $val, $expire = 0 ) {

		if (is_numeric($expire)) {
		} else {
			$expire = strtotime($expire);
		}
		

		if ($this->data[$name]) {
			$this->db->QueryUpdate(
				STB_COOKIES_TABLE,
				array(
					"cookie_parent"	=> $this->cookie,
					"cookie_code"	=> $name,
					"cookie_value"	=> serialize($val),
					"cookie_expire" => $expire,
					"cookie_access" => time(),
				),
				$this->db->Statement("cookie_parent LIKE '%s' AND cookie_code LIKE '%s'" , array($this->cookie , $name ))
			);
		} else {
			$this->db->QueryInsert(
				STB_COOKIES_TABLE,
				array(
					"cookie_parent"	=> $this->cookie,
					"cookie_code"	=> $name,
					"cookie_value"	=> serialize($val),
					"cookie_expire" => $expire,
					"cookie_create"	=> time(),
					"cookie_access"	=> time(),
				)
			);
		}
		
		$this->data[$name] = $val;
	}
	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function get($name) {
		return $this->data[$name];
	}	

	/**
	* description
	*
	* @param
	*
	* @return
	*
	* @access
	*/
	function del($name) {
		$this->db->Query(
			"DELETE FROM " . STB_COOKIES_TABLE . " WHERE cookie_parent LIKE '%s' AND cookie_code LIKE '%s'",
			array($this->cookie , $name)
		);
	}
	
}
