<?php
/*

  osConcert, Online Seat Booking 
  https://www.osconcert.com

  Copyright (c) 2009-2023 osConcert
  Released under the GNU General Public License
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	require('includes/application_top.php');
	// include currencies class and create an instance

	require_once('includes/classes/currencies.php');
	$currencies = new currencies();
	
	require(DIR_WS_INCLUDES . '/tweak/general.php');

	define('FPDF_FONTPATH','tfpdf/font/');
	require_once('tfpdf/tfpdf.php');
	tep_set_time_limit(100);
	
	//PlaceHolders
	define("TEXT_PN","Products Name");
	define("TEXT_PDS","Products Description");
	define("TEXT_OID","Order ID");
	define("TEXT_CPM","Concert ID");
	define("TEXT_RI","Ref ID");
	define("TEXT_PI","Prd ID");
	define("TEXT_DS","Coupon");
	define("TEXT_CPD","Prd Tax");
	define("TEXT_GAT","GA ID");//GA run
	define("TEXT_CP1","Concert Price");
	define("TEXT_PPP","Voucher Price");
	define("TEXT_PVC","Voucher Code");
	define("TEXT_CP2","Symbol");
	define("TEXT_CP3","Final Price");
	define("TEXT_CDT","Discount Type");
	define("TEXT_CST","Season Ticket");
	define("TEXT_BN","Billing Name");
	define("TEXT_THN","Ticketholder Name");
	define("TEXT_CUN","Customers Name");
	
	$order_id=$FGET['oID'];
	$found_results=false;
	$unit=72/25.4;
	$pos_left=5;
	$pos_top=5;
	$pos_width=$ticket_width;
	$pos_height=$ticket_height;
	// create the content and positions to be drawn 
	$content=array();
	// get the ticket details to be shown from the orders tables
	$order_sql = "
    SELECT 
	o.orders_id,
	o.currency,
	o.reference_id,
	c.customers_firstname,
	c.customers_lastname,
	o.customers_name,
	ov.voucher_id,
	ov.coupon_code,
	ov.coupon_amount,
	ov.products_name,
	ov.orders_products_id
    FROM " . TABLE_ORDERS . " o
    JOIN orders_vouchers ov ON o.orders_id = ov.orders_id
    JOIN " . TABLE_CUSTOMERS . " c ON o.customers_id = c.customers_id
    WHERE o.orders_id = $order_id
    ORDER BY ov.voucher_id ASC
";

	$order_query = tep_db_query($order_sql);
	$found_results = tep_db_num_rows($order_query) > 0;
	$tickets = [];
	$row = 0;

	while ($order_result = tep_db_fetch_array($order_query)) {
		$voucher_id = $order_result["voucher_id"];
		$products_name = $order_result["products_name"];
		$orders_products_id = $order_result["orders_products_id"];
		$coupon_code = $order_result["coupon_code"];
		$currency = $order_result["currency"];

		// No looping through quantity; each row is already a unique ticket
		if (function_exists('tep_create_unique_id')) {
			$tickets[$row]["unique_number"] = tep_create_unique_id($order_result["orders_id"], $voucher_id, 1);
		}

		$tickets[$row]["voucher_id"] = $voucher_id;
		$tickets[$row]["orders_id"] = $order_result["orders_id"];
		$tickets[$row]["products_name"] = $products_name;
		$tickets[$row]["orders_products_id"] = $orders_products_id;
		$tickets[$row]["coupon_code"] = $coupon_code;
		$tickets[$row]["coupon_amount"] = number_format($order_result["coupon_amount"], 2);
		$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]["reference_id"] = $order_result["reference_id"];
		
		$row++;  // Move to the next ticket entry
	}

	// Ensure tickets are sorted correctly before output
	usort($tickets, function ($a, $b) {
		return $a['voucher_id'] <=> $b['voucher_id'];
	});
	##################################################
	$symbol_left =  $currencies->get_symbol_left($currency);
	$symbol_right =  $currencies->get_symbol_right($currency);
	##################################################
	################################################################################################
	//We can only issue one ticket template 
	//...if the order is predomonatly a Gift Voucher give it a special template.
	if(!defined('TICKET_TEMPLATE'))
	{
	define('TICKET_TEMPLATE', '5');
	}

	
	$template_id=5;//TICKET_TEMPLATE;
	// get the template details if not found use default template
	$template_query=tep_db_query("SELECT template_id,template_width,template_height,template_type,template_content from " . TABLE_GENERAL_TEMPLATES . " where template_id='" . $template_id . "'");	
	//get the ticket type
	if (tep_db_num_rows($template_query)>0) 
	{
		$template_result=tep_db_fetch_array($template_query);
	}else 
	{
		$template_result=getVoucherDefaultTemplate();
	}
	$tic_type=$template_result['template_type'];
	//get the content
	$template_splt=preg_split("/{}/",$template_result["template_content"]);
	for ($icnt=0;$icnt<count($template_splt);$icnt=$icnt+2)
	{
		$key=$template_splt[$icnt];
		$template[$key]=$template_splt[$icnt+1];
	}
	//get the dimensions
	$ticket_width=$template_result["template_width"]*10;
	$ticket_height=$template_result["template_height"]*10;
	//get the format
	if(PAGE_FORMAT=="custom")
	{
	$resolution= array($ticket_width, $ticket_height);
	}else
	{
	$resolution	=PAGE_FORMAT;
	}
	
	// set page setup default width and height
	//$pdf=new tFPDF("l","mm",array($ticket_width,$ticket_height));
	$pdf = new tFPDF(ORIENTATION, "mm", $resolution, true, 'UTF-8', false);
	
	$pos_left=5;
	$pos_top=5;
	$pos_width=$ticket_width;
	$pos_height=$ticket_height;
	##########################################################################################

	if ($found_results)
	{
		//now do barcode stuffs
		require_once(DIR_FS_CATALOG_MODULES . "barcode/image.php");
		$bar_width=15;
		
		// print the ticket details
		$tickets = array_values($tickets);
		for ($tcnt=0;$tcnt<count($tickets);$tcnt++)
		{
			$ticket=$tickets[$tcnt];
			$event=$details[$ticket["voucher_id"]];
			$pdf->AddPage();
			$pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true);
			$pdf->AddFont('DejaVu','B','DejaVuSansCondensed-Bold.ttf',true);
			$pdf->SetFont('DejaVu','B',15); //13
			$pos_top=8; //8 from the top
			$pos_left=5;
			$event[TEXT_PVC] = $ticket["coupon_code"];
			$event[TEXT_FN] = $ticket["customers_firstname"];
			$event[TEXT_LN] = $ticket["customers_lastname"];
			$event[TEXT_CUN] = $ticket["customers_name"];
			$event[TEXT_RI] = $ticket["reference_id"];
			$event[TEXT_PI] = $ticket["orders_products_id"];	
			$event[TEXT_PN] = $ticket["products_name"];
			$event[TEXT_OID] = $ticket["orders_id"];

			if (!empty($symbol_right)) {				
				$event[TEXT_PPP] = number_format($ticket["coupon_amount"], 2) . $symbol_right;
			} elseif (!empty($symbol_left)) {	
				$event[TEXT_PPP] = $symbol_left . number_format($ticket["coupon_amount"], 2);
			}

			
				#############################################################
				//Ticket Image for each Category
				#############################################################
				$get_cat_id=tep_db_query("select categories_id from ". TABLE_PRODUCTS_TO_CATEGORIES ." where products_id='".$ticket["products_id"]."'");
				$got_id =tep_db_fetch_array($get_cat_id);
				$cat_id=$got_id['categories_id'];
				//got category id
				//We get the parent id where the category id is the same as the p2c category id
				$get_parent_id = tep_db_query("select * from ". TABLE_CATEGORIES ." where categories_id = '" . (int)$cat_id . "'");
				$got_parent_id =tep_db_fetch_array($get_parent_id);
				$parent_id=$got_parent_id['parent_id'];
				$cat_ticket_image=$got_parent_id['categories_image_2'];
				$get_parent_cat_id = tep_db_query("select * from ". TABLE_CATEGORIES ." where categories_id = '" . (int)$parent_id . "'");
				$got_parent_cat_id=tep_db_fetch_array($get_parent_cat_id);
				$parent_cat_id=$got_parent_cat_id['parent_id'];
				$parent_ticket_image=$got_parent_cat_id['categories_image_2'];
				
				$get_parent_parent_cat_id = tep_db_query("select * from ". TABLE_CATEGORIES ." where categories_id = '" . (int)$parent_cat_id . "'");
				$got_parent_parent_cat_id=tep_db_fetch_array($get_parent_parent_cat_id);
				$parent_parent_cat_id=$got_parent_parent_cat_id['parent_id'];
				$parent_parent_ticket_image=$got_parent_parent_cat_id['categories_image_2'];
	
				if ($cat_ticket_image!='')
				{
				$ticket_image=$cat_ticket_image;
				}
				elseif ($parent_ticket_image!='')
				{
				$ticket_image=$parent_ticket_image;
				}
				elseif ($parent_parent_ticket_image!='')
				{
				$ticket_image=$parent_parent_ticket_image;
				}else
				{
				//$ticket_image = in_array($sku, [6, 8]) ? DEFAULT_GIFT_VOUCHER_IMAGE : DEFAULT_TICKET_IMAGE;
				$ticket_image = 'gift_voucher.png';
				}
				###############################################################

				$tInfo=new objectInfo($template);
				
				if(tep_not_null($ticket_image))
				{
				$tInfo->shop_logo_image=DIR_FS_CATALOG_IMAGES . $ticket_image;
				}else
				{
				$tInfo->shop_logo_image=DIR_FS_CATALOG_IMAGES . $tInfo->shop_logo_image;
				}
		
					// get info of image
				if (file_exists($tInfo->shop_logo_image))
				{
					$info_shop=getimagesize($tInfo->shop_logo_image);
					$info_shop[0]=($info_shop[0]/$unit)*74/100;
					$info_shop[1]=($info_shop[1]/$unit)*74/100;
				}
				if (file_exists($tInfo->sponsor_logo_image))
				{
					$info_sponsor=getimagesize($tInfo->sponsor_logo_image);
					$info_sponsor[0]=($info_sponsor[0]/$unit)*114/100;
					$info_sponsor[1]=($info_sponsor[1]/$unit)*114/100;
				}
				// shop logo
				if (isset($info_shop)){
					if ($tInfo->shop_logo_position=="L")
					{
					$pdf->Image($tInfo->shop_logo_image,($tInfo->bar_image_position=="L"?$pos_left:BG_IMAGE_LEFT),BG_IMAGE_TOP,BG_IMAGE_WIDTH,BG_IMAGE_HEIGHT); //L,T,W,H//
					}else
					{
					$pdf->Image($tInfo->shop_logo_image,($tInfo->bar_image_position=="L"?$pos_width-$info_shop[0]:$pos_width-$info_shop[0]-BG_IMAGE_LEFT),BG_IMAGE_TOP,BG_IMAGE_WIDTH,BG_IMAGE_HEIGHT);
					}
				}
						##############################################################
				
				$top_font_size=TOP_FONT_SIZE;
				$pdf->SetFont('DejaVu','B',$top_font_size); //sets the font for TOP line (20)
				
				//event details MIDDLE
				$content=$tInfo->event_details_content;
				reset($event);
				foreach($event as $key1 => $value1) 	
				{
					//$placeholder;
					$content = str_replace("[[" . $key1  . "]]", $value1, $content);
					$content = str_replace("##" . $key1  . "##", $value1, $content);
				}
		
				$splt_line=preg_split("/\n/",$content);
				$temp_width=0;
				for ($icnt=0;$icnt<count($splt_line);$icnt++)
				{
					$str_width=$pdf->GetStringWidth($splt_line[$icnt]);
					if ($str_width>$temp_width)	$temp_width=$str_width;
				}
		
				if ($tInfo->event_details_position=="L")
				{
					$temp_left=$pos_left;
				}else 
				{
					$temp_left=$pos_width+20-$temp_width; //text from left margin when its set for position 'R'
				}
				$mid_font_size=MID_FONT_SIZE;
				for ($icnt=0;$icnt<count($splt_line);$icnt++)
				{
					if ($icnt>=1) 
					$pdf->SetFont('DejaVu','B',$mid_font_size); //size of MIDDLE written text (12)
					$pdf->Text($temp_left+15,$pos_top+10,$splt_line[$icnt]); 
					
					$pos_top+=MID_TEXT_SPACING; //spacing of the MIDDLE text 4
				}
				$pos_top+=8;
			
		
				// conditions BOTTOM
				$pdf->SetFont('DejaVu','B',BOTTOM_FONT_SIZE);
			
				$pos_top+=10;

				if (!isset($cond_splt))
				{
					$cond_height=0;
					$cond_splt=preg_split("/\n/",$tInfo->event_condition_content);
					$cond_height=count($cond_splt)*3;
					$cond_width=0;
					$temp_width=0;
					for ($icnt=0;$icnt<count($cond_splt);$icnt++)
					{
						$temp_width=$pdf->GetStringWidth($cond_splt[$icnt]);
						if ($temp_width>$cond_width) $cond_width=$temp_width;
					}
				}
				
				$temp_top=$ticket_height-$cond_height-3;
				if ($tInfo->event_condition_position=="L")
				{
					$cond_left=$temp_left+60; //position of BOTTOM text from left margin
				}else 
				{
					$cond_left=$ticket_width-$cond_width;
				}
				
				//event condition
				$content=$tInfo->event_condition_content;
				reset($event);
				foreach($event as $key1 => $value1)
				{
					$content = str_replace("[[" . $key1  . "]]", $value1, $content);
					$content = str_replace("##" . $key1  . "##", $value1, $content);
				}
		
				$splt_line=preg_split("/\n/",$content);
				$temp_width=0;
				for ($icnt=0;$icnt<count($splt_line);$icnt++)
				{
					$pdf->Text($cond_left,$temp_top,$splt_line[$icnt]);  
				}
		}//end  print the ticket details
	}else
	{
		$pdf->AddPage();
		$pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true);
		$pdf->AddFont('DejaVu','B','DejaVuSansCondensed-Bold.ttf',true);
		$pdf->SetFont('DejaVu','B',15); //13
		$pdf->Text(5,5,TEXT_NO_DETAILS_FOUND);
	}
	$voucher_tickets=sprintf("vouchers_%s_%s",$login_id,time());
	
	$pdf->output(DIR_FS_CATALOG . "images/vouchers/".$voucher_tickets.".pdf");
	tep_db_query("update  " . TABLE_ORDERS . "  set ticket_printed='Y' where orders_id = " . $order_id . "");
	tep_redirect(DIR_WS_CATALOG . "images/vouchers/".$voucher_tickets.".pdf");
	function &getVoucherDefaultTemplate()
	{
		$template_result=array(	"template_width"=>18.0000,
								"template_height"=>7.0000,
								"template_content"=>
								"shop_logo_image{}ticket.jpg{}shop_logo_position{}L{}event_details_content{}
								[[Voucher Code]] 
								Price: [[Voucher Price]]
								Voucher Ref: [[Ref ID]][[Order ID]]_[[Prd ID]]{}event_details_position{}L{}sponsor_logo_image{}sponsor_logo.png{}sponsor_logo_position{}R{}event_condition_content{}Not Refundable{}event_condition_position{}L{}bar_image_position{}
								R'"
								);
		return $template_result;
	}
?>