<?php

class RIVERMEDIA extends Controller
{	
	public function __construct()
	{
		parent::__construct();
	}

	public function this_date() {
		date_default_timezone_set('Africa/Johannesburg');
		$dateTime = explode('T', date(DATE_ATOM));
		echo $dateTime[0];
	}

	public function this_time() {
		date_default_timezone_set('Africa/Johannesburg');
		$dateTime = explode('T', date(DATE_ATOM));
		$timeUnFormatted = explode('+', $dateTime[1]);
		$timeFormatted = explode(':', $timeUnFormatted[0]);
		echo $timeFormatted[0].':'.$timeFormatted[1];
	}
	
	public function create_timestamp() {
		date_default_timezone_set('Africa/Johannesburg');
		$dateTime = explode('T', date(DATE_ATOM));
		return $dateTime[0].' '.$dateTime[1];
	}

	public function create_session() {
		if (session_status() == PHP_SESSION_NONE) {
			session_start();
		};
	}
	
	public function create_guid() {
		function guid() {
			if (function_exists('com_create_guid')){
				return com_create_guid();
			}
			else {
				mt_srand((double)microtime()*10000);
				$charid = strtoupper(md5(uniqid(rand(), true)));
				$hyphen = chr(45);// "-"
				$uuid = chr(123)// "{"
						.substr($charid, 0, 8).$hyphen
						.substr($charid, 8, 4).$hyphen
						.substr($charid,12, 4).$hyphen
						.substr($charid,16, 4).$hyphen
						.substr($charid,20,12)
						.chr(125);// "}"
				return $uuid;
			}
		};
		$guid = guid();
		return $guid;
	}
	
	public function read_login_session() {
		$this->create_session();
		$sessionArray = "";
		if (isset($_SESSION['customerlogin_info'])) {
			$sessionArray = $_SESSION['customerlogin_info'];
			return $sessionArray;
		}
		else {
			unset($_SESSION['customerlogin_info']);	
		};
	}
	
	public function image_symlink() {
		$arrCwd = explode("/", getcwd());
		return '/'.$arrCwd[1].'/'.$arrCwd[2].'/admin.river-media/public/media/product_images/';
	}
	
	public function get_vat() {
		$query = $this->db->query("SELECT * FROM tbl_vat;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			return $r->vat_rate;
		};
	}
		
	public function sign_in() {
		$email = "";
		if (isset($_POST['email'])) {
			$email = $_POST['email'];
		};
		$password = "";
		if (isset($_POST['password'])) {
			$password = $_POST['password'];
		};
		if ($email !== "" & $password !== "") {
			$query = $this->db->query("SELECT * FROM tbl_customers WHERE email = '".$email."';");
			ini_set('session.gc_maxlifetime','3600');
			$this->create_session();
			if ($r = $query->fetch(PDO::FETCH_OBJ)) {
				if (md5($r->email."_".$password."_".$r->firstname."_".$r->lastname."_".$r->salt) === $r->md5encrypt) {
					$sessionarray = array($r->email,$r->firstname,$r->lastname,$r->md5encrypt,$r->ID);
					$_SESSION['customerlogin_info'] = $sessionarray;
					$_SESSION['customerloginstatus'] = "success";
					$ip = $_SERVER['HTTP_CLIENT_IP']?$_SERVER['HTTP_CLIENT_IP']:($_SERVER['HTTP_X_FORWARDE‌​D_FOR']?$_SERVER['HTTP_X_FORWARDED_FOR']:$_SERVER['REMOTE_ADDR']);
					$stmt = $this->db->prepare("INSERT INTO tbl_customer_logs (customer_id, ip_address) VALUES (:customer_id, :ip_address);");
					$stmt->execute(array(':customer_id' => $r->ID, ':ip_address' => $ip));
					if ($this->get_cart_session() !== "x") {
						$stmt = $this->db->prepare("UPDATE tbl_orders SET customer_id = :customer_id WHERE guid = :cart_session AND customer_id = '0';");
						$stmt->execute(array(':customer_id' => $sessionarray[4], ':cart_session' => $this->get_cart_session()));
					};
					$this->db->query("DELETE FROM tbl_orders WHERE created = ADDDATE(NOW(), INTERVAL -12 HOUR) AND order_state = 'CART'"); //Delete carts older than 12 hours
					echo 'Login successful';
				}
				else {
					$_SESSION['email'] = $email;
					unset($_SESSION['customerlogin_info']);
					$_SESSION['customerloginstatus'] = "fail";
					echo 'Login failed';
				};	
			}
			else {
				unset($_SESSION['customerlogin_info']);
				$_SESSION['customerloginstatus'] = "fail";
				echo 'Login failed';
			};
		}
		else {
			echo 'Login failed';	
		};
	}

	public function get_page_name() {
		$arrUrl = explode("/", $_SERVER['REQUEST_URI']);
		$pageName = array_pop($arrUrl);
		return $pageName;
	}

	public function auth() {
		$this->create_session();
		$sessionarray = "";
		if (isset($_SESSION['customerlogin_info']) && is_array($_SESSION['customerlogin_info'])) {
			$email = $_SESSION['customerlogin_info'][0];
			$query = $this->db->query("SELECT * FROM tbl_customers WHERE email = '".$email."';");
			if ($r = $query->fetch(PDO::FETCH_OBJ)) {
				if ($r->email == $_SESSION['customerlogin_info'][0] && $r->firstname == $_SESSION['customerlogin_info'][1] && $r->lastname == $_SESSION['customerlogin_info'][2] && $r->md5encrypt == $_SESSION['customerlogin_info'][3]) {
					$sessionarray = array($r->email,$r->firstname,$r->lastname,$r->md5encrypt,$r->ID);
				}
				else {
					unset($_SESSION['customerlogin_info']);
					session_unset();
					session_destroy();
					header('Location: index');
				};
			};
		}
		else {
			$pageName = $this->get_page_name();
			if ($pageName === 'pay' || $pageName === 'order_confirm' || $pageName === 'invoices' || $pageName === 'list_invoices') {
				header('Location: index');
			};
		};
	}
	
	public function get_login_session() {
		$this->create_session();
		$sessionArray = "";
		if (isset($_SESSION['customerlogin_info']) && is_array($_SESSION['customerlogin_info'])) {
			$sessionArray = $_SESSION['customerlogin_info'];
		};
		return $sessionArray;
	}
	
	public function sign_out() {
		$customerId = "x";
		$sessionArray = $this->get_login_session();
		if (is_array($sessionArray)) {
			$customerId = $sessionArray[4];
		};
		$this->db->query("DELETE FROM tbl_orders WHERE customer_id = '".$customerId."' AND order_state = 'CART';");
		unset($_SESSION['customerlogin_info']);
		unset($_SESSION['customerloginstatus']);
		unset($_SESSION['cart_session']);
		session_unset();
		session_destroy();
		header('Location: index');
	}
	
	public function get_origin_types() {
		$arrOriginTypes = array();
		$query = $this->db->query("SELECT origin_type FROM tbl_origin_types ORDER BY ID ASC;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$arrOriginTypes[] = $r->origin_type;
		};
		return $arrOriginTypes;
	}

	public function tabs_origin_types() {
		$arrUrl = explode("/", $_SERVER['REQUEST_URI']);
		$pageName = array_pop($arrUrl);
		$counter = 0;
		$class = '';
		$tabsOriginTypes = $this->get_origin_types();
		foreach ($tabsOriginTypes as $value) {
			if ($counter === 0) {
				$class = 'active';
			};
			echo '
            <li class="'.$class.'"><a href="#'.$value.'" data-toggle="tab" aria-expanded="false">'.$value.'s</a></li>';
			$class = '';
			$counter++;
		};
	}

	public function tabcontent_origin_types() {
		$counter = 0;
		$class = '';
		$tabsOriginTypes = $this->get_origin_types();
		foreach ($tabsOriginTypes as $value) {
			if ($counter === 0) {
				$class = ' active in';
			};
			echo '
			<div class="tab-pane fade'.$class.'" id="'.$value.'">
    			<p>
			';
			 $query = $this->db->query("SELECT DISTINCT media_origin, ID, url_segment FROM tbl_media_origin WHERE arr_tag_origin_type LIKE '%".$value."%' ORDER BY media_origin ASC;");
			 while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$queryInner = $this->db->query("SELECT COUNT(*) AS prod_count FROM tbl_products WHERE media_origin = '".$r->ID."';");
				while($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
					$prodCount = $rInner->prod_count;
				};
				if ($prodCount > 0) {
					echo '&nbsp;&nbsp;<a href="#" class="btn btn-default btn-xs" data-category-type="media_origin__'.$r->url_segment.'">'.$r->media_origin.' <span class="badge">'.$prodCount.'</span></a></a>&nbsp;&nbsp;';
				};
			 };
			echo '
				</p>
			</div>
			'; 
			$class = '';
			$counter++;
		};
	}
	
	public function category_dropdown() {
		$prodCount = 0;
		$query = $this->db->query("SELECT * FROM tbl_media_type ORDER BY media_type ASC;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$queryInner = $this->db->query("SELECT COUNT(*) AS prod_count FROM tbl_products WHERE media_type = '".$r->ID."';");
			while($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$prodCount = $rInner->prod_count;
			};
			echo '<li> <a href="javascript:void(0);" data-category-type="media_type__'.$r->url_segment.'">'.$r->media_type.' <span class="badge">'.$prodCount.'</span></a></li>';
		};
	}
	
	public function event_dropdown() {
		$query = $this->db->query("SELECT * FROM tbl_event ORDER BY event_year DESC, event_name ASC;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$queryInner = $this->db->query("SELECT COUNT(*) AS prod_count FROM tbl_products WHERE media_event = '".$r->ID."';");
			while($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$prodCount = $rInner->prod_count;
			};
			echo '<li> <a href="javascript:void(0);" data-category-type="event__'.$r->event_year.'_'.$r->url_segment.'">'.$r->event_year.' '.$r->event_name.' <span class="badge">'.$prodCount.'</span></a></li>';
		};
	}

	public function origin_dropdown() {
		$query = $this->db->query("SELECT * FROM tbl_media_origin ORDER BY media_origin ASC;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$queryInner = $this->db->query("SELECT COUNT(*) AS prod_count FROM tbl_products WHERE media_origin = '".$r->ID."';");
			while($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$prodCount = $rInner->prod_count;
			};
			if ($prodCount > 0) {
				echo '<li> <a href="javascript:void(0);" data-category-type="media_origin__'.$r->url_segment.'">'.$r->media_origin.' <span class="badge">'.$prodCount.'</span></a></li>';
			};
		};
	}

	public function cart_dropdown() {
		$customerId = "x";
		$this->create_session();
		if (isset($_SESSION['customerlogin_info']) && is_array($_SESSION['customerlogin_info'])) {
			echo '<li>&nbsp;<i class="fa fa-shopping-cart"></i> Open Carts </li>';
			$customerId = $_SESSION['customerlogin_info'][4];
			$queryText = "SELECT ID, created, guid 
						  FROM tbl_orders 
						  WHERE customer_id = '".$customerId."'
						  AND order_state = 'CART'
						  ORDER BY tbl_orders.created ASC;";
			$query = $this->db->query($queryText);
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$cartCount = 0;
				$innerQuery = $this->db->query("SELECT COUNT(*) AS cart_count FROM tbl_order_lines WHERE order_id = '".$r->ID."';");
				while ($rInner = $innerQuery->fetch(PDO::FETCH_OBJ)) {
					$cartCount = $rInner->cart_count;
				};
				echo '<li> <a href="javascript:void(0);"';
				if ($this->get_cart_session() === $r->guid) {
					echo ' class="current_cart"';
				};
				echo ' data-cart-session="'.$r->guid.'">'.$r->created.'&nbsp;<span class="dropdown_badge badge">'.$cartCount.'</span></a> </li>';
			};
			
		};
	}

	public function email_status() {
		$email = "";
		if (isset($_GET['email'])) {
			$email = $_GET['email'];
		};
		$counter = 0;
		$query = $this->db->query("SELECT COUNT(*) AS record_count FROM tbl_customers WHERE email = '".$email."';");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$counter = $r->record_count;
		};
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			echo ' <i class="fa fa-minus-circle deny" aria-hidden="true"></i> <span class="deny">Invalid email address structure</span>';
			die();
		};
		if ($counter > 0) {
			echo ' <i class="fa fa-minus-circle deny" aria-hidden="true"></i> <span class="deny">Email already registered</span>';
		}
		else {
			echo ' <i class="fa fa-check-circle accept" aria-hidden="true"></i> <span class="accept">Address available to register</span>';
		};
	}

	public function add_account() {
		$email = "";
		if (isset($_GET['email'])) {
			$email = trim($_GET['email']);
		};
		$password = "";
		if (isset($_GET['password'])) {
			$password = filter_var(trim($_GET['password']), FILTER_SANITIZE_STRING);
		};
		$title = "MR";
		if (isset($_GET['title'])) {
			$title = $_GET['title'];
		};
		$n1 = "";
		if (isset($_GET['n1'])) {
			$n1 = $_GET['n1'];
		};
		$n2 = "";
		if (isset($_GET['n2'])) {
			$n2 = filter_var(trim($_GET['n2']), FILTER_SANITIZE_STRING);
		};
		$phone = "";
		if (isset($_GET['phone'])) {
			$phone = filter_var(trim(str_replace(" ", "", $_GET['phone'])), FILTER_SANITIZE_STRING);
		};
		$dob = "1900-01-01";
		if (isset($_GET['dob'])) {
			$dob = filter_var(trim($_GET['dob']), FILTER_SANITIZE_STRING);
		};
		$guid = $this->create_guid();
		$md5encrypt = "";
		if ($email !== "" && $password !== "" && $title !== "" && $n1 !== "" && $n2 !== "" && $phone !== "" && $dob !== "") {
			$md5encrypt = md5($email."_".$password."_".$n1."_".$n2."_".$guid);
			$stmt = $this->db->prepare("INSERT INTO tbl_customers (title, firstname, lastname, md5encrypt, email, phone, DOB, salt) VALUES (:title, :firstname, :lastname, :md5encrypt, :email, :phone, :DOB, :salt);");
			$stmt->execute(array( ':title' => $title, ':firstname' => $n1, ':lastname' => $n2, ':md5encrypt' => $md5encrypt, ':email' => $email, ':phone' => $phone, ':DOB' => $dob, ':salt' => $guid));
			$query = $this->db->query("SELECT LAST_INSERT_ID() AS customer_id FROM tbl_customers;");
			while($r = $query->fetch(PDO::FETCH_OBJ)) {
				$customerId = $r->customer_id;
			};
			$stmt = $this->db->prepare("INSERT INTO tbl_delivery_address (customer_id) VALUES (:customer_id);");
			$stmt->execute(array(':customer_id' => $customerId));
		};
		echo '<div id="account_added" class="hidden">success</div>';
	}

	public function get_cart_session() {
		$this->create_session();
		$cartSession = "x";
		if (isset($_SESSION['cart_session']) && strlen($_SESSION['cart_session']) === 38) {
			$cartSession = $_SESSION['cart_session'];
		};
		return $cartSession;
	}

	public function get_order_id() {
		$cartSession = $this->get_cart_session();
		$orderId = "x";
		if ($cartSession !== "x") {
			$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".$cartSession."';");
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$orderId = $r->ID;
			};
		};
		return $orderId;
	}

	public function get_customer_order_number() {
		$orderId = $this->get_order_id();
		$customerOrderNumber = "";
		$query = $this->db->query("SELECT customer_order_number FROM tbl_orders WHERE ID = '".$orderId."';");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$customerOrderNumber = $r->customer_order_number;
		};
		return $customerOrderNumber;
	}
	
	public function list_by_latest() {
		$orderId = "x";
		$cartSession = "";
		$this->create_session();
		if (isset($_SESSION['cart_session']) && strlen($_SESSION['cart_session']) === 38) {
			$cartSession = $_SESSION['cart_session'];
		}
		else {
			$_SESSION['cart_session'] = "";
			unset($_SESSION['cart_session']);
			if (!(isset($_SESSION['customerlogin_info']) && is_array($_SESSION['customerlogin_info']))) {
				session_destroy();
			};
		};
		if ($cartSession !== "") {
			$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".$cartSession."';");
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$orderId = $r->ID; 
			};
		};
		$stringId = "";
		$price = 0.00;
		$vat = $this->get_vat();
		$origin = "";
		$query = $this->db->query("SELECT * FROM tbl_products ORDER BY ID DESC LIMIT 0,3;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$origin = "";
			$stringId = strtolower(str_replace("{", "", str_replace("}", "", $r->string_id)));
			$innerQuery = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $innerQuery->fetch(PDO::FETCH_OBJ)) {
				$price = $rInner->price_ex_vat;
				$price = str_replace(",", " ", number_format($price * ($vat / 100) + $price, 2));
			};
			$originQuery = $this->db->query("SELECT media_origin FROM tbl_media_origin WHERE ID = '".$r->media_origin."';");
			while ($rOrigin = $originQuery->fetch(PDO::FETCH_OBJ)) {
				$origin = $rOrigin->media_origin;
			};
			$mediaType = "";
			//Media type
			$mediaTypeQuery = $this->db->query("SELECT media_type FROM tbl_media_type WHERE ID = '".$r->media_type."';");
			while ($rMediaType = $mediaTypeQuery->fetch(PDO::FETCH_OBJ)) {
				$mediaType = $rMediaType->media_type;
			};
			$inCart = "N";
			$cartCount = 0;
			$cartQuantity = 0;
			$cartQueryText = "SELECT COUNT(*) as line_count,
							  quantity 
							  FROM tbl_order_lines  
						  	  WHERE product_id = '".$r->ID."' 
						      AND order_id = '".$orderId."';";
			$cartQuery = $this->db->query($cartQueryText);
			while ($rCart = $cartQuery->fetch(PDO::FETCH_OBJ)) {
				$cartCount = $rCart->line_count;
				$cartQuantity = $rCart->quantity;
			};
			$quantity = 0;
			$queryInner = $this->db->query("SELECT quantity FROM tbl_product_quantities WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$quantity = $rInner->quantity;
				if ($quantity < 0) {
					$quantity = 0;
				};
			};
			echo '
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 product_tiles" id="lprod_'.$r->ID.'">
			  <div class="panel panel-default">
				<div class="panel-heading">
				  <h5>'.$r->product_name.'</h5>
				  <div class="origins">'.$origin.'</div>
				</div>
				<div class="panel-body">
				<div class="img_box effect2">
				';
			if (file_exists($this->image_symlink().'/tn_'.$stringId.".jpg")) {
				echo '<img src="http://admin.river-media.co.za/public/media/product_images/tn_'.$stringId.'.jpg" alt="'.$r->product_name.'" style="width:100%;" />';
			}
			else {
				echo '<img src="public/media/img/missing_image.gif" alt="'.$r->product_name.'" style="width:100%;" />';	
			};
			echo  '
			       </div>
				   <div class="clearfix"></div>
			       <p>'.$mediaType.' <small style="font-size:10pt!important;"> ('.$r->tag_array_physical_medium.')</small></p>';
			echo  '<div class="referencefield">Ref: '.$r->reference.'</div>
			       <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 prod_quantity"><div>'.number_format($quantity).' items in stock</div></div>
				   <p class="display_price">R'.$price.'</p>
				  <br />
				  <div class="clearfix"></div>';
			echo  '<span class="cart_addupd">
				    <a href="javascript:void(0);" class="btn btn-default add_to_cart" data-toggle="popover" data-placement="top" data-content="Content"> <i class="fa fa-shopping-cart" aria-hidden="true"></i>';
			echo ' <span class="badge">'.$cartQuantity.'</span> ';
			echo ' <span>';
			if ($cartCount > 0) {
				echo ' CHANGE';
			}
			else {
				echo ' Add to Cart';
			};
			echo	'</span></a> 
				  </span>';
			if ($cartCount > 0) {
				echo '&nbsp;&nbsp;&nbsp;<span><a href="javascript:void(0);" class="remove_from_cart btn btn-default" id="lremove_'.$r->ID.'"> <i class="fa fa-remove" aria-hidden="true"></i> Remove</a></span>';
			};
			echo	  '<div class="clearfix"></div>
				  <div id="l_ajax_prod_cart_actions__'.$r->ID.'" class="hidden"></div>
				</div>
			  </div>
			</div>
			';
		};
	}

	public function top_selling_products() {
		$orderId = "x";
		$cartSession = "";
		$this->create_session();
		if (isset($_SESSION['cart_session']) && strlen($_SESSION['cart_session']) === 38) {
			$cartSession = $_SESSION['cart_session'];
		}
		else {
			$_SESSION['cart_session'] = "";
			unset($_SESSION['cart_session']);
			if (!(isset($_SESSION['customerlogin_info']) && is_array($_SESSION['customerlogin_info']))) {
				session_destroy();
			};
		};
		if ($cartSession !== "") {
			$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".$cartSession."';");
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$orderId = $r->ID; 
			};
		};
		$stringId = "";
		$price = 0.00;
		$vat = 0;
		$vat = $this->get_vat();
		$priceExVat = 0;
		$priceIncVat = 0;
		$stringId = '';
		$q = "SELECT tbl_order_lines.product_id AS product_id, 
		      SUM(tbl_order_lines.quantity) AS sum_quantity, 
			  tbl_products.product_name AS product_name, 
			  tbl_products.ID AS ID, 
			  tbl_products.media_type AS media_type, 
			  tbl_products.tag_array_physical_medium AS tag_array_physical_medium, 
			  tbl_products.reference AS reference, 
			  tbl_products.string_id AS string_id 
			  FROM tbl_order_lines, tbl_orders, tbl_products 
			  WHERE tbl_products.ID = tbl_order_lines.product_id 
			  AND tbl_order_lines.order_id = tbl_orders.ID 
			  AND tbl_orders.order_state = 'ORDER' 
			  GROUP BY tbl_order_lines.product_id 
			  ORDER BY SUM(tbl_order_lines.quantity) DESC LIMIT 0,6;
			  ";
		$query = $this->db->query($q);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$origin = "";
			$stringId = strtolower(str_replace("{", "", str_replace("}", "", $r->string_id)));
			$innerQuery = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $innerQuery->fetch(PDO::FETCH_OBJ)) {
				$price = $rInner->price_ex_vat;
				$price = str_replace(",", " ", number_format($price * ($vat / 100) + $price, 2));
			};
			$originQuery = $this->db->query("SELECT media_origin FROM tbl_media_origin WHERE ID = '".$r->media_origin."';");
			while ($rOrigin = $originQuery->fetch(PDO::FETCH_OBJ)) {
				$origin = $rOrigin->media_origin;
			};
			$mediaType = "";
			//Media type
			$mediaTypeQuery = $this->db->query("SELECT media_type FROM tbl_media_type WHERE ID = '".$r->media_type."';");
			while ($rMediaType = $mediaTypeQuery->fetch(PDO::FETCH_OBJ)) {
				$mediaType = $rMediaType->media_type;
			};
			$inCart = "N";
			$cartCount = 0;
			$cartQuantity = 0;
			$cartQueryText = "SELECT COUNT(*) as line_count,
							  quantity 
							  FROM tbl_order_lines  
						  	  WHERE product_id = '".$r->ID."' 
						      AND order_id = '".$orderId."';";
			$cartQuery = $this->db->query($cartQueryText);
			while ($rCart = $cartQuery->fetch(PDO::FETCH_OBJ)) {
				$cartCount = $rCart->line_count;
				$cartQuantity = $rCart->quantity;
			};
			$quantity = 0;
			$queryInner = $this->db->query("SELECT quantity FROM tbl_product_quantities WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$quantity = $rInner->quantity;
				if ($quantity < 0) {
					$quantity = 0;
				};
			};
			echo '
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 product_tiles" id="tprod_'.$r->ID.'">
			  <div class="panel panel-default">
				<div class="panel-heading">
				  <h5>'.$r->product_name.'</h5>
				  <div class="origins">'.$origin.'</div>
				</div>
				<div class="panel-body">
				<div class="img_box effect2">
				';
			if (file_exists($this->image_symlink().'/tn_'.$stringId.".jpg")) {
				echo '<img src="http://admin.river-media.co.za/public/media/product_images/tn_'.$stringId.'.jpg" alt="'.$r->product_name.'" style="width:100%;" />';
			}
			else {
				echo '<img src="public/media/img/missing_image.gif" alt="'.$r->product_name.'" style="width:100%;" />';	
			};
			echo  '
			      <div class="clearfix"></div>
				  </div>
			      <p>'.$mediaType.' <small style="font-size:10pt!important;"> ('.$r->tag_array_physical_medium.')</small></p>';
			echo  '<div class="referencefield">Ref: '.$r->reference.'</div>
			       <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 prod_quantity"><div>'.number_format($quantity).' items in stock</div></div>
				   <p class="display_price">R'.$price.'</p>
				  <br />
				  <div class="clearfix"></div>';
			echo  '<span class="cart_addupd">
				    <a href="javascript:void(0);" class="btn btn-default add_to_cart" data-toggle="popover" data-placement="top" data-content="Content"> <i class="fa fa-shopping-cart" aria-hidden="true"></i>';
			echo ' <span class="badge">'.$cartQuantity.'</span> ';
			echo ' <span>';
			if ($cartCount > 0) {
				echo ' CHANGE';
			}
			else {
				echo ' Add to Cart';
			};
			echo	'</span></a> 
				  </span>';
			if ($cartCount > 0) {
				echo '&nbsp;&nbsp;&nbsp;<span><a href="javascript:void(0);" class="remove_from_cart btn btn-default" id="tremove_'.$r->ID.'"> <i class="fa fa-remove" aria-hidden="true"></i> Remove</a></span>';
			};
			echo	  '<div class="clearfix"></div>
				  <div id="t_ajax_prod_cart_actions__'.$r->ID.'" class="hidden"></div>
				</div>
			  </div>
			</div>
			';
		};
	}


	/*
	public function featured_product() {
		$orderId = "x";
		$cartSession = "";
		$this->create_session();
		if (isset($_SESSION['cart_session']) && strlen($_SESSION['cart_session']) === 38) {
			$cartSession = $_SESSION['cart_session'];
		}
		else {
			$_SESSION['cart_session'] = "";
			unset($_SESSION['cart_session']);
			if (!(isset($_SESSION['customerlogin_info']) && is_array($_SESSION['customerlogin_info']))) {
				session_destroy();
			};
		};
		if ($cartSession !== "") {
			$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".$cartSession."';");
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$orderId = $r->ID; 
			};
		};
		$stringId = "";
		$price = 0.00;
		$vat = 0;
		$vat = $this->get_vat();
		$priceExVat = 0;
		$priceIncVat = 0;
		$stringId = '';
		$q = "SELECT * FROM tbl_products WHERE featured = 'Y' LIMIT 0,1;";
		$query = $this->db->query($q);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$stringId = strtolower(str_replace("{", "", str_replace("}", "", $r->string_id)));
			$innerQuery = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $innerQuery->fetch(PDO::FETCH_OBJ)) {
				$price = $rInner->price_ex_vat;
				$price = str_replace(",", " ", number_format($price * ($vat / 100), 2));
			};
			$inCart = "N";
			$cartCount = 0;
			$cartQuantity = 0;
			$cartQueryText = "SELECT COUNT(*) as line_count,
							  quantity 
							  FROM tbl_order_lines  
						  	  WHERE product_id = '".$r->ID."' 
						      AND order_id = '".$orderId."';";
			$cartQuery = $this->db->query($cartQueryText);
			while ($rCart = $cartQuery->fetch(PDO::FETCH_OBJ)) {
				$cartCount = $rCart->line_count;
				$cartQuantity = $rCart->quantity;
			};
			$quantity = 0;
			$queryInner = $this->db->query("SELECT quantity FROM tbl_product_quantities WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$quantity = $rInner->quantity;
			};
			echo '
			<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 product_tiles" id="tprod_'.$r->ID.'">
			  <div class="panel panel-default">
				<div class="panel-heading">
				  <h5>'.$r->product_name.'</h5>
				</div>
				<div class="panel-body">';
			if (file_exists($this->image_symlink().'/tn_'.$stringId.".jpg")) {
				echo '<img src="http://admin.river-media.co.za/public/media/product_images/tn_'.$stringId.'.jpg" alt="'.$r->product_name.'" style="width:100%;" />';
			}
			else {
				echo '<img src="public/media/img/missing_image.gif" alt="'.$r->product_name.'" style="width:100%;" />';	
			};
			echo  '<p class="col-lg-6 col-md-6 col-sm-6 col-xs-12">R'.$price.'</p>
				  <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12 prod_quantity"><div>'.number_format($quantity).' available</div></div>
				  <div class="clearfix"></div>';
			echo  '<span class="cart_addupd">
				    <a href="javascript:void(0);" class="btn btn-default add_to_cart" data-toggle="popover" data-placement="top" data-content="Content"> <i class="fa fa-shopping-cart" aria-hidden="true"></i>';
			echo ' <span class="badge">'.$cartQuantity.'</span> ';
			echo ' <span>';
			if ($cartCount > 0) {
				echo ' CHANGE';
			}
			else {
				echo ' Add to Cart';
			};
			echo	'</span></a> 
				  </span>';
			if ($cartCount > 0) {
				echo '&nbsp;&nbsp;&nbsp;<span><a href="javascript:void(0);" class="remove_from_cart btn btn-default" id="tremove_'.$r->ID.'"> <i class="fa fa-remove" aria-hidden="true"></i> Remove</a></span>';
			};
			echo	  '<div class="clearfix"></div>
				  <div id="t_ajax_prod_cart_actions__'.$r->ID.'" class="hidden"></div>
				</div>
			  </div>
			</div>
			';
		};
	}
	*/
	
	public function get_category_name() {
		$categoryName = "";
		$categoryType = "";
		$resultsHeading = "";
		if (isset($_POST['categoryname'])) {
			$categoryName = filter_var($_POST['categoryname'], FILTER_SANITIZE_STRING);
		};
		if (isset($_POST['categorytype'])) {
			$categoryType = filter_var($_POST['categorytype'], FILTER_SANITIZE_STRING);
		};
		if ($categoryType === 'media_origin' || $categoryType === 'media_type') {
			$q = "SELECT DISTINCT ".$categoryType." AS category_name FROM tbl_".$categoryType." WHERE url_segment = '".$categoryName."';";
		};
		if ($categoryType === 'event') {
			$q = "SELECT CONCAT_WS(' ', event_year, event_name) AS category_name FROM tbl_event WHERE CONCAT_WS('_', event_year, url_segment) = '".$categoryName."';";
		};
		$query = $this->db->query($q);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$resultsHeading = $r->category_name;
		};
		return $resultsHeading;
	}
	
	public function search_by_category() {
		$referer = $_SERVER['HTTP_REFERER'];
		$categoryType = "";
		$categoryName = "";
		if (!empty($_POST)) {
			if (isset($_POST['categorytype'])) {
				$categoryType = filter_var($_POST['categorytype'], FILTER_SANITIZE_STRING);
				if ($categoryType !== 'media_origin' && $categoryType !== 'event' && $categoryType !== 'media_type') {
					header('Location: index');
				};
			};
			if (isset($_POST['categoryname'])) {
				$categoryName = filter_var($_POST['categoryname'], FILTER_SANITIZE_STRING);
			};
			$orderId = "x";
			$cartSession = "";
			$this->create_session();
			if (isset($_SESSION['cart_session']) && strlen($_SESSION['cart_session']) === 38) {
				$cartSession = $_SESSION['cart_session'];
			}
			else {
				$_SESSION['cart_session'] = "";
				unset($_SESSION['cart_session']);
				if (!(isset($_SESSION['customerlogin_info']) && is_array($_SESSION['customerlogin_info']))) {
					session_destroy();
				};
			};
			if ($cartSession !== "") {
				$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".$cartSession."';");
				while ($r = $query->fetch(PDO::FETCH_OBJ)) {
					$orderId = $r->ID; 
				};
			};
			$stringId = "";
			$origin = "";
			$price = 0.00;
			$vat = 0;
			$vat = $this->get_vat();
			$priceExVat = 0;
			$priceIncVat = 0;
			$stringId = '';
			if ($categoryType === "media_origin") {
				$q = "SELECT tbl_products.product_name AS product_name, 
					  tbl_products.ID AS ID, 
					  tbl_products.media_origin AS media_origin, 
					  tbl_products.media_type AS media_type, 
					  tbl_products.tag_array_physical_medium AS tag_array_physical_medium, 
					  tbl_products.reference AS reference, 
					  tbl_products.string_id AS string_id 
					  FROM tbl_products, tbl_media_origin 
					  WHERE tbl_media_origin.url_segment = '".$categoryName."' 
					  AND tbl_products.media_origin = tbl_media_origin.ID 
					  ORDER BY tbl_products.product_name ASC;"; 
			};
			if ($categoryType === "media_type") {
				$q = "SELECT tbl_products.product_name AS product_name, 
					  tbl_products.ID AS ID, 
					  tbl_products.media_origin AS media_origin, 
					  tbl_products.media_type AS media_type, 
					  tbl_products.tag_array_physical_medium AS tag_array_physical_medium, 
					  tbl_products.reference AS reference, 
					  tbl_products.string_id AS string_id 
					  FROM tbl_products, tbl_media_type 
					  WHERE tbl_media_type.url_segment = '".$categoryName."' 
					  AND tbl_products.media_type = tbl_media_type.ID 
					  ORDER BY tbl_products.product_name ASC;"; 
			};
			if ($categoryType === "event") {
				$q = "SELECT tbl_products.product_name AS product_name, 
					  tbl_products.ID AS ID, 
					  tbl_products.media_origin AS media_origin, 
					  tbl_products.media_type AS media_type, 
					  tbl_products.tag_array_physical_medium AS tag_array_physical_medium, 
					  tbl_products.reference AS reference, 
					  tbl_products.string_id AS string_id 
					  FROM tbl_products, tbl_event 
					  WHERE CONCAT_WS('_', tbl_event.event_year, tbl_event.url_segment) = '".$categoryName."' 
					  AND tbl_products.media_event = tbl_event.ID 
					  ORDER BY tbl_products.product_name ASC;"; 
			};	
			$query = $this->db->query($q);
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$origin = "";
				$stringId = strtolower(str_replace("{", "", str_replace("}", "", $r->string_id)));
				$innerQuery = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
				while ($rInner = $innerQuery->fetch(PDO::FETCH_OBJ)) {
					$price = $rInner->price_ex_vat;
					$price = str_replace(",", " ", number_format($price * ($vat / 100) + $price, 2));
				};
				$originQuery = $this->db->query("SELECT media_origin FROM tbl_media_origin WHERE ID = '".$r->media_origin."';");
				while ($rOrigin = $originQuery->fetch(PDO::FETCH_OBJ)) {
					$origin = $rOrigin->media_origin;
				};
				$mediaType = "";
				//Media type
				$mediaTypeQuery = $this->db->query("SELECT media_type FROM tbl_media_type WHERE ID = '".$r->media_type."';");
				while ($rMediaType = $mediaTypeQuery->fetch(PDO::FETCH_OBJ)) {
					$mediaType = $rMediaType->media_type;
				};
				$inCart = "N";
				$cartCount = 0;
				$cartQuantity = 0;
				$cartQueryText = "SELECT COUNT(*) as line_count,
								  quantity 
								  FROM tbl_order_lines  
								  WHERE product_id = '".$r->ID."' 
								  AND order_id = '".$orderId."';";
				$cartQuery = $this->db->query($cartQueryText);
				while ($rCart = $cartQuery->fetch(PDO::FETCH_OBJ)) {
					$cartCount = $rCart->line_count;
					$cartQuantity = $rCart->quantity;
				};
				$quantity = 0;
				$queryInner = $this->db->query("SELECT quantity FROM tbl_product_quantities WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
				while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
					$quantity = $rInner->quantity;
					if ($quantity < 0) {
						$quantity = 0;
					};
				};
				echo '
				<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 product_tiles" id="tprod_'.$r->ID.'">
				  <div class="panel panel-default">
					<div class="panel-heading">
					  <h5>'.$r->product_name.'</h5>
					  <div class="origins">'.$origin.'</div>
					</div>
					<div class="panel-body">
					<div class="img_box effect2">
					';
				if (file_exists($this->image_symlink().'/tn_'.$stringId.".jpg")) {
					echo '<img src="http://admin.river-media.co.za/public/media/product_images/tn_'.$stringId.'.jpg" alt="'.$r->product_name.'" style="width:100%;" />';
				}
				else {
					echo '<img src="public/media/img/missing_image.gif" alt="'.$r->product_name.'" style="width:100%;" />';	
				};
				echo  '
				      <div class="clearfix"></div>
				      </div>
				      <p>'.$mediaType.' <small style="font-size:10pt!important;"> ('.$r->tag_array_physical_medium.')</small></p>';
				echo  '<div class="referencefield">Ref: '.$r->reference.'</div>
				       <p class="display_price">R'.$price.'</p>
					  <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 prod_quantity"><div>'.number_format($quantity).' items in stock</div></div>
					  <div class="clearfix"></div>';
				echo  '<span class="cart_addupd">
						<a href="javascript:void(0);" class="btn btn-default add_to_cart" data-toggle="popover" data-placement="top" data-content="Content"> <i class="fa fa-shopping-cart" aria-hidden="true"></i>';
				echo ' <span class="badge">'.$cartQuantity.'</span> ';
				echo ' <span>';
				if ($cartCount > 0) {
					echo ' CHANGE';
				}
				else {
					echo ' Add to Cart';
				};
				echo	'</span></a> 
					  </span>';
				if ($cartCount > 0) {
					echo '&nbsp;&nbsp;&nbsp;<span><a href="javascript:void(0);" class="remove_from_cart btn btn-default" id="tremove_'.$r->ID.'"> <i class="fa fa-remove" aria-hidden="true"></i> Remove</a></span>';
				};
				echo	  '<div class="clearfix"></div>
					  <div id="t_ajax_prod_cart_actions__'.$r->ID.'" class="hidden"></div>
					</div>
				  </div>
				</div>
				';
			};
		}
		else {
			header('Location: '.$referer);
		};
	}
	
	public function search_count() {
		$counter = 0;
		$fieldName = "";
		$searchTerm = "";
		if (!empty($_POST)) {
			foreach($_POST as $key => $value) {
				$fieldName = explode('__', $key);
				if ($fieldName[0] === 'searchvalue') {
					$searchTerm = filter_var($value, FILTER_SANITIZE_STRING);
					$fieldName = "";
				};
			};
		};
		$q = "SELECT tbl_products.ID AS ID  
			  FROM tbl_products 
			  WHERE tbl_products.product_name LIKE '".$searchTerm."%' 
			  UNION DISTINCT
			  SELECT tbl_products.ID AS ID
			  FROM tbl_products, tbl_media_origin 
			  WHERE tbl_products.media_origin = tbl_media_origin.ID
			  AND tbl_media_origin.media_origin LIKE '".$searchTerm."%'
			  UNION DISTINCT 
			  SELECT tbl_products.ID AS ID 
			  FROM tbl_products, tbl_event 
			  WHERE tbl_products.media_event = tbl_event.ID
			  AND CONCAT_WS(' ', tbl_event.event_year, tbl_event.event_name) LIKE '%".$searchTerm."%'
			  ";
		$query = $this->db->query($q);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$counter = $counter + 1;
		};
		echo $counter;
	}
	
	public function search_results() {
		$referer = $_SERVER['HTTP_REFERER'];
		$fieldName = "";
		$searchTerm = "";
		if (!empty($_POST)) {
			foreach($_POST as $key => $value) {
				$fieldName = explode('__', $key);
				if ($fieldName[0] === 'searchvalue') {
					$searchTerm = filter_var($value, FILTER_SANITIZE_STRING);
					$fieldName = "";
				};
			};
			$orderId = "x";
			$cartSession = "";
			$this->create_session();
			if (isset($_SESSION['cart_session']) && strlen($_SESSION['cart_session']) === 38) {
				$cartSession = $_SESSION['cart_session'];
			}
			else {
				$_SESSION['cart_session'] = "";
				unset($_SESSION['cart_session']);
				if (!(isset($_SESSION['customerlogin_info']) && is_array($_SESSION['customerlogin_info']))) {
					session_destroy();
				};
			};
			if ($cartSession !== "") {
				$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".$cartSession."';");
				while ($r = $query->fetch(PDO::FETCH_OBJ)) {
					$orderId = $r->ID; 
				};
			};
			$stringId = "";
			$price = 0.00;
			$vat = 0;
			$vat = $this->get_vat();
			$priceExVat = 0;
			$priceIncVat = 0;
			$stringId = '';
			$q = "SELECT tbl_products.product_name AS product_name, 
				  tbl_products.ID AS ID, 
				  tbl_products.media_origin AS media_origin, 
				  tbl_products.media_type AS media_type, 
				  tbl_products.tag_array_physical_medium AS tag_array_physical_medium, 
				  tbl_products.reference AS reference, 
				  tbl_products.string_id AS string_id 
				  FROM tbl_products 
				  WHERE tbl_products.product_name LIKE '".$searchTerm."%' 
				  UNION DISTINCT
				  SELECT tbl_products.product_name AS product_name, 
				  tbl_products.ID AS ID, 
				  tbl_products.media_origin AS media_origin, 
				  tbl_products.media_type AS media_type, 
				  tbl_products.tag_array_physical_medium AS tag_array_physical_medium, 
				  tbl_products.reference AS reference, 
				  tbl_products.string_id AS string_id 
				  FROM tbl_products, tbl_media_origin 
				  WHERE tbl_products.media_origin = tbl_media_origin.ID
				  AND tbl_media_origin.media_origin LIKE '".$searchTerm."%'
				  UNION DISTINCT 
				  SELECT tbl_products.product_name AS product_name, 
				  tbl_products.ID AS ID, 
				  tbl_products.media_origin AS media_origin, 
				  tbl_products.media_type AS media_type, 
				  tbl_products.tag_array_physical_medium AS tag_array_physical_medium, 
				  tbl_products.reference AS reference, 
				  tbl_products.string_id AS string_id 
				  FROM tbl_products, tbl_event 
				  WHERE tbl_products.media_event = tbl_event.ID
				  AND CONCAT_WS(' ', tbl_event.event_year, tbl_event.event_name) LIKE '%".$searchTerm."%'
				  ";
			$query = $this->db->query($q);
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$stringId = strtolower(str_replace("{", "", str_replace("}", "", $r->string_id)));
				$innerQuery = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
				while ($rInner = $innerQuery->fetch(PDO::FETCH_OBJ)) {
					$price = $rInner->price_ex_vat;
					$price = str_replace(",", " ", number_format($price * ($vat / 100) + $price, 2));
				};
				$origin = "";
				$originQuery = $this->db->query("SELECT media_origin FROM tbl_media_origin WHERE ID = '".$r->media_origin."';");
				while ($rOrigin = $originQuery->fetch(PDO::FETCH_OBJ)) {
					$origin = $rOrigin->media_origin;
				};
				$mediaType = "";
				//Media type
				$mediaTypeQuery = $this->db->query("SELECT media_type FROM tbl_media_type WHERE ID = '".$r->media_type."';");
				while ($rMediaType = $mediaTypeQuery->fetch(PDO::FETCH_OBJ)) {
					$mediaType = $rMediaType->media_type;
				};
				$inCart = "N";
				$cartCount = 0;
				$cartQuantity = 0;
				$cartQueryText = "SELECT COUNT(*) as line_count,
								  quantity 
								  FROM tbl_order_lines  
								  WHERE product_id = '".$r->ID."' 
								  AND order_id = '".$orderId."';";
				$cartQuery = $this->db->query($cartQueryText);
				while ($rCart = $cartQuery->fetch(PDO::FETCH_OBJ)) {
					$cartCount = $rCart->line_count;
					$cartQuantity = $rCart->quantity;
				};
				$quantity = 0;
				$queryInner = $this->db->query("SELECT quantity FROM tbl_product_quantities WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
				while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
					$quantity = $rInner->quantity;
					if ($quantity < 0) {
						$quantity = 0;
					};
				};
				echo '
				<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 product_tiles" id="tprod_'.$r->ID.'">
				  <div class="panel panel-default">
					<div class="panel-heading">
					  <h5>'.$r->product_name.'</h5>
					  <div class="origins">'.$origin.'</div>
					</div>
					<div class="panel-body">
					<div class="img_box effect2">';
				if (file_exists($this->image_symlink().'/tn_'.$stringId.".jpg")) {
					echo '<img src="http://admin.river-media.co.za/public/media/product_images/tn_'.$stringId.'.jpg" alt="'.$r->product_name.'" style="width:100%;" />';
				}
				else {
					echo '<img src="public/media/img/missing_image.gif" alt="'.$r->product_name.'" style="width:100%;" />';	
				};
				echo  '
				       <div class="clearfix"></div>
					   </div>
				       <p>'.$mediaType.' <small style="font-size:10pt!important;"> ('.$r->tag_array_physical_medium.')</small></p>';
				echo  '<div class="referencefield">Ref: '.$r->reference.'</div>
				       <p class="display_price">R'.$price.'</p>
					  <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 prod_quantity"><div>'.number_format($quantity).' items in stock</div></div>
					  <div class="clearfix"></div>';
				echo  '<span class="cart_addupd">
						<a href="javascript:void(0);" class="btn btn-default add_to_cart" data-toggle="popover" data-placement="top" data-content="Content"> <i class="fa fa-shopping-cart" aria-hidden="true"></i>';
				echo ' <span class="badge">'.$cartQuantity.'</span> ';
				echo ' <span>';
				if ($cartCount > 0) {
					echo ' CHANGE';
				}
				else {
					echo ' Add to Cart';
				};
				echo	'</span></a> 
					  </span>';
				if ($cartCount > 0) {
					echo '&nbsp;&nbsp;&nbsp;<span><a href="javascript:void(0);" class="remove_from_cart btn btn-default" id="tremove_'.$r->ID.'"> <i class="fa fa-remove" aria-hidden="true"></i> Remove</a></span>';
				};
				echo	  '<div class="clearfix"></div>
					  <div id="t_ajax_prod_cart_actions__'.$r->ID.'" class="hidden"></div>
					</div>
				  </div>
				</div>
				';
			};
		}
		else {
			header('Location: index');
		};
	}

	public function view_product() {
		if (isset($_GET['product_id'])) {
			$productId = $_GET['product_id'];
			$query = $this->db->query("SELECT product_name, product_description, media_type, media_origin, tag_array_physical_medium, string_id FROM tbl_products WHERE ID = '".$productId."';");
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$mediaType = "";
				$qInner = $this->db->query("SELECT media_type FROM tbl_media_type WHERE ID = '".$r->media_type."';");
				while ($rInner = $query->fetch(PDO::FETCH_OBJ)) {
					$mediaType = $rInner->media_type;
				};
				$mediaOrigin = "";
				$qInner = $this->db->query("SELECT media_origin FROM tbl_media_origin WHERE ID = '".$r->media_origin."';");
				while ($rInner = $query->fetch(PDO::FETCH_OBJ)) {
					$mediaOrigin = $rInner->media_origin;
				};
				$vatRate = $this->get_vat();
				$price = 0.00;
				$qInner = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$r->ID."' ORDER BY ID DESC LIMIT 0,1;");
				while ($rInner = $query->fetch(PDO::FETCH_OBJ)) {
					$price = "R".number_format(($rInner->price_ex_vat * ($vatRate / 10)), 2);
				};
				$productName = $r->product_name;
				$productDescription = $r->product_description;
				$physMedium = $r->tag_array_physical_medium;
				$stringId = strtolower(str_replace("{", "", str_replace("}", "", $r->string_id)));
				echo '
				<div style="margin-top:0; top:0;">
				  <input type="hidden" name="vp_prodname" id="vp_prodname" value="'.$productName.'" />
				  <img src="';
				if (file_exists($this->image_symlink().'/sm_'.$stringId.".jpg")) {
					echo 'http://admin.river-media.co.za/public/media/product_images/sm_'.$stringId.'.jpg';
				}
				else {
					echo 'public/media/img/missing_image.gif';
				};
				echo '
				  " alt="'.$r->product_name.'" style="border-bottom:1px solid #dddddd; padding-bottom:16px;" />
				  <div style="padding:16px; margin-top:7px;">'.$productDescription.'</div>
				</div>';
			};
		};
	}

	public function add_to_cart() {
		$cartSession = "";
		$customerId = 0;
		$productId = "";
		$orderId = "x";
		if (isset($_POST['product_id'])) {
			$productId = $_POST['product_id'];
		};
		$quantity = 0;
		if (isset($_POST['quantity'])) {
			$quantity = $_POST['quantity'];
			if (!(is_numeric($quantity))) {
				$quantity = 0;
			};
		};
		$quantity = $_POST['quantity'];
		$this->create_session();
		if (isset($_SESSION['customerlogin_info'])) {
			$customerId = $_SESSION['customerlogin_info'][4];
		};
		if (isset($_SESSION['cart_session']) && strlen($_SESSION['cart_session']) === 38) {
			$cartSession = $_SESSION['cart_session'];
			$_SESSION['cart_session'] = $cartSession;
			$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".trim($cartSession)."';");
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$orderId = $r->ID;
			};
			if ($orderId === "x") {
				$stmt = $this->db->prepare("INSERT INTO tbl_orders (customer_id, guid) VALUES (:customer_id, :guid);");
				$stmt->execute(array(':customer_id' => $customerId, ':guid' => $cartSession));
				$query = $this->db->query("SELECT LAST_INSERT_ID() AS order_id FROM tbl_orders;");
				while ($r = $query->fetch(PDO::FETCH_OBJ)) {
					$orderId = $r->order_id;
				};
			};
		}
		else {
			$cartSession = $this->create_guid();
			$_SESSION['cart_session'] = $cartSession;
			$stmt = $this->db->prepare("INSERT INTO tbl_orders (customer_id, created, guid) VALUES (:customer_id, NOW(), :guid);");
			$stmt->execute(array(':customer_id' => $customerId, ':guid' => $cartSession));
			$query = $this->db->query("SELECT LAST_INSERT_ID() AS order_id FROM tbl_orders;");
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$orderId = $r->order_id;
			};
		};
		$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".trim($cartSession)."';");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$orderId = $r->ID;
		};
		//Delete line from cart and re-insert
		$stmt = $this->db->prepare("DELETE FROM tbl_order_lines WHERE order_id = :order_id AND product_id = :product_id;");
		$stmt->execute(array(':order_id' => $orderId, ':product_id' => $productId));
		$stmt = $this->db->prepare("INSERT INTO tbl_order_lines (order_id, product_id, quantity) VALUES (:order_id, :product_id, :quantity);");
		$stmt->execute(array(':order_id' => $orderId, ':product_id' => $productId, ':quantity' => $quantity));
		echo 'inserted__'.$quantity;
	}

	public function update_cart() {
		$productId = "x";
		if (isset($_GET['product_id'])) {
			$productId = $_GET['product_id'];
		};
		$quantity = 0;
		if (isset($_GET['quantity'])) {
			$quantity = $_GET['quantity'];
		};
		$cartSession = $this->get_cart_session();
		$orderId = $this->get_order_id();
		if ($productId !== "x") {
			$stmt = $this->db->prepare("UPDATE tbl_order_lines SET quantity = :quantity WHERE product_id = :product_id AND order_id = :order_id;");
			$stmt->execute(array(':quantity' => $quantity, ':product_id' => $productId, ':order_id' => $orderId));
			echo $stmt->rowCount();
		};
	}

	public function get_cart_count() {
		$count = 0;
		$cartSession = "x";
		$orderId = "y";
		$this->create_session();
		if (isset($_SESSION['cart_session']) && strlen($_SESSION['cart_session']) === 38) {
			$cartSession = $_SESSION['cart_session'];
		};
		$query = $this->db->query("SELECT ID FROM tbl_orders WHERE guid = '".$cartSession."';");
		while($r = $query->fetch(PDO::FETCH_OBJ)) {
			$orderId = $r->ID;
		};
		$query = $this->db->query("SELECT COUNT(*) 
		                           AS line_count 
								   FROM tbl_order_lines 
								   WHERE order_id = '".$orderId."' 
								   AND order_id = (
								     SELECT ID
									 FROM tbl_orders
									 WHERE ID = '".$orderId."'
									 AND order_state = 'CART'
								   );
								   ");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$count = $r->line_count;
		};
		return $count;
	}
	
	public function total_cart_count() {
		echo $this->get_cart_count();
	}
		
	public function delete_from_cart() {
		$productId = "x";
		if (isset($_GET['product_id'])) {
			$productId = $_GET['product_id'];
		};
		$cartSession = $this->get_cart_session();
		$orderId = $this->get_order_id();
		$stmt = $this->db->prepare("DELETE FROM tbl_order_lines WHERE order_id = :order_id AND product_id = :product_id");
		$stmt->execute(array('order_id' => $orderId, 'product_id' => $productId));
		echo 'removed';
	}
	
	public function view_cart() {
		echo '<table class="table table-hover" id="cart_table">';
		echo '  <thead>';
		echo '    <tr>';
		echo '      <th>&nbsp;</th>';
		echo '      <th>Item</th>';
		echo '      <th>By</th>';
		echo '      <th>Event</th>';
		echo '      <th style="text-align:right;">Quantity</th>';
		echo '      <th>&nbsp;</th>';
		echo '      <th style="text-align:center;">Remove</th>';
		echo '    </tr>';
		echo '  </thead>';
		echo '  <tbody>';
		$orderId = $this->get_order_id();
		$queryText = "SELECT tbl_products.product_name AS product_name,
					  tbl_products.ID AS product_id, 
					  tbl_order_lines.ID AS line_id, 
					  tbl_order_lines.quantity AS quantity,
					  tbl_media_origin.media_origin AS media_origin,
					  tbl_products.media_event AS event_id  
					  FROM tbl_products, tbl_media_origin, tbl_order_lines, tbl_orders  
					  WHERE tbl_products.ID = tbl_order_lines.product_id 
					  AND tbl_products.media_origin = tbl_media_origin.ID
					  AND tbl_order_lines.order_id = '".$orderId."' 
					  AND tbl_orders.ID = '".$orderId."' 
					  AND tbl_orders.order_state = 'CART' 
					  ORDER BY tbl_order_lines.ID ASC;
					  ";
		$recordCount = 0;
		$query = $this->db->query($queryText);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$recordCount = $recordCount + 1;
			$event = "";
			if ($r->event_id !== "0") {
				$queryInner = $this->db->query("SELECT CONCAT_WS(' ', event_year, event_name) AS event_title FROM tbl_event WHERE ID = '".$r->event_id."';");
				while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
					$event = $rInner->event_title;
				};
			};
			echo '  <tr id="cart_row_'.$r->product_id.'">';
			echo '    <th>'.$recordCount.'</th>';
			echo '    <td>'.$r->product_name.'</td>';
			echo '    <td>'.$r->media_origin.'</td>';
			echo '    <td>'.$event.'</td>';
			echo '    <td style="text-align:right!important;">
			<span style="text-align:right!important;">
			  <span class="col-xs-6 col-sm-5 col-md-5 col-lg-5 pull-right">
			    <input type="text" name="ct_'.$r->product_id.'" id="ct_'.$r->product_id.'" class="form-control cart_quantity_inputs" maxlength="4" min="1" style="text-align:right;" value="'.$r->quantity.'" />
				<input type="hidden" name="oq_'.$r->product_id.'" id="oq_'.$r->product_id.'" value="'.$r->quantity.'" />
			  </span>
			</span>
			</td>';
			echo '    <td><span class="col-xs-5 col-sm-5 col-md-5 col-lg-5"><a href="javascript:void(0);" class="btn btn-primary" id="cupd_'.$r->product_id.'"> UPDATE </a></span></span></td>';
			echo '    <td style="text-align:center;"><i class="fa fa-times" id="de_'.$r->product_id.'" aria-hidden="true"></i><div class="hidden" id="ajax_prod_cart_actions__'.$r->product_id.'"></div></td>';
			echo '  </tr>';
		};
		echo '  <tr>
		          <td>&nbsp;</td>
				  <td id="cart_record_count" class="';
		if ($recordCount === 0) {
			echo 'counter_zero';
		}
		else {
			echo 'counter_gtzero';
		};
		echo	  '">'.$recordCount.' item';
		if ($recordCount !== 1) {
			echo 's';
		};
		echo	'</td>
		         <td>&nbsp;</td>
				 <td>&nbsp;</td>
				 <td>&nbsp;</td>
				 <td>&nbsp;</td>
				 <td>&nbsp;</td>
		       </tr>';
		echo '  </tbody>';
		echo '</table>';
	}
	/*
	public function get_shipping_rate() {
		$ratePerKg = 0.00;
		$query = $this->db->query("SELECT price_per_kg FROM tbl_shipping_rate_per_kg ORDER BY ID DESC LIMIT 0,1;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$ratePerKg = $r->price_per_kg;
		};
		return $ratePerKg;
	}
	*/
	public function get_shipping_rates() {
		$firstKg = 0.00;
		$perAdditionalKg = 0.00;
		$query = $this->db->query("SELECT first_kg, per_additional_kg FROM tbl_shipping ORDER BY ID DESC LIMIT 0,1;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$firstKg = str_replace(",", "", number_format($r->first_kg, 2));
			$perAdditionalKg = str_replace(",", "", number_format($r->per_additional_kg, 2));
		};
		return array($firstKg, $perAdditionalKg);
	}
	
	public function delivery_address() {
		$sessionArray = $this->read_login_session();
		$customerId = $sessionArray[4];
		$orderId = $this->get_order_id();
		$customerOrderNumber = "";
		if (isset($_POST['customer_order_number']) && trim($_POST['customer_order_number']) !== "") {
			$customerOrderNumber = filter_var($_POST['customer_order_number'], FILTER_SANITIZE_STRING);
			$stmt = $this->db->prepare("UPDATE tbl_orders SET customer_order_number = :customer_order_number WHERE ID = :order_id;");
			$stmt->execute(array(':customer_order_number' => $customerOrderNumber, ':order_id' => $orderId));
		};
		if (trim($_POST['line1']) !== "" && trim($_POST['line2']) !== "" && trim($_POST['line3']) !== "" && trim($_POST['postal_code']) !== "") {
			$line1 = filter_var($_POST['line1'], FILTER_SANITIZE_STRING);
			$line2 = filter_var($_POST['line2'], FILTER_SANITIZE_STRING);
			$line3 = filter_var($_POST['line3'], FILTER_SANITIZE_STRING);
			$line4 = filter_var($_POST['line4'], FILTER_SANITIZE_STRING);
			$postalCode = filter_var($_POST['postal_code'], FILTER_SANITIZE_STRING);
			$stmt = $this->db->prepare("UPDATE tbl_delivery_address SET line1 = :line1, line2 = :line2, line3 = :line3, line4 = :line4, postal_code = :postal_code WHERE customer_id = :customer_id");
			$stmt->execute(array(':line1' => $line1, ':line2' => $line2, ':line3' => $line3, ':line4' => $line4, ':postal_code' => $postalCode, ':customer_id' => $customerId));
			echo $stmt->rowCount();
			die();
		};	
		$addressArray = array("", "", "", "", "");
		$query = $this->db->query("SELECT * FROM tbl_delivery_address WHERE customer_id = '".$customerId."';");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$addressArray = array($r->line1, $r->line2, $r->line3, $r->line4, $r->postal_code);
			return $addressArray;
		};
	}
	
	public function calculate_cart_total_due() {
		$orderId = $this->get_order_id();
		$vatRate = $this->get_vat();
		$shipppingRates = $this->get_shipping_rates();
		$firstKg = $shipppingRates[0];
		$perAdditionalKg = $shipppingRates[1];
		$subTotal = 0;
		$productId = "";
		$quantity = 0;
		$linePrice = 0;
		$vatAmount = 0;
		$totalIncVat = 0;
		$itemWeight = 0;
		$lineWeight = 0;
		$totalWeight = 0;
		$fields = "";
		$fields_string = "";
		$q = "SELECT tbl_order_lines.product_id AS product_id,
		      tbl_order_lines.quantity AS quantity 
			  FROM tbl_order_lines 
			  WHERE order_id = '".$orderId."';";
		$query = $this->db->query($q);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$quantity = $r->quantity;
			$linePrice = 0;
			$productId = $r->product_id;
			$queryInner = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$productId."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$linePrice = $rInner->price_ex_vat * $quantity;
			};
			$queryWeight = $this->db->query("SELECT shipping_weight FROM tbl_products WHERE ID = '".$productId."';");
			while ($rWeight = $queryWeight->fetch(PDO::FETCH_OBJ)) {
				$itemWeight = $rWeight->shipping_weight;
			};
			$totalWeight = $totalWeight + str_replace(",", "", number_format(($itemWeight * $quantity), 2));
			$subTotal = str_replace(",", "", number_format($subTotal + $linePrice, 2));
		};
		$subtoTal = str_replace(",", "", number_format($subTotal, 2));
		//$shippingTotal = str_replace(",", "", number_format(($totalWeight * $ratePerKg), 2));
		if ($totalWeight <= 1) {
			$shippingTotal = $firstKg;
		}
		else {
			$additionalWeight = ceil($totalWeight - 1);
			$additionalWeightCalc = str_replace(",", "", number_format($additionalWeight * $perAdditionalKg, 2));
			$shippingTotal = str_replace(",", "", number_format($firstKg + ($additionalWeightCalc), 2));
		};
		
		$shippingTotal = str_replace(",", "", number_format($shippingTotal, 2));
		
		//$vatAmount = str_replace(",", "", number_format(($subTotal + $shippingTotal) * ($vatRate / 100), 2));
		$vatAmount = str_replace(",", "", number_format($subTotal * ($vatRate / 100), 2));
		$totalIncVat = str_replace(",", "", number_format($shippingTotal + ($subTotal * ($vatRate / 100)) + $subTotal, 2));
		return $totalIncVat;
	}

	public function debug_cart_total_due() {
		$orderId = $this->get_order_id();
		$vatRate = $this->get_vat();
		$shipppingRates = $this->get_shipping_rates();
		$firstKg = $shipppingRates[0];
		$perAdditionalKg = $shipppingRates[1];
		echo 'firstKg = '.$firstKg.', perAdditionalKg = '.$perAdditionalKg;
		$subTotal = 0;
		$productId = "";
		$quantity = 0;
		$linePrice = 0;
		$vatAmount = 0;
		$totalIncVat = 0;
		$itemWeight = 0;
		$lineWeight = 0;
		$totalWeight = 0;
		$fields = "";
		$fields_string = "";
		$q = "SELECT tbl_order_lines.product_id AS product_id,
		      tbl_order_lines.quantity AS quantity 
			  FROM tbl_order_lines 
			  WHERE order_id = '".$orderId."';";
		$query = $this->db->query($q);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$quantity = $r->quantity;
			$linePrice = 0;
			$productId = $r->product_id;
			$queryInner = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$productId."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$linePrice = $rInner->price_ex_vat * $quantity;
			};
			$queryWeight = $this->db->query("SELECT shipping_weight FROM tbl_products WHERE ID = '".$productId."';");
			while ($rWeight = $queryWeight->fetch(PDO::FETCH_OBJ)) {
				$itemWeight = $rWeight->shipping_weight;
			};
			$totalWeight = $totalWeight + str_replace(",", "", number_format(($itemWeight * $quantity), 2));
			$subTotal = str_replace(",", "", number_format($subTotal + $linePrice, 2));
		};
		$subtoTal = str_replace(",", "", number_format($subTotal, 2));
		echo '<br />Subtotal = '.$subTotal;
		//$shippingTotal = str_replace(",", "", number_format(($totalWeight * $ratePerKg), 2));
		if ($totalWeight <= 1) {
			$shippingTotal = $firstKg;
		}
		else {
			$additionalWeight = ceil($totalWeight - 1);
			$additionalWeightCalc = str_replace(",", "", number_format($additionalWeight * $perAdditionalKg, 2));
			$shippingTotal = str_replace(",", "", number_format($firstKg + ($additionalWeightCalc), 2));
		};
		
		$shippingTotal = str_replace(",", "", number_format($shippingTotal, 2));
		echo '<br /> ShippingTotal = '.$shippingTotal;
		
		//$vatAmount = str_replace(",", "", number_format(($subTotal + $shippingTotal) * ($vatRate / 100), 2));
		$vatAmount = str_replace(",", "", number_format($subTotal * ($vatRate / 100), 2));
		$totalIncVat = str_replace(",", "", number_format($shippingTotal + ($subTotal * ($vatRate / 100)) + $subTotal, 2));
		echo '<br />VatAmount = '.$vatAmount;
		return $totalIncVat;
	}

	
	public function banking_details() {
		$orderId = $this->get_order_id();
		$bankName = "";
		$accountName = "";
		$accountNumber = "";
		$accountType = "";
		$branchCode = "";
		$popContact = "";
		$popFax = "";
		$query = $this->db->query("SELECT * FROM tbl_banking_details LIMIT 0,1;");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$bankName = $r->bank_name;
			$accountName = $r->account_name;
			$accountNumber = $r->account_number;
			$accountType = $r->account_type;
			$branchCode = $r->branch_code;
			$popContact = $r->pop_contact;
			$popFax = $r->pop_fax;
		};
		if ($orderId === "x") {
			echo 'Session expired!';
		}
		else {
		$orderId = str_pad($orderId, 6, '0', STR_PAD_LEFT);
			echo '
				<table width="333" border="0" cellspacing="3" cellpadding="0">
				  <tr style="background:#eeeeee;">
					<td width="48%" align="right" valign="top">BANK</td>
					<td width="5%">:</td>
					<td width="47%" align="left" valign="top">'.$bankName.'</td>
				  </tr>
				  <tr>
					<td align="right" valign="top">ACCOUNT NAME</td>
					<td>:</td>
					<td align="left" valign="top">'.$accountName.'</td>
				  </tr>
				  <tr style="background:#eeeeee;">
					<td align="right" valign="top">ACCOUNT NUMBER</td>
					<td>:</td>
					<td align="left" valign="top">'.$accountNumber.'</td>
				  </tr>
				  <tr>
					<td align="right" valign="top">ACCOUNT TYPE</td>
					<td>:</td>
					<td align="left" valign="top">'.$accountType.'</td>
				  </tr>
				  <tr style="background:#eeeeee;">
					<td align="right" valign="top">BRANCH CODE</td>
					<td>:</td>
					<td align="left" valign="top">'.$branchCode.'</td>
				  </tr>
				  <tr>
					<td align="right" valign="top">REFERENCE</td>
					<td>:</td>
					<td align="left" valign="top">'.$orderId.'</td>
				  </tr>
				  <tr style="background:#eeeeee; font-weight:bold; color:#ff0000;">
					<td align="right" valign="top">TOTAL DUE</td>
					<td>:</td>
					<td align="left" valign="top">R'.$this->calculate_cart_total_due().'</td>
				  </tr>
				</table>
				<br />
				<div>Please fax proof of payment to '.$popContact.' on <span id="popfax">'.$popFax.'</span></div>
				<br />
				<div style="color:#009900;">Click the CONFIRM button to confirm your order</div>
			';
		};
	}
	
	public function eft_order() {
		$orderId = $this->get_order_id();
		$priceIncVat = $this->calculate_cart_total_due();
		$priceIncVat = str_replace(',', '', $priceIncVat);
		$stmt = $this->db->prepare("UPDATE tbl_orders SET order_state = :order_state, price_inc_vat = :price_inc_vat WHERE ID = :order_id;");
		$stmt->execute(array(':order_state' => 'ORDER', ':price_inc_vat' => $priceIncVat, ':order_id' => $orderId));
		$stmt = $this->db->prepare("INSERT INTO tbl_order_progress (order_id, state_id) VALUES (:order_id, :state_id)");
		$stmt->execute(array(':order_id' => $orderId, ':state_id' => '10'));
		$this->create_invoice();
	}
	
	public function order_confirm() {
		$this->create_session();
		$_SESSION['cart_session'] = '';
		unset($_SESSION['cart_session']);
	}
	
	public function vcs_gateway() {
		//VCS parameters
		$url = "https://www.vcs.co.za/vvonline/vcspay.aspx";
		$vcsTerminalId = '9870';
		$canceledUrl = 'http://test.myriver.com/rivermedia/pay';
		//End VCS
		$sessionArray = $this->get_login_session();
		$customerId = $sessionArray[4];
		$orderId = $this->get_order_id();
		$vatRate = $this->get_vat();
		//$ratePerKg = $this->get_shipping_rate();
		$shipppingRates = $this->get_shipping_rates();
		$firstKg = $shipppingRates[0];
		$perAdditionalKg = $shipppingRates[1];
		$attemptCounter = $this->get_vcs_attempt_no();
		$attemptCounter = explode('__', $attemptCounter);
		$attemptCounter = $attemptCounter[1];
		$shippingTotal = 0;
		$subTotal = 0;
		$productId = "";
		$quantity = 0;
		$linePrice = 0;
		$vatAmount = 0;
		$totalIncVat = 0;
		$itemWeight = 0;
		$lineWeight = 0;
		$totalWeight = 0;
		$fields = "";
		$fields_string = "";
		$q = "SELECT tbl_order_lines.product_id AS product_id,
		      tbl_order_lines.quantity AS quantity 
			  FROM tbl_order_lines 
			  WHERE order_id = '".$orderId."';";
		$query = $this->db->query($q);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$quantity = $r->quantity;
			$linePrice = 0;
			$productId = $r->product_id;
			$queryInner = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$productId."' ORDER BY ID DESC LIMIT 0,1;");
			while ($rInner = $queryInner->fetch(PDO::FETCH_OBJ)) {
				$linePrice = $rInner->price_ex_vat * $quantity;
			};
			$queryWeight = $this->db->query("SELECT shipping_weight FROM tbl_products WHERE ID = '".$productId."';");
			while ($rWeight = $queryWeight->fetch(PDO::FETCH_OBJ)) {
				$itemWeight = $rWeight->shipping_weight;
			};
			$totalWeight = $totalWeight + number_format(($itemWeight * $quantity), 2);
			$subTotal = $subTotal + $linePrice;
		};
		
		if ($totalWeight <= 1) {
			$shippingTotal = $firstKg;
		}
		else {
			$additionalWeight = ceil($totalWeight - 1);
			$shippingTotal = $firstKg + ($additionalWeight * $perAdditionalKg);
		};
		
		$shippingTotal = str_replace(",", "", number_format($shippingTotal, 2));
		
		//$shippingTotal = str_replace(",", "", number_format(($totalWeight * $ratePerKg), 2));
		//$vatAmount = str_replace(",", "", number_format(($subTotal + $shippingTotal) * ($vatRate / 100), 2));
		//$totalIncVat = number_format((($subTotal + $shippingTotal) * ($vatRate / 100)) + $subTotal + $shippingTotal, 2);
		$vatAmount = str_replace(",", "", number_format($subTotal * ($vatRate / 100), 2));
		$totalIncVat = number_format($shippingTotal + ($subTotal * ($vatRate / 100)) + $subTotal, 2);
		//P1, P2, P3, P4, P5, P10, P
		$fields = array($vcsTerminalId, $customerId.'-'.$orderId.'__'.$attemptCounter, 'RIVER MEDIA ORDER', $totalIncVat, 'ZAR', $canceledUrl, $sessionArray[0]);
		return $fields;
  	}
	
	public function get_vcs_attempt_no() {
		$orderId = $this->get_order_id();
		$vcsAttemptNo = 0;
		$query = $this->db->query("SELECT vcs_attempt_no FROM tbl_orders WHERE ID = '".$orderId."';");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$vcsAttemptNo = $r->vcs_attempt_no;
		};
		return $orderId.'__'.$vcsAttemptNo;
	}
	
	public function update_vcs_attempt_no() {
		$this->create_session();
		if (strlen($_SESSION['cart_session']) === 38) {
			$arrayVcsAttempt = explode('__', $this->get_vcs_attempt_no());
			$orderId = $arrayVcsAttempt[0];
			$existingValue = $arrayVcsAttempt[1];
			$newValue = $existingValue + 1;
			$stmt = $this->db->prepare("UPDATE tbl_orders SET vcs_attempt_no = :vcs_attempt_no WHERE ID = :order_id");
			$stmt->execute(array(':vcs_attempt_no' => $newValue, ':order_id' => $orderId));
		}
		else {
			header('Location: view_cart');	
		};
	}
	
	public function get_bank_error() {
		$errArray = array('', '');
		$errorDescription = "";
		if ($_POST['p3']) {
		  $errorDescription = $_POST['p3'];
		};
		if (trim($errorDescription) !== "") {
			$errArray = array('<h4 class="error" style="text-align:center;"> Transaction failed <br /><i class="fa fa-credit-card" aria-hidden="true" style="font-size:48pt!important;"></i></h4>', '<h5 class="error" style="text-align:center;">'.$errorDescription.'</h5>');
		};
		return $errArray;
	}
	
	public function success() {
		$vcsResponse = "";
		if (isset($_POST['p3'])) {
			$vcsResponse = $_POST['p3'];
		};
		$totalAmount = 0.00;
		if (isset($_POST['p6'])) {
			$totalAmount = str_replace(',', '', $_POST['p6']);
		};
		if (strpos($vcsResponse, 'APPROVED') > 0) {
			$customerId = $this->get_login_session();
			$orderId = $this->get_order_id();
			$stmt = $this->db->prepare("UPDATE tbl_orders SET order_state = :order_state, vcs_response = :vcs_response, price_inc_vat = :price_inc_vat WHERE ID = :order_id;");
			$stmt->execute(array(':order_state' => 'ORDER', ':vcs_response' => $vcsResponse, ':price_inc_vat' => $totalAmount, ':order_id' => $orderId));
			$queryText = "
			SELECT tbl_order_lines.product_id, 
			tbl_order_lines.quantity 
			FROM tbl_order_lines, tbl_orders 
			WHERE tbl_order_lines.order_id = '".$orderId."' 
			AND tbl_orders.ID = tbl_order_lines.order_id 
			AND tbl_orders.order_state = 'ORDER';
			";
			$query = $this->db->query($queryText);
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$queryGetQuantity = $this->db->query("SELECT quantity FROM tbl_product_quantities WHERE product_id = '".$r->product_id."' ORDER BY ID DESC LIMIT 0,1;");
				while ($rGetQuantity = $queryGetQuantity->fetch(PDO::FETCH_OBJ)) {
					$stmt = $this->db->prepare("INSERT INTO tbl_product_quantities (product_id, order_id, quantity, transaction_type) VALUES (:product_id, :order_id, :quantity, :transaction_type);");
					$stmt->execute(array(':product_id' => $r->product_id, ':order_id' => $orderId, ':quantity' => $rGetQuantity->quantity - $r->quantity, ':transaction_type' => 'ORDER'));
				};
			};
			$stmt = $this->db->prepare("INSERT INTO tbl_order_progress (order_id, state_id) VALUES (:order_id, :state_id)");
			$stmt->execute(array(':order_id' => $orderId, ':state_id' => '2'));
			$this->create_session();
			$_SESSION['payment_valid'] = 'Y';
			$this->create_invoice();
			header('Location: success');
		}
		else {
			header('Location: pay');	
		};
	}
	
	public function get_order_lines() {
		$orderId = $this->get_order_id();
	}
	
	public function mail_invoice($docName, $type) {
		$sessionArray = $this->get_login_session();
		$emailAddress = $sessionArray[0];
		require_once('includes/phpMailer/class.phpmailer.php');
		$email = new PHPMailer();
		$email->From      = 'bookshop@myriver.com';
		$email->FromName  = 'River Media';
		$email->Subject   = 'Invoice';
		$email->Body      = 'Thank you for using River Media\'s online shop. Your invoice is attached.';
		$email->AddAddress($emailAddress);
		$cwd = getcwd();
		$file_to_attach = $cwd.'/public/pdf/invoices/'.$docName;
		$email->AddAttachment($file_to_attach);
		$email->Send();	
		echo '<div';
		if ($type === 'AWAITING EFT') {
			echo ' style="color:#ffffff;"';
		};
		echo '>A copy of the invoice has also been mailed to you.</div>';
		unset($_SESSION['cart_session']);
	}
	
	public function create_invoice() {
		$vatRate = $this->get_vat();
		$sessionArray = $this->get_login_session();
		$customerId = $sessionArray[4];
		$orderId = $this->get_order_id();
		$orderId = str_pad($orderId, 6, '0', STR_PAD_LEFT);
		$orderDate = '';
		$vcsResponse = '';
		$query = $this->db->query("SELECT created, vcs_response FROM tbl_orders WHERE ID = '".$orderId."';");
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$orderDate = explode(' ', $r->created);
			$vcsResponse = $r->vcs_response;
			if (strpos($vcsResponse, 'APPROVED') > 0) {
				$vcsResponse = "VCS <br />&nbsp;&nbsp;&nbsp;".$vcsResponse;
			};
		};
		require_once('tcpdf/tcpdf.php');
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('River Media');
		$pdf->SetTitle('Invoice');
		$pdf->SetSubject('River Media Invoice');
		$pdf->SetKeywords('River Media, Invoice');
		$pdf->setPrintHeader(false);
		$pdf->setPrintFooter(false);
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
		$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
		if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
			require_once(dirname(__FILE__).'/lang/eng.php');
			$pdf->setLanguageArray($l);
		}
		$pdf->SetFont('dejavusans', '', 9.5);
		$pdf->SetMargins(10, 5, 10, true);
		$pdf->AddPage();
		$html = '
		<table style="font-size:14pt; color:#777777;">
		  <tr>
			<td><img src="public/media/img/pdf_logo.png" /></td>
			<td align="right">RIVER-MEDIA<br />INVOICE #'.$orderId.'<br />'.$orderDate[0].'</td>
		  </tr>
		</table>';
		$deliveryAddress = $this->delivery_address();
		$html = $html.'<br /><br /><br /><br />
		<table width="650" border="0" cellspacing="3" cellpadding="0">
		  <tr>
			<td width="50%" style="background-color:#555555; color:#ffffff;">&nbsp;DELIVERY &amp; BILLING ADDRESS</td>
			<td colspan="2" width="50%" style="background-color:#555555; color:#ffffff;">&nbsp;ORDER HEADERS</td>
		  </tr>
		  <tr>
			<td style="color:#555555;">&nbsp;'.$deliveryAddress[0].'</td>
			<td width="24%" style="color:#555555;">&nbsp;ORDER NUMBER</td>
			<td width="23%">&nbsp;: '.$this->get_customer_order_number().'</td>
		  </tr>
		  <tr>
			<td style="color:#555555;">&nbsp;'.$deliveryAddress[1].'</td>
			<td style="color:#555555;">&nbsp;Order Date</td>
			<td>&nbsp;: '.$orderDate[0].'</td>
		  </tr>
		  <tr>
			<td style="color:#555555;">&nbsp;'.$deliveryAddress[2].'</td>
			<td style="color:#555555;">&nbsp;Payment Method</td>
			<td>&nbsp;: '.$vcsResponse.'</td>
		  </tr>
		  <tr>
			<td style="color:#555555;">&nbsp;'.$deliveryAddress[3].'</td>
			<td>&nbsp;</td>
			<td>&nbsp;</td>
		  </tr>
		  <tr>
			<td style="color:#555555;">&nbsp;'.$deliveryAddress[4].'</td>
			<td>&nbsp;</td>
			<td>&nbsp;</td>
		  </tr>		  
		</table>
		<br /><br /><br />
		';
		$html = $html.'
		<table width="650" border="0" cellspacing="3" cellpadding="0">
		  <tr>
			<td width="321" style="background-color:#555555; color:#ffffff;">&nbsp;ITEM</td>
			<td width="95" style="background-color:#555555; color:#ffffff;" align="right">PRICE Inc VAT&nbsp;&nbsp;</td>
			<td width="91" style="background-color:#555555; color:#ffffff;" align="right">QUANTITY&nbsp;&nbsp;</td>
			<td width="128" style="background-color:#555555; color:#ffffff;" align="right">TOTAL&nbsp;&nbsp;</td>
		  </tr>';
		$lineCount = 0; 
		$rowColour = "ffffff";
		$totalWeight = 0;
		$subTotalEx = 0;
		$subTotal = 0;
		$queryOrderLines = "SELECT tbl_products.product_name AS product_name, 
		                    tbl_products.shipping_weight AS weight, 
							tbl_products.media_event AS event_id, 
							tbl_products.ID AS product_id, 
							tbl_media_origin.media_origin AS media_origin, 
							tbl_order_lines.quantity AS quantity 
							FROM tbl_products, tbl_media_origin, tbl_order_lines, tbl_orders 
							WHERE tbl_products.ID = tbl_order_lines.product_id 
							AND tbl_media_origin.ID = tbl_products.media_origin
							AND tbl_order_lines.order_id = tbl_orders.ID
							AND tbl_orders.customer_id = '".$customerId."' 
							AND tbl_orders.ID = '".$orderId."'
							ORDER BY tbl_order_lines.ID ASC;
		"; 
		$query = $this->db->query($queryOrderLines);
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$event = "";
			if ($r->event_id !== "0") {
				$queryEvent = $this->db->query("SELECT CONCAT_WS(' ', event_year, event_name) AS media_event FROM tbl_event WHERE ID = '".$r->event_id."';");
				while ($rEvent = $queryEvent->fetch(PDO::FETCH_OBJ)) {
					$event = $rEvent->media_event;
				};
			};
		$priceExc = 0;
		$priceInc = 0;
		$queryPrice = $this->db->query("SELECT price_ex_vat FROM tbl_price WHERE product_id = '".$r->product_id."' ORDER BY ID DESC LIMIT 0,1;");
		while ($rPrice = $queryPrice->fetch(PDO::FETCH_OBJ)) {
			$priceExc = $rPrice->price_ex_vat;
			$priceInc = str_replace(",", " ", number_format($priceExc * ($vatRate / 100) + $priceExc, 2));
		};
		if ($lineCount % 2 == 0) {
			$rowColour = "efefef";
		}
		else {
			$rowColour = "dedede";
		};
		$html = $html.'
		  <tr>
			<td style="background-color:#'.$rowColour.';">&nbsp;'.$r->product_name.' '.$r->media_origin.' '.$event.'</td>
			<td style="background-color:#'.$rowColour.';" align="right">'.number_format($priceInc, 2).'&nbsp;&nbsp;</td>
			<td style="background-color:#'.$rowColour.';" align="right">'.$r->quantity.'&nbsp;&nbsp;</td>
			<td style="background-color:#'.$rowColour.';" align="right">'.number_format(($r->quantity * $priceInc), 2).'&nbsp;&nbsp;</td>
		  </tr>
		';
		$lineCount = $lineCount + 1;
		$totalWeight = $totalWeight + str_replace(",", "", number_format(($r->weight * $r->quantity), 2));
		$subTotal = $subTotal + ($r->quantity * $priceInc);
		$subTotalEx = $subTotalEx + ($r->quantity * $priceExc);
		};
		$subTotalEx = str_replace(",", "", number_format($subTotalEx, 2));
		//$ratePerKg = $this->get_shipping_rate();
		$shipppingRates = $this->get_shipping_rates();
		$firstKg = $shipppingRates[0];
		$perAdditionalKg = $shipppingRates[1];
		
		if ($totalWeight <= 1) {
			$shippingTotal = $firstKg;
		}
		else {
			$additionalWeight = ceil($totalWeight - 1);
			$shippingTotal = str_replace(",", "", number_format($firstKg + ($additionalWeight * $perAdditionalKg), 2));
		};

		//$vatAmount = str_replace(",", "", number_format(($subTotalEx + ($totalWeight * $ratePerKg)) * (($vatRate / 100)), 2));
		$vatAmount = str_replace(",", "", number_format($subTotal * ($vatRate / 100), 2));
		$totalIncVat = number_format($shippingTotal + $subTotal, 2);

		$html = $html.'
		  <tr>
			<td colspan="3" align="right">&nbsp;</td>
			<td align="right">&nbsp;</td>
		  </tr>
		  <tr>
			<td colspan="3" align="right">Subtotal&nbsp;&nbsp;</td>
			<td align="right" style="border-bottom:1px dotted #999999;">'.number_format($subTotal, 2).'&nbsp;&nbsp;</td>
		  </tr>
		  <tr>
			<td colspan="3" align="right">Shipping&nbsp;&nbsp;</td>
			<td align="right" style="border-bottom:1px dotted #999999;">'.number_format($shippingTotal, 2).'&nbsp;&nbsp;</td>
		  </tr>
		  <tr>
			<td colspan="3" align="right">VAT Amount&nbsp;&nbsp;</td>
			<td align="right" style="border-bottom:1px dotted #999999;">'.number_format($vatAmount, 2).'&nbsp;&nbsp;</td>
		  </tr>
		  <tr>
			<td colspan="3" align="right">&nbsp;&nbsp;</td>
			<td>&nbsp;&nbsp;</td>
		  </tr>
		  <tr>
			<td colspan="3" align="right">Total&nbsp;&nbsp;</td>
			<td align="right" style="border-top:1px solid #333333; border-bottom:1px solid #333333;">R'.$totalIncVat.'&nbsp;&nbsp;</td>
		  </tr>
		</table>
		<br /><br /><br />
		<table width="650" border="0" cellspacing="3" cellpadding="0">
		  <tr>
			<td colspan="2" align="left" valign="top" style="background-color:#555555; color:#ffffff;">&nbsp;BANKING DETAILS</td>
			<td width="172" align="left" valign="top" style="background-color:#555555; color:#ffffff;">&nbsp;POSTAL ADDRESS</td>
			<td width="145" align="left" valign="top" style="background-color:#555555; color:#ffffff;">&nbsp;PHYSICAL ADDRESS</td>
		  </tr>
		  <tr>
			<td width="113" align="left" valign="top">&nbsp;Bank</td>
			<td width="205" align="left" valign="top">&nbsp;: Standard Bank</td>
			<td align="left" valign="top">&nbsp;P/Bag X9027</td>
			<td align="left" valign="top">&nbsp;1 Pontoon Rd</td>
		  </tr>
		  <tr>
			<td align="left" valign="top">&nbsp;Account Name</td>
			<td align="left" valign="top">&nbsp;: River Media</td>
			<td align="left" valign="top">&nbsp;East London</td>
			<td align="left" valign="top">&nbsp;East London</td>
		  </tr>
		  <tr>
			<td align="left" valign="top">&nbsp;Account No</td>
			<td align="left" valign="top">&nbsp;: 081174438</td>
			<td align="left" valign="top">&nbsp;5200</td>
			<td align="left" valign="top">&nbsp;5201</td>
		  </tr>
		  <tr>
			<td align="left" valign="top">&nbsp;Branch Code</td>
			<td align="left" valign="top">&nbsp;: 050021</td>
			<td align="left" valign="top">&nbsp;</td>
			<td align="left" valign="top">&nbsp;</td>
		  </tr>
		  <tr>
			<td align="left" valign="top">&nbsp;</td>
			<td align="left" valign="top">&nbsp;</td>
			<td align="left" valign="top">&nbsp;</td>
			<td align="left" valign="top">&nbsp;</td>
		  </tr>
		  <tr>
			<td colspan="4" align="left" valign="top">&nbsp;Fax proof of payment to 043 711 4915, attention Liza</td>
		  </tr>
		</table>
		<br /><br/><br />
		';
		$pdf->writeHTML($html, true, false, true, false, '');
		$footerText = '
		<div style="text-align:center; border-top:1px solid #999999; color:#777777;">
		<br />Tel: 043 711 4800&nbsp;&nbsp;&#8226;&nbsp;&nbsp;Fax: 043 711 4915<br />A division of RIVER GROUP
		</div>
		';
		$pdf->writeHTMLCell(0, 0, '', '', $footerText, 0, 1, false, true, 'L', true);
		//$pdf->Output($orderId.'.pdf', 'I'); //Render in browser
		$cwd = getcwd();
		ob_clean();
		$pdf->Output($cwd.'/public/pdf/invoices/'.$orderId.'.pdf', 'F'); //Save to file
		echo '<div';
		if ($vcsResponse === 'AWAITING EFT') {
			echo ' style="color:#ffffff;"';
		};
		echo '>Your invoice has been created. Click <a href="view_invoice">here</a> to download the pdf.</div>';
		$this->mail_invoice($orderId.'.pdf', $vcsResponse); //Mail invoice
	}
	
	public function list_invoices() {
		$sessionArray = $this->get_login_session();
		$customerId = $sessionArray[4];
		$rowCounter = 0;
		echo '<table class="table table-hover" id="invoice_table">';
		echo '  <thead>';
		echo '    <tr>';
		echo '      <th>&nbsp;</th>';
		echo '      <th>Invoice #</th>';
		echo '      <th>Customer Ref</th>';
		echo '      <th>Date/Time</th>';
		echo '      <th style="text-align:right;">Amount</th>';
		echo '      <th style="text-align:center;"><img src="public/media/img/128x128-pdf.png" style="width:20px; height:20px;" /></th>';
		echo '    </tr>';
		echo '  </thead>';
		echo '  <tbody>';
		$query = $this->db->query("SELECT ID, customer_order_number, created, price_inc_vat FROM tbl_orders WHERE customer_id = '".$customerId."' AND order_state = 'ORDER' ORDER BY ID DESC;");	
		while ($r = $query->fetch(PDO::FETCH_OBJ)) {
			$rowCounter = $rowCounter + 1;
			echo '<tr id="inv_'.str_pad($r->ID, 6, '0', STR_PAD_LEFT).'"';
			if (!file_exists('public/pdf/invoices/'.str_pad($r->ID, 6, '0', STR_PAD_LEFT).'.pdf')) {
				echo ' class="missing_invoice"';
			};
			echo '>';
			echo '  <td style="text-align:right;">'.$rowCounter.'</td>';
			echo '  <td>'.str_pad($r->ID, 6, '0', STR_PAD_LEFT).'</td>';
			echo '  <td>'.$r->customer_order_number.'</td>';
			echo '  <td>'.$r->created.'</td>';
			echo '  <td style="text-align:right;">'.$r->price_inc_vat.'</td>';
			echo '  <td style="text-align:center;">';
			if (file_exists('public/pdf/invoices/'.str_pad($r->ID, 6, '0', STR_PAD_LEFT).'.pdf')) {
				echo '<i class="fa fa-check-circle" aria-hidden="true" style="color:#009900;"></i>';
			}
			else {
				echo '<i class="fa fa-times-circle" aria-hidden="true" style="color:#ff0000;"></i>';
			};
			echo '  </td>';
			echo '</tr>';
		};
		echo '</tbody>';
		echo '</table>';
	}
	
	public function view_invoice() {
		$sessionArray = $this->get_login_session();
		$orderId = "x";
		if (is_array($sessionArray)) {
			$customerId = $sessionArray[4];
			$query = $this->db->query("SELECT ID FROM tbl_orders WHERE customer_id = '".$customerId."' ORDER BY ID DESC LIMIT 0,1;");
			while ($r = $query->fetch(PDO::FETCH_OBJ)) {
				$orderId = str_pad($r->ID, 6, '0', STR_PAD_LEFT);
			};
			header("Content-Type: application/octet-stream");
			$file = $orderId.".pdf";
			$path = getcwd().'/public/pdf/invoices/';
			$fullfile = $path.$file;
			header("Content-Disposition: attachment; filename=" . Urlencode($file));   
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Description: File Transfer");            
			header("Content-Length: " . Filesize($fullfile));
			flush();
			$fp = fopen($fullfile, "r");
			while (!feof($fp)) {
				echo fread($fp, 65536);
				flush();
			} 
			fclose($fp);
		}
		else {
			header('Location: index');
		};
	}
	
	public function view_selected_invoice() {
		$sessionArray = $this->get_login_session();
		$orderId = "x";
		$customerId = "x";
		$forThisCustomer = "N";
		if (is_array($sessionArray)) {
			$customerId = $sessionArray[4];
			if (isset($_GET['order_id'])) {
				$orderId = $_GET['order_id'];
				$query = $this->db->query("SELECT COUNT(*) AS order_count FROM tbl_orders WHERE ID = '".(int)$orderId."' AND customer_id = '".$customerId."';");
				while ($r = $query->fetch(PDO::FETCH_OBJ)) {
					if ($r->order_count > 0) {
						$forThisCustomer = "Y";
						if (file_exists("public/pdf/invoices/".$orderId.".pdf")) {
							header("Content-Type: application/octet-stream");
							$file = $orderId.".pdf";
							$path = getcwd().'/public/pdf/invoices/';
							$fullfile = $path.$file;
							header("Content-Disposition: attachment; filename=" . Urlencode($file));   
							header("Content-Type: application/force-download");
							header("Content-Type: application/octet-stream");
							header("Content-Type: application/download");
							header("Content-Description: File Transfer");            
							header("Content-Length: " . Filesize($fullfile));
							flush();
							$fp = fopen($fullfile, "r");
							while (!feof($fp)) {
								echo fread($fp, 65536);
								flush();
							} 
							fclose($fp);
						}
					};
				};
			}
			else {
				header('Location: list_invoices');
			};
		}
		else {
			header('Location: index');	
		};
	}
	
	public function validate_email() {
		$email = $_GET['email'];
		if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
			echo '<i class="fa fa-check accept" aria-hidden="true"></i>';
		}
		else {
			echo '<i class="fa fa-close deny" aria-hidden="true"></i>';
		};
	}
	
	public function contact_form() {
		foreach ($_POST as $key => $value) {
			${$key} = filter_var($value, FILTER_SANITIZE_STRING);
		};
		$this->create_session();
		if ($_POST) {
			$postArray = $_POST;
			$postArray['status'] = 'success';
			$_SESSION['contact_fields'] = $postArray;
			$to = "bookshop@myriver.com";
			$message = "From: ".strtoupper($firstname)." ".strtoupper($lastname)."\n\nEmail: ".$email."\n\nTel: ".$phone."\n\nMessage:\n ".$message;
			$from = $email;
			$subject = "River Media Website Enquiry";
			$headers = "From: " .$name.'<'.$email.'>';
			mail($to,$subject,$message,$headers);
		}
		else {
			$_SESSION['contact_fields'] = array('firstname' => '', 'lastname' => '', 'phone' => '', 'email' => '', 'message' => '');
		};
	}
	
	public function copyright() {
		$thisdate = getdate(date("U"));
		$thisyear = "$thisdate[year]";
		$fromDate = '2016';
		echo '&copy; '.$fromDate;
		if ($thisyear > $fromDate) {
			echo ' - '.$thisyear;
		};
	}

}
