<?php
// include osConcert files
	define( '_FEXEC', 1 );
	require('includes/application_top.php');
// get list of orders lacking an entry in the barcode table that have a status = 3 i.e delivered
set_time_limit(0); 
$number_barcode = 0;
	
	        $check_query = tep_db_query("select orders.orders_id as orders_id from orders left join orders_barcode on orders.orders_id = orders_barcode.orders_id where  orders_barcode.orders_id is null and orders.orders_status = '3' ");
        if (tep_db_num_rows($check_query) < 1) {
			echo "Barcodes up to date";
			exit();
        } else {
			while($check = tep_db_fetch_array($check_query)){
				
				echo "Working on order #: " . $check['orders_id'] . "<br>";
				
			##### code adapted from products_ticket
				$order_sql="SELECT distinct c.customers_id,op.products_name,op.products_id,op.products_model,op.orders_products_id,op.products_price,op.final_price,op.events_type,o.date_purchased,op.discount_text,o.reference_id,op.categories_name,op.concert_venue,op.concert_date,op.concert_time,op.support_packs_type,o.orders_id,c.customers_firstname,c.customers_lastname,o.billing_name,o.payment_method,o.customers_name from " . 
				TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_CUSTOMERS . " c, " . TABLE_CUSTOMERS_TO_CUSTOMERS ." c2c ".
				" where o.customers_id=c2c.group_customer_id and c2c.customer_id=c.customers_id and c2c.orders_id=o.orders_id and o.orders_id = " . $check['orders_id'] . " and o.orders_id=op.orders_id and op.is_printable = 1" .
				" order by c.customers_id,o.orders_id,op.products_name";
	            $order_query=tep_db_query($order_sql);
				
				if (!(tep_db_num_rows($order_query))){ // and op.support_packs_type !='B'
				
				$order_sql="SELECT distinct 
				op.orders_products_id,
				op.products_id,
				o.reference_id,
				op.products_name,
				
				op.products_model,
				op.categories_name,
				o.date_purchased,
				op.concert_venue,
				op.concert_date,
				op.concert_time,
				op.events_type,
				o.orders_id,
				op.orders_products_id,
				op.products_price,
				op.final_price,
				op.discount_text,
				op.support_packs_type,
				o.customers_id,
				c.customers_firstname,
				c.customers_lastname,
				o.billing_name,
				o.payment_method,
				o.customers_name 
				from " . 
				TABLE_ORDERS . " o, 
				" . TABLE_ORDERS_PRODUCTS . " op, 
				" . TABLE_CUSTOMERS . " c " .
				" where 
				o.orders_id = " . $check['orders_id'] . " 
				and op.orders_id=o.orders_id 
				and o.customers_id=c.customers_id 
				 
				  and op.is_printable = 1" .
				" order by o.orders_id,op.products_name"; 
				$order_query=tep_db_query($order_sql);
				
				}
	        if (tep_db_num_rows($order_query) < 1) {
				echo "No matching products found";
				echo "<br>";
			}
	
			$details=array();
			$tickets=array();
			$cnt=1;
			$row=0;
			$prev_order=0;
			$prev_event=0;
			//$session_dates = "";
			$pre_cus_id=0;
			$date = array();
 
		while($order_result=tep_db_fetch_array($order_query)){
			
					$product_id=$order_result["products_id"];
					$orders_id=$order_result["orders_id"];
					$date_id=$order_result["products_model"];
					$orders_products_id=$order_result["orders_products_id"];
					$date_purchased=$order_result["date_purchased"];
					$events_type=$order_result["events_type"];
	
				############## individual tickets ###############
					//ORDERS PRODUCTS
					$qs=tep_db_query("SELECT * FROM  " . TABLE_ORDERS_PRODUCTS . "  WHERE orders_id = '". $orders_id ."' and products_id = '". $product_id ."' and orders_products_id='".$orders_products_id."'");
					$q=tep_db_fetch_array($qs);
					
					$quantity = $q['products_quantity'];
					$namez = $q['products_name'];
					$type = $q['support_packs_type'];
					//$date_id = $q['products_model'];
					$pricez = $q['products_price'];
					$final = $q['final_price'];
					$discount_text = $q['discount_text'];
					$discount_id = $q['discount_id'];
					$discount_type = $q['discount_type'];
					if(is_numeric($q['products_season'])){
					$season_quantity = (int)$q['products_season'];
					}else{
					$season_quantity = 0;
					}
			//if SPECIALS DISCOUNT is used -note eTicket
		if ( $discount_type == 'S')
		$special = $plus.'SPECIAL PRICE';
		else
		$special = '';
		//if SALEMAKER DISCOUNT is used -note eTicket
		$sms=tep_db_query("SELECT * FROM  " . TABLE_SALEMAKER_SALES . "  WHERE sale_id = '". $discount_id ."'");
		$sm=tep_db_fetch_array($sms);
		
		$choice_text=$sm['choice_text'];
		$discount_text = $plus.$choice_text;
		
		if($events_type=='F'){
		$ticket_type="FAMILY TICKET";	
		}
		
		if ($prev_order!=$orders_id){
			$cnt=1;
			if ($prev_order>0) $row=$row+1;
			$prev_order=$orders_id;
			$prev_event=0;
		}
		
		if ($prev_event!=$product_id){
			if (!isset($details[$product_id])){
		//Anything from the PRODUCTS tables? product query?
		$event_query=tep_db_query("SELECT p.products_model,p.manufacturers_id,pd.products_name,p.products_price from " . TABLE_PRODUCTS . " p left join " . TABLE_PRODUCTS_DESCRIPTION . " pd on p.products_id=pd.products_id  where p.products_id='" . $product_id . "' and pd.language_id='" . (int)$FSESSION->languages_id . "'"
										);
		$event_products=tep_db_fetch_array($event_query);	
		$manufacturers_id=$event_products["manufacturers_id"];
		
										
		$discount_query=tep_db_query("SELECT o.orders_id,cr.order_id FROM " . TABLE_ORDERS . " o,  " . TABLE_COUPON_REDEEM_TRACK . " cr WHERE o.orders_id=cr.order_id" . " order by o.orders_id");
		while ($discount=tep_db_fetch_array($discount_query) )
	    for ($i=0, $n=sizeof($discount); $i<$n; $i++) {
		$discount_id = $discount['orders_id'];
			if($orders_id == $discount_id) {
			$coupon_txt = "COUPON DISCOUNT";
			} else {
			$coupon_txt = "";
			}
		}		
		//get manufacturers details
		$manufacturers_query = tep_db_query("select manufacturers_name,manufacturers_image from ". TABLE_MANUFACTURERS." where manufacturers_id = '".$manufacturers_id."'");
		$manufacturers_result=tep_db_fetch_array($manufacturers_query);
		$manufacturers_name=$manufacturers_result["manufacturers_name"];
		$manufacturers_image=$manufacturers_result["manufacturers_image"];
		
		$server_date = date('Y-m-d',getServerDate(false));
		//date('Y-m-d H:i:s',getServerDate(false))
		//HERE we can get the data for categories
		$heading_name=$order_result["categories_name"];
		$heading_venue=$order_result["concert_venue"];
		$heading_date=$order_result["concert_date"];
		$heading_time=$order_result["concert_time"];
		$details[$product_id][TEXT_CHN]=$heading_name;
		$details[$product_id][TEXT_CCV]=$heading_venue;
		$details[$product_id][TEXT_CCD]=$heading_date;
		$details[$product_id][TEXT_CCT]=$heading_time;
		$details[$product_id][TEXT_CPM]=$date_id;
		$details[$product_id][TEXT_OID]=$orders_id;
		$details[$product_id][TEXT_PD]=$date_purchased;
		
		
		$tax_rate=tep_get_tax_rate(1);
		
		//$products_price = substr($order_result['final_price'],0,-2);
		$products_price=tep_add_tax(tep_get_plain_products_price($order_result['products_price']), $tax_rate);
		$d = '' . LEFT_SYMBOL . '';
		$details[$product_id][TEXT_CP1]=$products_price . ' ' . $ticket_type;
		$details[$product_id][TEXT_CP2]=$d;
		//$details[$product_id][TEXT_CDT]=$discount_text.' '.$special;//use discount_text for season ticket
		}
		$cnt=1;
		if ($prev_event>0) $row=$row+1;
		$prev_event=$product_id;
		}
		if ($cnt==1) {
		for ($i = 0; $i != $quantity; $i++) {
		//// this loop prints multiple GA Tickets
		$q = $i+1;
		$l="(";
		if($type=='F'){
		$r=" of " . FAMILY_TICKET_QTY . ")";
		}else{
		$r=")";
		}
		// season ticket shows here
		$season_text = '';
		if ($season_quantity > 0){
			//$season_text = " [Season Ticket Purchase] ";
			$season_text = SEASON_TICKET_PURCHASE;
			$season_quantity = $season_quantity - 1;
		}
			$details[$product_id][TEXT_CDT]= $season_text .$discount_text.' '.$special;
			
			$tickets[$row]["products_id"]=$product_id;
			$tickets[$row]["customers_id"]=$order_result["customers_id"];
			$tickets[$row]["orders_id"]=$orders_id;
			$tickets[$row]["customers_firstname"]=$order_result["customers_firstname"];
			$tickets[$row]["customers_lastname"]=$order_result["customers_lastname"];
			$tickets[$row]["customers_name"]=$order_result["customers_name"];
			$tickets[$row]["run"]=$q;
			$tickets[$row]["reference_id"]=$order_result["reference_id"];
			$tickets[$row]["products_model"]=$order_result["products_model"];
			$tickets[$row]["products_name"]=$order_result["products_name"];
			$tickets[$row]["concert_venue"]=$order_result["concert_venue"];
			$tickets[$row]["concert_date"]=$order_result["concert_date"];
			$tickets[$row]["concert_time"]=$order_result["concert_time"];
			$tickets[$row]["products_name"]=$order_result["products_name"];
			$tickets[$row]["customers_id"]=$order_result["customers_id"];
			############################## unique id
			if (function_exists(tep_create_unique_id)){
			// send the data to function order_id/order_products_id/quantity
				$tickets[$row]["unique_number"] = tep_create_unique_id( $orders_id, $product_id, $q );
			}
			#############################  unique_id ends
			if ($quantity == 1){
			   $tickets[$row]["run"]='_1';
			}else{
			   $tickets[$row]["run"]='_'.$q;
			   //Want an underscore or NOT?
			   //$tickets[$row]["run"]=$q;
			}
			$tickets[$row]["billing_name"]=$order_result["billing_name"];
			$tickets[$row]["payment_method"]=$order_result["payment_method"];
			//manufacturers name
			$tickets[$row]["manufacturers_name"]=$manufacturers_name;
			if ($i != $quantity) { $row++; }
			}
		}	
		$cnt=$cnt+1;
		if ($cnt>9){
			$row=$row+1;
			$cnt=1;
		}
		
				// print the ticket details
		$tickets = array_values($tickets);
		for ($tcnt=0;$tcnt<count($tickets);$tcnt++){
						$ticket=$tickets[$tcnt];
			            $event=$details[$ticket["products_id"]];
						
									$qr_text=$ticket["orders_id"] .'_'. $ticket["products_id"] . $ticket["run"];
		
				$products_id = (int)$ticket["products_id"];
				$showtime = $ticket["concert_date"].' '.$ticket["concert_time"];
				$products_name = $ticket["products_name"];
				$orders_id = (int)$ticket["orders_id"];
				//new for scan
				$order_data_query = tep_db_query("
				SELECT
					op.categories_name AS categories_name,
					op.concert_venue AS concert_venue
				FROM 
					" . TABLE_ORDERS_PRODUCTS . " op
				WHERE 
					op.orders_id = '". $orders_id . "'");
					
				$order_data = tep_db_fetch_array($order_data_query);
				$product_data_query=tep_db_query("SELECT
					op.products_model,
					op.products_name,
					op.products_price 
				from " . TABLE_ORDERS_PRODUCTS . " op where op.products_id='" . (int)$ticket["products_id"] . "'"
											);
				$product_data = tep_db_fetch_array($product_data_query);
					
				//save barcode
				$orders_barcode_query = tep_db_query("SELECT `barcode_id` FROM `orders_barcode` WHERE `orders_id` = '".$orders_id."' AND `products_id` = '".(int)$products_id."' AND `barcode` = '".tep_db_input($qr_text)."'");
				$orders_barcode = tep_db_fetch_array($orders_barcode_query);
				
				//var_dump($order_data);
				
				$JSON_BARCODE = json_encode(array_merge($ticket, $order_data, $product_data));
				$JSON_BARCODE = strtr($JSON_BARCODE, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
				$JSON_BARCODE = addslashes(stripslashes($JSON_BARCODE));
				
				if(NULL !== $orders_barcode && false !== $orders_barcode)
				{
					tep_db_query(sprintf("UPDATE `orders_barcode` SET `orders_id`='%d', `products_id`='%d',`showtime`='%s', `products_name`='%s',`barcode`='%s', `created`='%d', `data` = '%s' WHERE `barcode_id` = '%d'",
						(int)$orders_id,
						(int)$products_id,
						$showtime,
						$products_name,
						tep_db_input($qr_text),
						time(),
						$JSON_BARCODE,
						//json_encode(array_merge($ticket)),
						(int)$orders_barcode['barcode_id']
					));
				}
				else
				{
					tep_db_query(sprintf("INSERT INTO `orders_barcode`(`orders_id`, `products_id`,  `showtime`,`products_name`,`barcode`, `created`, `data`) VALUES ('%d','%d', '%s','%s', '%s', '%d', '%s');",
						(int)$orders_id,
						(int)$products_id,
						$showtime,
						$products_name,
						tep_db_input($qr_text),
						time(),
						$JSON_BARCODE
					));
				}
		
		}//end tccntg
		}// end while($order_result=tep_db_fetch_array($order_query)){
	
			}//end while
		}// end code