<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/api/Simpla.php';

class Preorder {
	
	public static $db;
	
	static function update(){ print_r($_SESSION);
		if(!isset($_SESSION['preorder_id']) || !$_SESSION['preorder_id']) self::start();  
		if(!isset($_SESSION['shopping_cart']) || !$_SESSION['shopping_cart']) return;
		self::setDb();
		
		$keys = array('name','email','phone','city','address','comment');
		foreach($keys as $key) $_POST[$key] = isset($_POST[$key]) ? mysql_real_escape_string($_POST[$key]) : '';
		
		$products = self::getProducts();
		
		self::$db->query("UPDATE __preorders SET products='$products',name='".$_POST['name']."',
																	email='".$_POST['email']."',
																	phone='".$_POST['phone']."',
																	city='".$_POST['city']."',
																	address='".$_POST['address']."',
																	comment='".$_POST['comment']."' WHERE `id`='".$_SESSION['preorder_id']."' ");
	}
	
	static function getProducts(){
		$x = $_SESSION['shopping_cart'];
		foreach($x as $k=>$v) unset($x[$k]['options']);
		
		return json_encode($x);
	}
	
	static function start(){ 
		if(isset($_SESSION['preorder_id']) && $_SESSION['preorder_id']) return;  
		if(!isset($_SESSION['shopping_cart']) || !$_SESSION['shopping_cart']) return; 
		
		self::setDb();
		//
		$products = self::getProducts();
		
		self::$db->query("INSERT INTO __preorders SET date=NOW(), products='$products',name='',email='',phone='',city='',address='',comment='' ");
		
		$_SESSION['preorder_id'] = self::$db->insert_id();
	}
	
	static function remove(){
		if(!isset($_SESSION['preorder_id']) || !$_SESSION['preorder_id']) return;
		self::setDb();
		self::$db->query("DELETE FROM __preorders WHERE `id`='".$_SESSION['preorder_id']."' ");
		unset($_SESSION['preorder_id']);
	}
	
	static function setDb(){
		if(self::$db) return;
		$simpla = new Simpla();
		self::$db = $simpla->db;
		self::$db->connect();
	}
}