<?php 
/*
	osConcert Seat Booking Software
	https://www.osconcert.com
	Copyright (c) 2024 osConcert

	Released under the GNU General Public License 
*/	
// Check to ensure this file is included in osConcert!
	defined('_FEXEC') or die();
	require(DIR_WS_INCLUDES.'http.js'); ?>
	<?php echo tep_draw_form('order', tep_href_link(FILENAME_CHECKOUT_SUCCESS, 'action=update', 'SSL')); ?>
	<?php //box office refund 
	//we need an extra /form tag here so that the box office links work
	if($_SESSION['box_office_refund'])
	{
	echo '</form>';
	$FSESSION->remove('box_office_refund');
	}
?>
<div class="section-header">
  <h2>
    <?php
    // Default heading
    $heading = HEADING_TITLE;

    // 1) Refund path always wins
    if (isset($_GET['payment']) && $_GET['payment'] === 'box_office_refund') {
      $heading = HEADING_TITLE_REFUND;

    // 2) Otherwise, when order is status=1, decide based on product types
    } elseif ((int)$orders['orders_status'] === 1) {
      $hasM = false;
      $hasC = false;

      if (!empty($products_array) && is_array($products_array)) {
        foreach ($products_array as $p) {
          $t = isset($p['type']) ? $p['type'] : '';
          if ($t === 'M') { $hasM = true; }
          elseif ($t === 'C') { $hasC = true; }
        }
      }

      // Prefer M message if present, otherwise C, otherwise pending
      if ($hasM) {
        $heading = GIFT_VOUCHER_SUCCESS_M;
      } elseif ($hasC) {
        $heading = GIFT_VOUCHER_SUCCESS_C;
      } else {
        $heading = PENDING_HEADING_TITLE;
      }
    }

    echo $heading;
    ?>
  </h2>
</div>

<div class="index_static">
	<?php
	if ($messageStack->size('checkout_success') > 0) 
	{
	?>
		<div><?php echo $messageStack->output('checkout_success');?></div>
	<?php 
	}   
	?>

	<div><?php echo tep_image(DIR_WS_TEMPLATES . TEMPLATE_NAME . '/images/'.COMPANY_LOGO, '','',''); ?></div>

        <?php //box office refund
		if($_GET['payment']=='box_office_refund')		  
		{ 
		?>
            <br><strong><?php echo BOX_OFFICE_REFUND; ?></strong>
			<?php
					
			if (sizeof($products_array)>0)
			{
				echo '<strong>' . ORDER_LIST . '</strong><br>';
				$products_displayed = array();
				for ($i=0, $n=sizeof($products_array); $i<$n; $i++) 
				{
					if (!in_array($products_array[$i]['id'], $products_displayed)) 
					{
					echo $products_array[$i]['qty'] . ' x ' . $products_array[$i]['seat'] . ' [ ' . $products_array[$i]['date'] . '] : ' . $products_array[$i]['categories_name'] . ' - ' . $products_array[$i]['concert_date'].'- ' . $products_array[$i]['concert_time'].'<br>' ;
					}
				echo tep_draw_form('box_office_refund_start', 'index.php?' . tep_get_all_get_params($parameters)) . tep_draw_hidden_field('box_office_switch', 'no') . "<span onClick='document.forms[\"box_office_refund_start\"].submit()'>&nbsp;<button class=\"btn btn-primary btn-sm\">" . TEXT_LEGEND_REFUND_CANCEL . ":</button></span></form>";
				
				}
			}
  
		}else
		{


					echo '<h1>' . INVOICE . $FREQUEST->getvalue('order_id') .'</h1>';
					$date = strtotime($orders['date_purchased']);
					$thedate=date('M d, Y', $date);
					//echo '<h4 style="margin-left:15px;">' . $thedate . '</h4></div>';

			$pdfdelivered_query = tep_db_query("select osh.orders_status_history_id, osh.orders_status_id from " . TABLE_ORDERS_STATUS_HISTORY . " osh where osh.orders_id = '". (int)$FREQUEST->getvalue('order_id') . "' order by orders_status_history_id desc limit 1");
			$pdfdelivered_status = tep_db_fetch_array($pdfdelivered_query);

			if ($pdfdelivered_status['orders_status_id'] == 3 && DISPLAY_PDF_DELIVERED_ONLY == 'true')
			{
			echo '<a target="_blank" href="' . tep_href_link('pdfinvoice.php', 'oID=' . $FREQUEST->getvalue('order_id') , 'SSL') . '">' . tep_template_image_button_basic('', IMAGE_BUTTON_PRINT_ORDER) . '</a>';
			}elseif ($pdfdelivered_status['orders_status_id'] == 1 && DISPLAY_PDF_DELIVERED_ONLY == 'true'){
				
			if($payment=='bank_transfer'){
			require(DIR_WS_LANGUAGES . $FSESSION->language . '/modules/payment/bank_transfer.php');
			echo MODULE_BANK_TRANSFER_INFO;
			}
			}
			?>
			<br class="clearfloat">
			<?php

				if (sizeof($products_array)>0)
				{
					echo '<br><h2>' . ORDER_LIST . '</h2>';
					
					//echo '<br>'.$order_total_amount.'<br>';
					$products_displayed = array();
					$order_is_printable = 0;
					for ($i=0, $n=sizeof($products_array); $i<$n; $i++) 
					{
						if (!in_array($products_array[$i]['id'], $products_displayed)) 
						{
							
							//sort a family ticket
							if(!defined('SET_OF_FAMILY'))
							{
							define('SET_OF_FAMILY', 'Set of ');
							}	
							if($products_array[$i]['type']=='F')
							{
							$qty_times=$products_array[$i]['qty'] . ' x ' . SET_OF_FAMILY . '  '. FAMILY_TICKET_QTY .' ';
							}else
							{
							$qty_times=$products_array[$i]['qty'] . ' x ';
							}
							$cPathNow=$products_array[$i]['events_id'];
							$url=tep_href_link(FILENAME_DEFAULT, 'cPath='.$cPathNow.'');
						
							echo 
							$qty_times . '<b><a href="' . $url . '">' . 
							$products_array[$i]['categories_name'] . '</b>  ' . 
							$products_array[$i]['concert_date'] . '  ' .
							$products_array[$i]['concert_time'] . '  ' .							
							$products_array[$i]['seat'] . '</a><br>' ;
							
	
						}
						$order_is_printable = $order_is_printable + $products_array[$i]['is_printable'];
					}
				}
			
				?>
						<br><strong><?php echo TEXT_THANKS_FOR_SHOPPING; ?></strong><br>
<?php
$venue_address = '';

$venue_query = tep_db_query("
  SELECT 
    cd.concert_venue,
    cd.concert_address
  FROM " . TABLE_ORDERS_PRODUCTS . " op
  INNER JOIN " . TABLE_CATEGORIES_DESCRIPTION . " cd
    ON cd.categories_id = op.events_id
   AND cd.language_id = " . (int)$languages_id . "
  WHERE op.orders_id = '" . (int)$FREQUEST->getvalue('order_id') . "'
  LIMIT 1
");

if ($venue = tep_db_fetch_array($venue_query)) {
  $venue_address = trim(
    $venue['concert_venue'] .
    (!empty($venue['concert_address']) ? ', ' . $venue['concert_address'] : '')
  );
}



$orderId   = (int)($orders['orders_id'] ?? 0);
$icsUrl    = tep_href_link('download_ics.php', 'order_id='.$FREQUEST->getvalue('order_id'));

// Use your real venue variables if you have them
$venueText = $venue_address; //'Theater am Insulaner Berlin';
$mapsUrl   = 'https://www.google.com/maps/search/?api=1&query=' . urlencode($venueText);
?>
<div class="d-grid gap-2 d-md-flex justify-content-md-start">
  <a class="btn btn-primary btn-sm d-inline-flex align-items-center gap-2"
     href="<?php echo htmlspecialchars($icsUrl, ENT_QUOTES); ?>">
    <i class="bi bi-calendar-plus"></i> <?php echo TEXT_ADDTO_CALENDAR; ?> <span class="opacity-75">(.ics)</span>
  </a>
<?php if (GET_DIRECTIONS_ENABLE==='true'){ ?>
  <a class="btn btn-outline-secondary btn-sm d-inline-flex align-items-center gap-2"
     href="<?php echo htmlspecialchars($mapsUrl, ENT_QUOTES); ?>"
     target="_blank" rel="noopener">
    <i class="bi bi-map"></i> <?php echo TEXT_GET_DIRECTIONS; ?>
  </a>
<?php } ?>
</div>
<br>
		<?php
		}
		?>

		<?php 
			$order_status_query = tep_db_query("select orders_status from " . TABLE_ORDERS . " where orders_id = '" . (int)$FREQUEST->getvalue('order_id') . "'");
			$order_status = tep_db_fetch_array($order_status_query); 	
			if(($order_status['orders_status'])==3)
			{
			if (DOWNLOAD_ENABLED == 'true') 
				include(DIR_WS_MODULES . 'downloads.php'); 
			}
        ?>

<?php
$target = " target='_blank'";
$order_id = (int)$FREQUEST->getvalue('order_id');

// Fetch delivered status
$delivered_query = tep_db_query(
    "SELECT MAX(osh.date_added) AS los, osh.orders_status_history_id, osh.orders_status_id 
     FROM " . TABLE_ORDERS_STATUS_HISTORY . " osh 
     WHERE osh.orders_id = '$order_id' 
     GROUP BY osh.orders_status_id, osh.orders_status_history_id 
     ORDER BY orders_status_history_id DESC 
     LIMIT 1"
);
$delivered_status = tep_db_fetch_array($delivered_query);

// Determine if e-tickets are available
$e_tickets_enabled = (E_TICKETS == 'true');
$order_is_delivered = ($delivered_status['orders_status_id'] == E_TICKET_STATUS);
$display_pdf_delivered_only = (DISPLAY_PDF_DELIVERED_ONLY == 'true');

// Flags to track buttons
$voucher_button_shown = false;
$ticket_button_shown = false;

// Generate buttons based on SKUs
if ($e_tickets_enabled && $order_is_printable > 0 && $order_is_delivered && $display_pdf_delivered_only) {
    foreach ($products_array as $product) {
        // Check for voucher products (SKU 6 or 8)
        if (in_array($product['sku'], ['6', '8']) && !$voucher_button_shown) {
            generateButton(
                GET_VOUCHERS_HERE,
                tep_href_link(FILENAME_VOUCHER_PDF, 'oID=' . $order_id . '&customer_id=' . $customer_number['customers_id'], 'SSL')
            );
            $voucher_button_shown = true; // Mark voucher button as shown
        }

        // Check for ticket products (SKU 1 or 9)
        if (in_array($product['sku'], ['1', '9']) && !$ticket_button_shown) {
            generateButton(
                GET_TICKETS_HERE,
                tep_href_link(FILENAME_CUSTOMER_PDF, 'oID=' . $order_id . '&customer_id=' . $customer_number['customers_id'], 'SSL')
            );
            $ticket_button_shown = true; // Mark ticket button as shown
        }
    }
}

// Function to generate button HTML
function generateButton($label, $url) {
    echo "<div align='center'>
            <input type='button' class='btn btn-primary btn-lg' value='$label' onclick=\"window.open('$url')\">
          </div>";
}

?>

			<br>
			<div>
			<?php 
			if  (DISPLAY_PDF_DELIVERED_ONLY == 'false'){//if it's set at 'Pending' we tell them 
				if ($guest==1)
				{
				echo MESSAGE3 . ' '. $user;
				}else
				{
				echo MESSAGE2;	
				}
			}else
			{
				if ($guest==1)
				{
				echo MESSAGE3 . ' '. $user . ' ' . $log_page;//if PWA 
				}else
				{
				echo MESSAGE2;	
				}
			}
			?>
			</div>
			
			<div>
			<?php
			//Social networking
			if (SOCIAL_NETWORKING=='yes')
			{
			require(DIR_WS_INCLUDES.'social_networking.php');
			}
			?>
			</div>
            
			<?php
			//CCGV FOR ORDER_TOTAL CREDIT SYSTEM - Start Addition
			$gv_query=tep_db_query("select amount from " . TABLE_COUPON_GV_CUSTOMER . " where customer_id='" . (int)$customer_id . "'");
			if ($gv_result=tep_db_fetch_array($gv_query)) 
			{
				if ($gv_result['amount'] > 0) 
				{
				?>
			<div>
			<?php echo GV_HAS_VOUCHERA; echo tep_href_link(FILENAME_GV_SEND); echo GV_HAS_VOUCHERB; ?>
			</div>
			<?php
				}
			}
			//CCGV ADDED FOR ORDER_TOTAL CREDIT SYSTEM - End Addition
			?>

	<div class="d-flex justify-content-end">
	  <?php 
	  if ($guest == 1) {
		  // echo '<a href="' . tep_href_link(FILENAME_LOGOFF) . '">' . tep_template_image_button_basic('', IMAGE_BUTTON_CONTINUE) . '</a>'; 
	  } else {
		  echo '<a href="' . tep_href_link(FILENAME_DEFAULT) . '">' . tep_template_image_button_basic('', IMAGE_BUTTON_CONTINUE) . '</a>'; 
	  }
	  ?>
	</div>
<?php
$order_id = (int)$FREQUEST->getvalue('order_id');
$is_refund = (isset($_GET['payment']) && $_GET['payment'] === 'box_office_refund');

$tracking_enabled = (defined('OSC_TRACKING_ENABLE') && OSC_TRACKING_ENABLE === 'true');
$meta_pixel_id    = (defined('OSC_META_PIXEL_ID') ? trim(OSC_META_PIXEL_ID) : '');

// Final total from ot_total
$order_total_value = 0.00;
if ($order_id > 0) {
  $q = tep_db_query("
    SELECT value
    FROM " . TABLE_ORDERS_TOTAL . "
    WHERE orders_id = '" . (int)$order_id . "'
      AND class = 'ot_total'
    LIMIT 1
  ");
  if ($r = tep_db_fetch_array($q)) {
    $order_total_value = (float)$r['value'];
  }
}

$can_track = ($tracking_enabled && !$is_refund && $order_id > 0 && $order_total_value > 0);

if ($can_track):
?>
<script>
  // 1) For Google (via GTM)
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'osc_purchase',
    transaction_id: <?php echo json_encode((string)$order_id); ?>,
    value: <?php echo json_encode($order_total_value); ?>,
    currency: 'EUR'
  });
</script>

<?php if ($meta_pixel_id !== ''): ?>
<script>
  // 2) For Meta (direct pixel, NOT GTM)
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');

  fbq('init', <?php echo json_encode($meta_pixel_id); ?>);
  fbq('track', 'Purchase', { value: <?php echo json_encode($order_total_value); ?>, currency: 'EUR' });
</script>
<?php endif; ?>

<?php endif; ?>


	  <div class="bs-stepper">
            <div class="bs-stepper-header">
              <div class="step" data-target="#delivery">
                <button type="button" class="btn step-trigger"  disabled="disabled">
                  <span class="bs-stepper-circle">1</span>
                  <span class="bs-stepper-label"><?php echo CHECKOUT_BAR_DELIVERY; ?></span>
                </button>
              </div>
              <div class="line"></div>
              <div class="step" data-target="#payment">
                <button type="button" class="btn step-trigger"  disabled="disabled">
                  <span class="bs-stepper-circle">2</span>
                  <span class="bs-stepper-label"><?php echo CHECKOUT_BAR_PAYMENT; ?></span>
                </button>
              </div>
              <div class="line"></div>
              <div class="step active" data-target="#confirm">
                <button type="button" class="btn step-trigger" disabled="disabled">
                  <span class="bs-stepper-circle">3</span>
                  <span class="bs-stepper-label"><?php echo CHECKOUT_BAR_CONFIRMATION; ?></span>
                </button>
              </div>
            </div>
          </div></form>
<?php
echo '<!-- tracking enable defined=' . (defined('OSC_TRACKING_ENABLE') ? 'yes' : 'no') . ' value=' . (defined('OSC_TRACKING_ENABLE') ? OSC_TRACKING_ENABLE : 'n/a') . ' -->';
?>
