<?php

/**
 * 
 * @author Peter Csubak (chuby)
 * @copyright Peter Csubak (chuby)
 * 
 * //Annotations:
 * @Stateful
 */
class CustomerSF {
	
	private $cart;
	
	public function login($passCode){
		$where = new Where("PassCode", "=", $passCode);
		$res = PersistenceHandler::getInstance()->selectEntities("Customer", $where);
		if (is_array($res) && count($res) == 1){
			SessionPeaHandler::getInstance()->setLoggedInUser($res[0]);
		}else{
			throw new Exception("Hibás felhasználóinév, vagy jelszó.");
		}
	}
	
	/**
	 * 
	 * @return multitype:
	 * 
	 * @GrantTo("customer")
	 */
	public function getMyOrdersList(){
		$cust = SessionPeaHandler::getInstance()->getLoggedInUser();
		if ($cust instanceof Customer){
			$where = new Where("CustomerId", "=", $cust->ID);
			return PersistenceHandler::getInstance()->selectEntities("Order", $where);
		}else{
			//Nah ez az ahova kb soha nem jutunk el, ha a SecureSession jól teszi a dolgát
			throw new Exception("Nincs bejelentkezve egyetlen felhasználó sem.");
		}
	}
	
	public function registrate($name, $address, $phone, $username, $passwd){
		$cust = new Customer();
		if (!$cust->hasTableCreated()){
			$cust->createTheTable();
		}
		$cust->name = $name;
		$cust->address = $address;
		$cust->phone = $phone;
		$cust->userName = $username;
		$cust->passCode = md5($username.$passwd);
		$cust->save();
	}
	
	public function addToCart($dvd){
		if (isset($this->cart)){
			foreach ($this->cart as $dvd2){
				if ($dvd->ID == $dvd2->ID){
					return;
				}
			}
			$this->cart[count($this->cart)] = $dvd;
		}else{
			$this->cart = array($dvd);
		}
	}
	
	public function makeOrder(){
		if (isset($this->cart)){
			$order = new Order();
			if (!$order->hasTableCreated()){
				$order->createTheTable();
			}
			$order->customerId = SessionPeaHandler::getInstance()->getLoggedInUser()->ID;
			$order->orderTime = date("Y-m-d H:i:s");
			$order->status = "before";
			$order->save();
			foreach ($this->cart as $dvd){
				$dvd->orderId = $order->ID;
				$dvd->save();
			}
			$this->cart = null;
		}else{
			throw new Exception("Üres a kosár.");
		}
	}
	
	public function getCart(){
		if (isset($this->cart)){
			return $this->cart;
		}else{
			return array();
		}
	}
	
	public function clearCart(){
		$this->cart = null;
	}
	
}
?>