<?php  
namespace WCQT\classes\com;

class Session
{
	var $cache;
	function __construct()
	{
		add_action( 'init', array( $this, 'setup_session' ));
		add_action( 'wp_loaded', array( $this, 'setup_session' ));
	}
	function add_product_to_quote_list($product_id, $variation_id = 0, $quantity = 1)
	{
		
		$existing = $this->get_data();
		if(isset($existing[$product_id."-". $variation_id]))
			$quantity += $existing[$product_id."-". $variation_id]['quantity'];
		$existing[$product_id."-". $variation_id] = array('product_id' => $product_id, 'variation_id' => $variation_id, 'quantity' => $quantity );
		
		$this->set_data($existing);
	}
	function get_quote_list()
	{
		global  $wcqt_product_model;
		$products_to_quote = $this->get_data();
		$products_that_ca_be_quoted = $wcqt_product_model->get_quotable_products_list();
		
		//validation
		$was_unset = false;
		if($products_that_ca_be_quoted != "always")
			foreach($products_to_quote as $key => $product_to_validate)
				if( in_array($product_to_validate['product_id'], $products_that_ca_be_quoted) || ($product_to_validate['variation_id'] != 0 && in_array($product_to_validate['variation_id'], $products_that_ca_be_quoted)))
					;
				else 
				{
					unset($products_to_quote[$key]);
					$was_unset = true;
				}
		if($was_unset)	
		{
			$this->set_data($products_to_quote);
		}			
		return $products_to_quote;
	}
	function delete_quote_list()
	{
		$this->set_data(array());
	}
	function update_quote_list($update)
	{
		if(!$update)
			return;
		
		$quote = $this->get_quote_list();
		foreach($update as $unique_id => $data)
			if(isset($quote[$unique_id]))
			{
				if($data['quantity'] > 0)
					$quote[$unique_id]['quantity'] = $data['quantity'];
				else
					unset($quote[$unique_id]);
			}
			
		$this->set_data($quote);
	}
	function remove_product_from_quote_list($unique_id)
	{
		if(!$unique_id)
			return;
		
		$quote = $this->get_quote_list();
		if(isset($quote[$unique_id]))
			unset($quote[$unique_id]);
	
		$this->set_data($quote);
	}
	private function get_data()
	{
		//Doesn't work with unlogged: return (array) WC()->session->get( 'wcqt_quotes' );
		
		//$this->setup_session();
		$data = isset( $_SESSION["wcqt_quotes"]) ? $_SESSION["wcqt_quotes"] : array();
		
		return $data;
	}
	private function set_data($quote)
	{
		//Doesn't work with unlogged: WC()->session->set( 'wcqt_quotes', $quote);
		//$this->setup_session();
		$_SESSION["wcqt_quotes"] = $quote;
	}
	public function setup_session()
	{
		if (!session_id() && !headers_sent()) 
			try 
			{
				@session_start();
			}catch (Exception $e) {}
	}
}
?>