<?php

class OrderHandler extends Handler{

	var $cart;
	var $order;
	var $salestax = 0.0925;		// 9.25 %
	var $flag = 0;

	function __construct($name='OrderHandler'){
		parent::__construct($name);
		$this->cart = $this->createCart();
		$this->order = $this->createOrder();
		$order->salestax = 0;
	}

	function openSection($request = array()) {
		global $Server;
		$action = $Server->getAction(2);
		$handler = $action->Handler;
		return $handler->openSection($request);
	}

	function getCart($request = array()) {
		return $this->cart;
	}

	function getShoppingStatus($request = array()) {
		$request['total'] = $this->cart->total;
		$request['qty'] = 0;
		foreach($this->cart->cartlineitems->data as $value) {
			$request['qty'] += $value->qty;
		}
		return $request;
	}

	function getOrder($request = array()) {
		$this->order->_error = '';
		$this->order->id = '';
		$this->order->customer->id = '';
		$this->order->orderlineitems->data = array();
		foreach($this->cart->cartlineitems->data as $index => $li) {
			$OrderLI = $this->order->orderlineitems->type;
			$OrderLI->product = $li->product;
			$OrderLI->qty = abs($li->qty);
			$OrderLI->price = $li->price;
			$this->order->orderlineitems->data[] = clone $OrderLI;
		}
		$this->order->product_price = $this->order->ship_price = $this->order->tax_price = 0;
		foreach($this->order->orderlineitems->data as $index => $li) {
			$this->order->product_price += (double)($li->price*$li->qty);
			/*if(!empty($this->order->shipcosttype->id)) {
				foreach($li->product->shipcosts->data as $idx => $cost) {
					if($cost->type == $this->order->shipcosttype->id && $this->order->_paytype==1) {
						$this->order->ship_price += (double)($cost->value*(int)$li->qty);
					}
				}
			}*/
		}
		
		$this->DB->initObject($this->order->customer->country);
		$this->DB->initObject($this->order->customer->state);
		$this->DB->initObject($this->order->customer);
		if($this->order->_paytype!=1) $this->order->customer->state->id = 0;
			else if($this->order->customer->country->id==42) $this->order->customer->state->id = 0;
		if($this->order->customer->bill_country->id!=250) $this->order->customer->bill_state->id = 0;
		/*if($this->order->customer->state->id == 5 && $this->order->customer->country->id == 250 && $this->order->_paytype==1) {
			$this->order->tax_price = (double)$this->order->product_price*(double)$this->salestax;
		}	else*/		 
		$this->order->tax_price = 0;
		$this->order->salestax = 0;
		$this->order->ship_price = 0;
		$this->order->shipcosttype->id = 0;
		$this->order->product_price = (double)round($this->order->product_price,2);
		$this->order->total = $this->order->product_price;
		$this->order->total_price = $this->order->product_price + $this->order->ship_price + $this->order->tax_price;
		$this->order->_continue = $this->cart->continue;
		return $this->order;
	}

	function updateOrder($request = array()) {
		if(!empty($request['id'])) {
			$this->order = $this->createOrder();
			$this->order->id = $request['id'];
			$this->DB->initObject($this->order);
			$this->order->status = 1;
			$this->order->customer->cc_type = 0;
			$this->order->customer->cc_card = 0;
			$this->order->customer->cc_code = 0;
			$this->order->customer->cc_month = 0;
			$this->order->customer->cc_year = 0;
			$this->DB->processObject($this->order);
			$this->DB->processObject($this->order->customer);
			$this->DB->commit();
		}
		return $request;
	}

	function saveOrder($request = array()) {
		$this->parseRequest($request,$this->order);
		$this->order->_error = '';
		return $this->order;
	}
	
	function getTaxShippingOrder($request = array()) {
		$state =  $this->DB->SelectAny("select id from state where trim(shortname) like '".$request['code']."' LIMIT 1");
		if (isset($state[0]['id']))
			$this->order->customer->state->id = $state[0]['id'];
		$this->DB->initObject($this->order->customer->state);
			
		//-------- add taxes			
		$location = $this->DB->SelectAny("SELECT tax FROM location l left join region r on l.ownerid = r.id WHERE trim(r.shortname) like '".$request['code']."' LIMIT 1 ");
		
		unset($request['code']);
		$this->parseRequest($request,$this->order);
		
		if (isset($location[0]['tax']))
				$this->order->salestax = $location[0]['tax'];
				else  $this->order->salestax = 0;
		if ($this->order->salestax > 0 )
				$this->order->tax_price = (double)$this->order->product_price*(double)$this->order->salestax/100;
			else $this->order->tax_price = 0;
		$this->order->product_price = (double)round($this->order->product_price,2);
		$this->order->total = $this->order->product_price;
		$this->order->total_price = $this->order->product_price + $this->order->ship_price + $this->order->tax_price;
		//------------------
		$this->order->_error = '';
		return $this->order;
	}
	
	function setPromocodeOrder($request = array()) {
		$this->cart->promocode = new Promo_Code();
		$this->cart->promocode->id = $request['id'];
		$this->DB->initObject($this->cart->promocode);
		
		$this->order->promocode = new Promo_Code();
		$this->order->promocode->id = $request['id'];
		$this->DB->initObject($this->order->promocode);
		$this->order->_error = '';
		
		return $this->order;
	}
	
	function getCountriesOrder($request = array()) {
		$state =  $this->DB->SelectAny("select id from state where trim(shortname) like '".$request['code']."' LIMIT 1");
		if (isset($state[0]['id']))
				$this->order->customer->state->id =$state[0]['id'];
		$this->order->_error = '';
		return $this->order;
	}
	//--------------------------------------
	function getLocationOrder($request = array()) {
		$region =  $this->DB->SelectAny("select id from region where id  = ".$request[0]['id']." LIMIT 1");
		if (isset( $region[0]['id']))
				$this->order->customer->region->id = $region[0]['id'];
		$location =  $this->DB->SelectAny("SELECT id, tax, name FROM location WHERE ownerid = ".$request[0]['id']." ORDER BY name ");
		if (isset($location[0]['tax']))
				$this->order->salestax = $location[0]['tax'];
				else  $this->order->salestax = 0;
				
		return $location;
	}
	function getTaxOrder($request = array()) {
		$tax =  $this->DB->SelectAny("SELECT tax FROM location WHERE id = ".$request[0]['idtax']);
		if (isset($tax[0]['tax']))
				$this->order->salestax = $tax[0]['tax'];
			else $this->order->salestax = 0;
				
		if ($this->order->salestax > 0 )
				$this->order->tax_price = (double)$this->order->product_price*(double)$this->order->salestax/100;
			else $this->order->tax_price = 0;
		$this->order->product_price = (double)round($this->order->product_price,2);
		$this->order->total = $this->order->product_price;
		$this->order->total_price = $this->order->product_price + $this->order->ship_price + $this->order->tax_price;
		return $this->order;
	}

	function editQty($request) {
		//------cart
		foreach($this->cart->cartlineitems->data as $index => $li) {
				if(!empty($request[0]['id']) && $request[0]['id']==$li->product->id) {
					if(!empty($request[0]['qty']) && validate(intval($request[0]['qty']))) {
						if(intval(abs($request[0]['qty'])) <= 999)
							$this->cart->cartlineitems->data[$index]->qty = intval(abs($request[0]['qty']));
						else $this->cart->cartlineitems->data[$index]->qty = 999;
					}
				}
		}
		$this->cart->total = 0;
		$this->cart->tax_price =0;
		foreach($this->cart->cartlineitems->data as $index => $li) {
			$this->cart->product_price += (double)($li->price*$li->qty);
			$this->cart->tax_price += (double)$li->price*(double)$this->order->salestax/100*$li->qty;;
			$this->cart->total += $li->price*$li->qty;
		}
		//------cart END	
		foreach($this->order->orderlineitems->data as $index => $li) {
				if(!empty($request[0]['id']) && $request[0]['id']==$li->product->id) {
					if(!empty($request[0]['qty']) && validate(intval($request[0]['qty']))) {
						if(intval(abs($request[0]['qty'])) <= 999)
							$this->order->orderlineitems->data[$index]->qty = intval(abs($request[0]['qty']));
						else $this->order->orderlineitems->data[$index]->qty = 999;
					}
				}
		}
		$this->order->product_price = 0; 
		$this->order->ship_price = 0;
		$this->order->total = 0;
		$this->order->tax_price =0;
		foreach($this->order->orderlineitems->data as $index => $li) {
			$this->order->product_price += (double)($li->price*$li->qty);
			$this->order->tax_price += (double)$li->price*(double)$this->order->salestax/100*$li->qty;;
			$this->order->total += $li->price*$li->qty;
			if(!empty($this->order->shipcosttype->id)) {
				foreach($li->product->shipcosts->data as $idx => $cost) {
					if($cost->type == $this->order->shipcosttype->id) {
						$this->order->ship_price += (double)($cost->{'value_zone'.$this->order->customer->state->zone}*(int)$li->qty);
					}
				}
			}
		}		
		$this->order->total_price = $this->order->product_price + $this->order->ship_price + $this->order->tax_price;
		return $this->order;
	}	

	function getShippingOrder($request) {
		if (isset($request[0]['idshipping'])) {
			$this->order->shipcosttype->id = $request[0]['idshipping'];
			$this->DB->initObject($this->order->shipcosttype);
		} else return $this->order;
			
		$this->order->product_price = $this->order->ship_price = 0;
		foreach($this->order->orderlineitems->data as $index => $li) {
			$this->order->product_price += (double)($li->price*$li->qty);
			if(!empty($this->order->shipcosttype->id)) {
				foreach($li->product->shipcosts->data as $idx => $cost) {
					if($cost->type == $this->order->shipcosttype->id) {
						$this->order->ship_price += (double)($cost->{'value_zone'.$this->order->customer->state->zone}*(int)$li->qty);
					}
				}
			}
		}
	$this->order->total = $this->order->product_price;
	$this->order->total_price = $this->order->product_price + $this->order->ship_price + $this->order->tax_price;
//printObject($this->order);exit;			
		return $this->order;
	}
	
	function delItemCartOrder($request) {//---!!!!!!!!!!!!!
		//----CART
		foreach($this->cart->cartlineitems->data as $index => $li) {
				if(!empty($request[0]['id']) && $request[0]['id']==$li->product->id){	unset($this->cart->cartlineitems->data[$index]); break;} 
		}
		$this->cart->total = 0;
		$this->cart->tax_price =0;
		foreach($this->cart->cartlineitems->data as $index => $li) {
			$this->cart->product_price += (double)($li->price*$li->qty);
			$this->cart->tax_price += (double)$li->price*(double)$this->order->salestax/100*$li->qty;;
			$this->cart->total += $li->price*$li->qty;
		}		
		//----cart END
		foreach($this->order->orderlineitems->data as $index => $li) {
				if(!empty($request[0]['id']) && $request[0]['id']==$li->product->id){	unset($this->order->orderlineitems->data[$index]); break;} 
		}
		
		$this->order->product_price = $this->order->ship_price = 0;
		$this->order->total = 0;
		$this->order->tax_price =0;
		foreach($this->order->orderlineitems->data as $index => $li) {
			$this->order->product_price += (double)($li->price*$li->qty);
			$this->order->tax_price += (double)$li->price*(double)$this->order->salestax/100*$li->qty;;
			$this->order->total += $li->price*$li->qty;
			if(!empty($this->order->shipcosttype->id)) {
				foreach($li->product->shipcosts->data as $idx => $cost) {
					if($cost->type == $this->order->shipcosttype->id) {
						$this->order->ship_price += (double)($cost->{'value_zone'.$this->order->customer->state->zone}*(int)$li->qty);
					}
				}
			}
		}
		$this->order->total_price = $this->order->product_price + $this->order->ship_price + $this->order->tax_price;
		return $this->order;
	}
	
	function resetOrder($request = array()) {
		$this->order->_error = '';
		$this->order = $this->createOrder();
		return $this->order;
	}

	function getShipMethod($request = array()) {
		return $this->DB->SelectGuide('shipcosttype g');
	}

	function getPayType($request = array()) {
		return $this->DB->SelectGuide('paytype g');
	}

	function fillOrder($request = array('to_mail' => false)) {
//printObject($this->order);exit;	
		$this->order->customer->first_name =$request['cart-shipping-first-name'];
        $this->order->customer->last_name  =$request['cart-shipping-last-name'];
        $this->order->customer->address1  = $request['cart-shipping-street'];
        $this->order->customer->address2  = $request['cart-shipping-apt'];
        $this->order->customer->company  =  $request['cart-shipping-company'];
        $this->order->customer->city  = 	$request['cart-shipping-city'];
	    //$this->order->customer->region  = 	$request['cart-shipping-first-name'];
        $this->order->customer->zip  = 		$request['cart-shipping-zipcode'];		
//        $this->order->customer->region  = 	$request['cart-shipping-first-name'];
	    $this->order->customer->email  = 	$request['cart-shipping-email'];
        $this->order->customer->phone  = 	$request['cart-shipping-phone'];
        if (!empty($request['cart-billing-first-name'])) {
			$this->order->customer->bill_first_name = $request['cart-billing-first-name'];
	        $this->order->customer->bill_last_name  = $request['cart-billing-last-name'];
	        $this->order->customer->bill_address1  =  $request['cart-billing-street'];
	        $this->order->customer->bill_address2  =  $request['cart-billing-apt'];
	        $this->order->customer->bill_city  = 	  $request['cart-billing-city'];
	        //$this->order->customer->bill_state  =     $request['cart-shipping-first-name'];
		    $this->order->customer->bill_zip  =       $request['cart-billing-zipcode'];
	 	    $this->order->customer->bill_phone  =     $request['cart-billing-phone'];
	 	    $this->order->customer->bill_company  =   $request['cart-billing-company'];
        } else {
			$this->order->customer->bill_first_name = $this->order->customer->first_name;
	        $this->order->customer->bill_last_name  = $this->order->customer->last_name;
	        $this->order->customer->bill_address1  =  $this->order->customer->address1;
	        $this->order->customer->bill_address2  =  $this->order->customer->address2;
	        $this->order->customer->bill_city  = 	  $this->order->customer->city;
		    $this->order->customer->bill_zip  =       $this->order->customer->zip;
	 	    $this->order->customer->bill_phone  =     $this->order->customer->phone;
	 	    $this->order->customer->bill_company  =   $this->order->customer->company;
        	
        }
        $cc =  $this->DB->SelectAny("select id from paytype where code like '".$request['cart-cur-cardtype']."' ");
        $this->order->customer->cc_type  = (isset($cc[0]['id']))?$cc[0]['id']:0;
	    $this->order->customer->cc_card  = $request['cart-creditnumber'];
        $this->order->customer->cc_code  = $request['cart-securety-code'];
        $this->order->customer->cc_month  =$request['cart-cur-month'];
        $this->order->customer->cc_year  = $request['cart-cur-years'];
		$this->order->_error = '';
		//$this->parseRequest($request,$this->order);
		//$this->order = $this->getOrder();
		$this->order->continue = $this->cart->continue;
		if(!empty($this->order->product_price)) {
			//$this->DB->initObject($this->order->customer->country);
			//$this->DB->initObject($this->order->customer->bill_country);
			//$this->DB->initObject($this->order->customer->state);
			//$this->DB->initObject($this->order->customer->bill_state);
			//$this->DB->initObject($this->order->shipcosttype);
			$this->DB->initObject($this->order->customer->cc_type);
			$this->order->customer->_error = '';
			$this->DB->processObject($this->order->customer);
			if(!empty($this->order->customer->_error)) {
				$this->order->_error = $this->order->customer->_error;
				return $this->order;
			}
			$this->order->status = 0;
			$this->order->date = 'now';
			$this->DB->processObject($this->order);
			if(!empty($this->order->_error)) return $this->order;
			$this->DB->commit();
		}	
		return $this->order;
	}

	function addToCart($request = array('cartlineitems' => array()),$ROOT = true) {
		!empty($request['cartlineitems']) or $request['cartlineitems'] = array();
		foreach($request['cartlineitems'] as $key => $value) {
			$found = 0;
			foreach($this->cart->cartlineitems->data as $index => $li) {
				if($value==$li->product->id) {
					$found = 1;
					if($this->cart->cartlineitems->data[$index]->qty < 999)
						$this->cart->cartlineitems->data[$index]->qty++;
				}
			}
			if(!$found) {
				$this->cart->continue = getenv('HTTP_REFERER');
				$product = new Product();
				$product->prices = new ObjectsList();
				$product->prices->type = new Price();
				$product->shipcosts = new ObjectsList();
				$product->shipcosts->type = new ShipCost();
				$product->files = new ObjectsList();
				$product->files->type = new ProductFile();
				
				$product->relatedlineitems = new ObjectsList();
				$product->relatedlineitems->type = new RelatedLineItem();
				$product->relatedlineitems->type->lineitem = new Product();
				$product->relatedlineitems->type->lineitem->prices = new ObjectsList();
				$product->relatedlineitems->type->lineitem->prices->type = new Price();
				
				$product->id = (int)$value;
				$this->DB->initObject($product);
//			printObject($product); exit;
				if($product->is_active) {
					$sale = 0;
					$real_price = 0;
					foreach($product->prices->data as $idx => $price) {
						if(empty($price->value) || !is_numeric($price->value) || (double)$price->value < 0.01 || (count($product->prices->data) > 1 && $price->current==0)) $sale = 0;
						else {
							$real_price = $price->value;
							$sale = 1;
							break;
						}
					}
					if($sale) {
						$LI = clone $this->cart->cartlineitems->type;
						$LI->product = clone $product;
						$LI->qty = 1;
						$LI->price = $real_price;
						$this->cart->cartlineitems->data[] = clone $LI;
					}
				}
			}
		}
		if(!empty($request['cartlineitems'])) {
			$this->cart->total = 0;
			foreach($this->cart->cartlineitems->data as $index => $li) {
				$this->cart->total += $li->price*$li->qty;
			}
		}
		return $this->cart;//array();
	}

	function clearCart($request = array()) {
		$cart = $this->createCart();
		$cart->continue = $this->cart->continue;
		$this->cart = $cart;
		return $this->cart;//array();
	}

	function setOrder($request = array('cartlineitems' => array(),'_paytype' => 1)) {
		$this->order->_error = '';
		$this->cart = $this->refreshCart($request);
		$this->parseRequest($request,$this->order);
		return $this->order;
	}

	function refreshCart($request = array('cartlineitems' => array())) {
		!empty($request['cartlineitems']) or $request['cartlineitems'] = array();
		foreach($this->cart->cartlineitems->data as $index => $li) {
			$found = 0;
			foreach($request['cartlineitems'] as $key => $value) {
				if(!empty($value['id']) && $value['id']==$li->product->id) {
					$found = 1;
					if(!empty($value['qty']) && validate(intval($value['qty']))) {
						if(intval(abs($value['qty'])) <= 999)
							$this->cart->cartlineitems->data[$index]->qty = intval(abs($value['qty']));
						else $this->cart->cartlineitems->data[$index]->qty = 999;
					}
				}
			}
			if(empty($found)) unset($this->cart->cartlineitems->data[$index]);
		}
		$this->cart->total = 0;
		foreach($this->cart->cartlineitems->data as $index => $li) {
			$this->cart->total += $li->price*$li->qty;
		}
		return $this->cart;//array();
	}
	
	function getOrders($request) {
		//!empty($request['conditions']) or $request['conditions'] = array();
		$request['conditions']['o.customer'] = array('=' => 'c.id');
		$request['conditions']['oli.ownerid'] = array('=' => 'o.id');
		if(empty($request['fields'])) $request['fields']='distinct o.id, o._paytype, o.date, o.total_price, c.first_name, c.last_name, o.status';
		if(empty($request['sortColumn']) || $request['sortColumn']=='date') { $request['sortColumn']='o.date'; $request['sortType']='desc';}
		if(!empty($request['conditions']['customer'])) {
			$request['conditions']['c.id'] = array('='=>$request['conditions']['customer']);
			unset($request['conditions']['customer']);
		}
		if(!empty($request['conditions']['product'])) {
			$request['conditions']['oli.product'] = array('='=>$request['conditions']['product']);
			unset($request['conditions']['product']);
		}
		if(!empty($request['conditions']['begin_date'])) {
			$request['conditions']['date'] = array('>='=>$request['conditions']['begin_date']);
			unset($request['conditions']['begin_date']);
		}
		if(!empty($request['conditions']['end_date'])) {
			$request['conditions']['o.date'] = array('<='=>$request['conditions']['end_date']);
			unset($request['conditions']['end_date']);
		}
		//$rels = array();
		foreach($request['conditions'] as $k => $v) $rels[] = 'and';
		if(empty($request['curPageNumber'])) $request['curPageNumber']='1';
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty']='20';
		$selected = $this->DB->SelectArray(array('lorder o','customer c','orderlineitem oli'),'count(distinct o.id) as qty',$request['conditions'],0,0,0,array(),'CND_COMPLEX',$rels);
		$request['recordsTotal'] = $selected[0]['qty'];
		$request['pagesTotal'] = ceil($request['recordsTotal']/$request['pageRecordsQty']);
		$request['curPage'] = $this->DB->SelectArray(array('lorder o','customer c','orderlineitem oli'),$request['fields'],$request['conditions'],$this->getOrderBy($request),$this->getLimit($request),0,array(),'CND_COMPLEX',$rels);
		//if($request['sortColumn']=='o.total_price') {
			//uasort($request['curPage'],'by_price');
		//}
		return $request;
	}

	function openOrder($request = array()) {
		$this->order = $this->createOrder();
		$this->parseRequest($request,$this->order);
		$this->DB->initObject($this->order);
		$this->order->_error = '';
		return $this->order;
	}

	function createCart() {
		$cart = new Cart();
		$cart->cartlineitems = new ObjectsList();
		$cart->cartlineitems->type = new CartLineItem();
		$cart->cartlineitems->type->product = $this->createShoppingProduct();
		return $cart;
	}

	function createOrder() {
		$order = new LOrder();
		$order->customer = $this->createCustomer();
		$order->shipcosttype = new ShipCostType();
		$order->promocode = new Promo_Code();
		$order->orderlineitems = new ObjectsList();
		$order->orderlineitems->type = new OrderLineItem();
		$order->orderlineitems->type->product = $this->createShoppingProduct();
		return $order;
	}

	function createCustomer() {
		$customer = new Customer();
		$customer->state = new State();
		$customer->region = new Region();
		$customer->cc_type = new PayType();
		$customer->bill_state = new State();
		$customer->country = new Country();
		$customer->bill_country = new Country();
		return $customer;
	}

	function createShoppingProduct() {
		$product = new Product();
		$product->generation = new Generation();
		$product->prices = new ObjectsList();
		$product->prices->type = new Price();
		
		$product->relatedlineitems = new ObjectsList();
		$product->relatedlineitems->type = new RelatedLineItem();
		$product->relatedlineitems->type->lineitem = new Product();
		return $product;
	}
}
?>