<?php
if($tpl['status'] == 'OK' && $tpl['event_arr']['status'] == 'T'):

    $ev = $tpl['event_arr'];

    $event_name        = isset($ev['title'])       ? $ev['title']       : '';
    $event_description = isset($ev['description']) ? $ev['description'] : '';
    $event_start       = isset($ev['start_date'])  ? $ev['start_date']  : '';
    $event_end         = isset($ev['end_date'])     ? $ev['end_date']   : $event_start;
    $event_id          = isset($_GET['id'])         ? (int)$_GET['id']  : 0;

    // Location fields — apne DB columns ke naam check karo
    $venue_name        = isset($ev['location'])         ? $ev['location']         : 'Cress Creeks Farm';
    $street_address    = isset($ev['address'])          ? $ev['address']          : '';
    $city              = isset($ev['city'])             ? $ev['city']             : '';
    $state             = isset($ev['state'])            ? $ev['state']            : '';
    $zip               = isset($ev['zip'])              ? $ev['zip']              : '';

    $event_url = 'https://cresscreeksfarm.com/events/preview.php?id=' . $event_id;

    $organizer_name = 'Cress Creeks Farm';
    $organizer_url  = 'https://cresscreeksfarm.com';

    $start_formatted = !empty($event_start)
        ? date('Y-m-d', strtotime($event_start))
        : '';

    $end_formatted = !empty($event_end)
        ? date('Y-m-d', strtotime($event_end))
        : $start_formatted;

    $schema_price      = 0;
    $schema_sale_start = $start_formatted;
    $schema_image_arr  = [];

    if(!empty($tpl['ticket_arr']))
    {
        foreach($tpl['ticket_arr'] as $t)
        {
            if($t['type'] == 'paid' && !empty($t['price']))
            {
                if($schema_price == 0 || (float)$t['price'] < $schema_price)
                {
                    $schema_price      = (float)$t['price'];
                    $schema_sale_start = isset($t['sale_start'])
                        ? date('Y-m-d\TH:i', strtotime($t['sale_start']))
                        : $start_formatted;
                }
            }

            if(!empty($t['thumbnail']))
            {
                $img_url = PJ_INSTALL_URL . $t['thumbnail'];
                $schema_image_arr[] = $img_url;
            }
        }
    }

    if(!empty($ev['thumbnail']))
    {
        array_unshift($schema_image_arr, PJ_INSTALL_URL . $ev['thumbnail']);
    }

    $schema_image_arr = array_unique($schema_image_arr);

    $availability = 'https://schema.org/InStock'; 
    $total_remaining = 0;
    if(!empty($tpl['ticket_arr']))
    {
        foreach($tpl['ticket_arr'] as $t)
        {
            $total_remaining += max(0, (int)$t['available_tickets'] - (int)$t['cnt_booked']);
        }
    }
    if($total_remaining <= 0)
    {
        $availability = 'https://schema.org/SoldOut';
    }

    $clean_description = strip_tags(stripslashes($event_description));
    $clean_description = str_replace(["\r\n", "\r", "\n"], ' ', $clean_description);
    $clean_description = json_encode(trim($clean_description));
   
?>
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Event",
  "name": <?php echo json_encode(stripslashes($event_name)); ?>,
  "startDate": "<?php echo $start_formatted; ?>",
  "endDate": "<?php echo $end_formatted; ?>",
  "eventStatus": "https://schema.org/EventScheduled",
  "eventAttendanceMode": "https://schema.org/OfflineEventAttendanceMode",
  "location": {
    "@type": "Place",
    "name": <?php echo json_encode(stripslashes($venue_name)); ?>,
    "address": {
      "@type": "PostalAddress",
      "streetAddress": <?php echo json_encode(stripslashes($street_address)); ?>,
      "addressLocality": <?php echo json_encode(stripslashes($city)); ?>,
      "postalCode": <?php echo json_encode($zip); ?>,
      "addressRegion": <?php echo json_encode($state); ?>,
      "addressCountry": "US"
    }
  },
  <?php if(!empty($schema_image_arr)): ?>
  "image": <?php echo json_encode(array_values($schema_image_arr)); ?>,
  <?php endif; ?>
  "description": <?php echo $clean_description; ?>,
  "offers": {
    "@type": "Offer",
    "url": "<?php echo $event_url; ?>",
    "price": <?php echo $schema_price; ?>,
    "priceCurrency": "<?php echo strtoupper($tpl['option_arr']['o_currency']); ?>",
    "availability": "<?php echo $availability; ?>",
    "validFrom": "<?php echo $schema_sale_start; ?>"
  },
  "organizer": {
    "@type": "Organization",
    "name": <?php echo json_encode($organizer_name); ?>,
    "url": "<?php echo $organizer_url; ?>"
  }
}
</script>
<?php
endif; 
?>
<?php

if($tpl['status'] == 'OK')
{
	if($tpl['event_arr']['status'] == 'T')
	{
		?>
		<div class="panel panel-default pjTbMain">
			<?php
			include_once dirname(__FILE__) . '/elements/header.php';
			
			if(!empty($tpl['ticket_arr']))
			{
				$STORE = @$_SESSION[$controller->defaultStore];
				$discount_store = isset($STORE['discount_data']) ? $STORE['discount_data'] : array();
				$ticket_donation = isset($STORE['tickets']) && isset($STORE['tickets']['donation']) ? $STORE['tickets']['donation'] : array();
				$ticket_store = isset($STORE['tickets']) && isset($STORE['tickets']['ticket_id']) ? $STORE['tickets']['ticket_id'] : array();
				$temp_ticket_id_arr = isset($discount_store['ticket_id_arr']) && !empty($discount_store['ticket_id_arr']) ? explode("~|~", $discount_store['ticket_id_arr']) : array();
				$ticket_id_arr = array();
				foreach($temp_ticket_id_arr as $k => $price_str)
				{
					list($ticket_id, $price, $price_format) = explode("~:~", $price_str);
					$ticket_id_arr[$ticket_id] = compact('price', 'price_format');
				}
				$discount_count = isset($discount_store['count']) ? $discount_store['count'] : -1;
				$code_msg = '';
				if(isset($STORE['discount_code']))
				{
					$code_msg = __('front_code_applied', true);
				}
				
				$ticket_available = false;
				foreach($tpl['ticket_arr'] as $k => $v)
				{
					$remaining_tickets = (int) $v['available_tickets'] - (int) $v['cnt_booked'];
					
					$ticket_sold = 'shown';
					if($remaining_tickets <= 0 && $v['tickets_sold'] == 'hide')
					{
						$ticket_sold = 'hide';
					}else if($remaining_tickets <= 0 && $v['tickets_sold'] == 'sold'){
						$ticket_sold = 'sold';
					}else if($remaining_tickets <= 0 && $v['tickets_sold'] == 'join'){
						$ticket_sold = 'join';
					}
					if($ticket_sold != 'hide')
					{
						$ticket_available = true;
					}
				}
				?>
				<form id="pjEtsTicketsForm_<?php echo $_GET['id'];?>" action="" method="post">
					<!--<h1 class="pjTbTicketTitle"><?php echo pjSanitize::html($v['title']);?></h1> -->
					<?php echo stripslashes($v['description']);?></p>
					<?php
					if($ticket_available == true)
					{ 
						?>	
						<div class="panel-body pjTbBody">
							<section class="pjTbSectionTickets">
								<?php
								if($tpl['cnt_codes'] > 0)
								{ 
									?>
									<header class="clearfix pjTbpjTbSectionHead">
										
										<div class="pull-right text-right pjTbSectionPromoCode">
											<a href="#pjTbPromoCode_<?php echo $_GET['id']?>" class="btn btn-link" role="button" data-pj-toggle="collapse" aria-expanded="false" aria-controls="pjTbPromoCode">
												<span class="glyphicon glyphicon-tag" aria-hidden="true"></span>
												<?php __('front_enter_promo_code');?>
											</a>
									
											<div class="form-group collapse" id="pjTbPromoCode_<?php echo $_GET['id']?>">
												<label id="pjEtsCodeMsg_<?php echo $_GET['id'];?>"><?php echo $code_msg;?></label>
												<input type="text" id="pjEtsDiscountCode_<?php echo $_GET['id']?>" name="discount_code" value="<?php echo isset($STORE['discount_code']) ? $STORE['discount_code'] : NULL;?>" class="form-control" />
												<a href="#" id="pjEtsApplyCode_<?php echo $_GET['id'];?>" class="pjEtsDiscountCode btn btn-link" style="display:<?php echo isset($STORE['discount_code']) ? 'none' : 'inline-block';?>;"><?php __('front_apply_code');?></a>
												<a href="#" id="pjEtsRemoveCode_<?php echo $_GET['id'];?>" class="pjEtsDiscountCode btn btn-link" style="display:<?php echo isset($STORE['discount_code']) ? 'inline-block' : 'none';?>;"><?php __('front_remove_code');?></a>
											</div><!-- /.form-group collapse -->
										</div><!-- /.pull-right text-right pjTbSectionPromoCode -->
									</header><!-- /.clearfix pjTbpjTbSectionHead -->
									<?php
								} 
								?>
							
							
								<div class="pjTbSectionBody">
									<ul class="list-unstyled pjTbTickets">
										<?php
										$total_tickets = 0;
										$total_price = 0;
										foreach($tpl['ticket_arr'] as $k => $v)
										{ 
											$remaining_tickets = (int) $v['available_tickets'] - (int) $v['cnt_booked'];
											
											$ticket_sold = 'shown';
											if($remaining_tickets <= 0 && $v['tickets_sold'] == 'hide')
											{
												$ticket_sold = 'hide';
											}else if($remaining_tickets <= 0 && $v['tickets_sold'] == 'sold'){
												$ticket_sold = 'sold';
											}else if($remaining_tickets <= 0 && $v['tickets_sold'] == 'join'){
												$ticket_sold = 'join';
											}
											if($ticket_sold != 'hide')
											{
													
												$sale_starts = date($tpl['option_arr']['o_date_format'], strtotime($v['sale_start'])) . ', ' . date($tpl['option_arr']['o_time_format'], strtotime($v['sale_start']));
												$sale_ends = date($tpl['option_arr']['o_date_format'], strtotime($v['sale_end'])) . ', ' . date($tpl['option_arr']['o_time_format'], strtotime($v['sale_end']));
												
												$ticket_types = __('ticket_types', true);
												$price = $v['price'];
												$ticket_meta_arr = array();
		
												if(isset($ticket_store[$v['id']]) && (int) $ticket_store[$v['id']] > 0)
												{
													$total_tickets += (int) $ticket_store[$v['id']];
													if($discount_count > 0 && (int) $ticket_store[$v['id']] >= $discount_count && isset($ticket_id_arr[$v['id']]))
													{
														$price = $ticket_id_arr[$v['id']]['price'];
													}
													if(isset($ticket_donation[$v['id']]))
													{
														$total_price += (int) $ticket_store[$v['id']] * (float) $ticket_donation[$v['id']];
													}else{
														$total_price += (int) $ticket_store[$v['id']] * $price;
													}
												}
												
												if($v['type'] == 'paid')
												{
													$ticket_meta_arr[] = '<span id="pjEtsPriceLabel_'.$v['id'].'">' . pjUtil::formatCurrencySign($price, $tpl['option_arr']['o_currency']) . '</span>';
												}else{
													$ticket_meta_arr[] = $ticket_types[$v['type']];
												}
												if($v['show_remain'] == 'yes')
												{
													$ticket_meta_arr[] = $remaining_tickets . ' ' . __('front_remaining', true);
												}
												
												?>
												<li class="pjTbTicket">
													<header class="clearfix pjTbTicketHead">
														<?php
														if($v['sale_end'] >= date('Y-m-d H:i:s'))
														{ 
															?>
															<aside class="pull-right pjTbTicketAside">
																<?php
																if($ticket_sold == 'sold')
																{ 
																	?>
																	<span class="badge pjTbTicketBadge pjTbTicketBadgeSold"><?php __('front_sold_out');?></span>
																	<?php
																}else if($ticket_sold == 'join'){
																	?>
																	<a href="#" class="btn btn-info pjEtsJoinWaitlist" data-event_id="<?php echo $v['event_id']?>" data-ticket_id="<?php echo $v['id']?>"><?php __('front_join_waitlist');?></a>
																	<?php
																}else{
																	if($v['hide_selector'] == 0)
																	{
																		if($v['type'] == 'donation')
																		{
																			?>
																			<div class="input-group pjTbTicketDonation">
																				<span class="input-group-addon"><?php echo pjUtil::getCurrencySign($tpl['option_arr']['o_currency'], false);?></span>
																				<input type="text" class="form-control text-right pjEtsDonation" id="pjEtsDonation_<?php echo $v['id'];?>" name="donation[<?php echo $v['id'];?>]" value="<?php echo isset($ticket_donation[$v['id']]) ? $ticket_donation[$v['id']] : NULL;?>"/>
																			</div><!-- /.input-group pjTbTicketDonation -->
																			<div class="pjTbTicketMultipleSign">x</div>
																			<?php
																		}
																		if($remaining_tickets > (int) $v['maximum_purchase'])
																		{
																			$remaining_tickets = (int) $v['maximum_purchase'];
																		}
																		?>
																		<select id="pjEtsTicketQty_<?php echo $v['id'];?>" 
																				name="ticket_id[<?php echo $v['id'];?>]" class="form-control pjEtsTicketQty" 
																				data-type="<?php echo $v['type'];?>" 
																				data-map="<?php echo !empty($tpl['event_arr']['map']) ? 'T' : 'F'; ?>" 
																				data-id="<?php echo $v['id'];?>" 
																				data-price="<?php echo $v['type'] == 'paid' && !empty($price) ? $price : 0;?>" 
																				data-apply="<?php echo isset($ticket_id_arr[$v['id']]) ? 'T' : 'F';?>"  
																				data-original_price="<?php echo $v['type'] == 'paid' && !empty($v['price']) ? $v['price'] : 0;?>" 
																				data-original_price_format="<?php echo $v['type'] == 'paid' && !empty($v['price']) ? pjUtil::formatCurrencySign($v['price'], $tpl['option_arr']['o_currency']) : 0;?>" >
																			<option value="0">0</option>
																			<?php
																			for($i = 1; $i <= $remaining_tickets; $i++)
																			{
																				?><option value="<?php echo $i;?>"<?php echo isset($ticket_store[$v['id']]) ? ($ticket_store[$v['id']] == $i ? ' selected="selected"' : NULL) : NULL;?>><?php echo $i;?></option><?php
																			} 
																			?>
																		</select>
																		<?php
																	} 
																} 
																?>
															</aside><!-- /.pull-right pjTbTicketAside -->
															<?php
														} 
														?>
														
														<div class="pull-left pjTbTicketHeadInner pjTbTicketHeadInnerFlex">
															<?php if(!empty($v['thumbnail']) && is_file(PJ_INSTALL_PATH . $v['thumbnail'])): ?>
															<div class="pjTbTicketThumbWrap">
																<img src="<?php echo PJ_INSTALL_URL . $v['thumbnail']; ?>" alt="<?php echo pjSanitize::html($v['title']); ?>" class="pjTbTicketThumb" />
															</div>
															<?php endif; ?>
															<div class="pjTbTicketHeadText">
																<?php
																if($v['show_sale_start'] == 'T')
																{ 
																	?>
																	<p class="pjTbSectionDate"><?php __('front_sale_starts_on');?> <?php echo $sale_starts;?></p><!-- /.pull-left pjTbSectionDate -->
																	<?php
																} 
																?>
																<p class="pjTbTicketTitle"><?php echo pjSanitize::html($v['title']);?></p><!-- /.pjTbTicketTitle -->
														
																<p class="pjTbTicketMeta"><?php echo implode(", ", $ticket_meta_arr);?></p><!-- /.pjTbTicketMeta -->
															</div><!-- /.pjTbTicketHeadText -->
														</div><!-- /.pull-left pjTbTicketHeadInner -->
													</header><!-- /.clearfix pjTbTicketHead -->
													
													<div class="pjTbTicketBody">
														<div class="collapse pjTbTicketContent" id="pjTbTicketContent_<?php echo $v['id'];?>">
															<!-- <p><?php echo nl2br(htmlspecialchars(stripslashes($v['description'])));?></p> -->
															<p><?php echo stripslashes($v['description']);?></p>
														</div><!-- /#pjTbTicketContent.collapse pjTbTicketContent1 -->
													
														<div class="clearfix pjTbTicketActions">
															<a href="#pjTbTicketContent_<?php echo $v['id'];?>" class="btn btn-link pull-left" role="button" data-pj-toggle="collapse" aria-expanded="false" aria-controls="pjTbTicketContent1">
																<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>More Details
															</a>
															<?php
															if($v['show_sale_end'] == 'T')
															{ 
																?>
																<p class="pull-right pjTbSectionDate"><?php __('front_sale_ends_on');?> <?php echo $sale_ends;?></p><!-- /.pull-right pjTbSectionDate -->
																<?php
															} 
															?>
														</div><!-- /.clearfix pjTbTicketActions -->
													</div><!-- /.pjTbTicketBody -->
												</li><!-- /.pjTbTicket -->
												<?php
											}
										} 
										?>
									</ul><!-- /.list-unstyled pjTbTickets -->
								</div><!-- /.pjTbSectionBody -->
							</section><!-- /.pjTbSectionTickets -->
						</div><!-- /.panel-body pjTbBody -->
						
						<div class="panel-body pjTbBody" style="display: none;"><p id="pjEtsTicketMsg_<?php echo $_GET['id']; ?>" class="text-danger"></p></div>
							
						<footer class="panel-footer clearfix pjTbFooter">
							<ul class="list-inline pull-left pjTbListTicketsInfo">
								<li>
									<dl class="dl-horizontal">
										<dt><?php __('front_selected_tickets');?>: </dt>
										<dd id="pjEtsSelectedTickets_<?php echo $_GET['id'];?>"><?php echo $total_tickets;?></dd>
									</dl><!-- /.dl-horizontal -->
								</li>
					
								<li>
									<dl class="dl-horizontal">
										<dt><?php __('front_price');?>: </dt>
										<dd id="pjEtsPrice_<?php echo $_GET['id'];?>"><?php echo pjUtil::formatCurrencySign(number_format($total_price, 2), $tpl['option_arr']['o_currency']);?></dd>
									</dl><!-- /.dl-horizontal -->
								</li>
							</ul><!-- /.list-inline pull-left pjTbListTicketsInfo -->
					
							<button type="submit" class="pull-right btn btn-primary"><?php __('front_btn_checkout');?></button>
						</footer><!-- /.panel-footer clearfix pjTbFooter -->
						<?php
					}else{
						?>
						<div class="panel-body pjTbBody"><?php __('front_no_tickets_available');?></div>
						<?php
					} 
					?>
				</form>
				
				<div class="modal fade pjTbModal pjTbModalJoinWaitlist" id="pjEtsModalJoinWaitlist_<?php echo $_GET['id'];?>" tabindex="-1" role="dialog" aria-labelledby="pjTbModalJoinWaitlistLabel">
					<div class="modal-dialog" role="document">
						<div class="modal-content">
							<header class="modal-header">
								<button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								</button>
	
								<p class="modal-title"><?php __('front_join_our_waitlist');?></p><!-- /.modal-title -->
							</header><!-- /.modal-header -->
	
							<div class="modal-body">
								<p><?php __('front_join_waitlist_desc');?></p>
	
								<div class="pjTbForm pjTbFormWatchList">
									<form id="pjEtsJoinForm_<?php echo $_GET['id'];?>" action="#" method="post">
										<input type="hidden" name="event_id" value=""/>
										<input type="hidden" name="ticket_id" value=""/>
										<div class="row">
											<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
												<div class="form-group">
													<label for=""><?php __('front_your_name');?>: </label>
													<input type="text" name="name" class="form-control required" data-msg-required="<?php __('front_field_required');?>"/>
													<div class="help-block with-errors"><ul class="list-unstyled"></ul></div>
												</div><!-- /.form-group -->
											</div><!-- /.col-lg-6 col-md-6 col-sm-6 col-xs-12 -->
	
											<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
												<div class="form-group">
													<label for=""><?php __('front_your_email');?>: </label>
													<input type="text" name="email" class="form-control required email" data-msg-required="<?php __('front_field_required');?>" data-msg-email="<?php __('front_invalid_email');?>"/>
													<div class="help-block with-errors"><ul class="list-unstyled"></ul></div>
												</div><!-- /.form-group -->
											</div><!-- /.col-lg-6 col-md-6 col-sm-6 col-xs-12 -->
										</div><!-- /.row -->
	
										<div class="form-group pjTbFormActions">
											<button type="submit" class="btn btn-primary"><?php __('front_btn_submit');?></button>
											<span id="pjEtsJoinMessage_<?php echo $_GET['id'];?>"></span>
										</div><!-- /.form-group pjTbFormActions -->
									</form>
								</div><!-- /.pjTbForm pjTbFormWatchList -->
							</div><!-- /.modal-body -->
						</div><!-- /.modal-content -->
					</div><!-- /.modal-dialog -->
				</div><!-- /#pjTbModalJoinWaitlist.modal fade pjTbModal pjTbModalJoinWaitlist -->
				
				<div class="modal fade pjTbModal pjTbModalJoinWaitlistConfirm" id="pjEtsModalJoinWaitlistConfirm_<?php echo $_GET['id'];?>" tabindex="-1" role="dialog" aria-labelledby="pjTbModalJoinWaitlistConfirmLabel">
					<div class="modal-dialog" role="document">
						<div class="modal-content">
							<header class="modal-header">
								<button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								</button>
	
								<p class="modal-title"><?php __('front_thank_you');?></p><!-- /.modal-title -->
							</header><!-- /.modal-header -->
	
							<div class="modal-body">
								<p><?php __('front_join_confirm_message');?></p>
								<br/>
								<div class="pjTbForm pjTbFormWatchList">
									<div class="form-group pjTbFormActions">
										<button type="button" class="btn btn-primary" data-dismiss="modal" aria-label="Close"><?php __('front_btn_close');?></button>
									</div><!-- /.form-group pjTbFormActions -->
								</div><!-- /.pjTbForm pjTbFormWatchList -->
							</div><!-- /.modal-body -->
						</div><!-- /.modal-content -->
					</div><!-- /.modal-dialog -->
				</div><!-- /#pjTbModalJoinWaitlist.modal fade pjTbModal pjTbModalJoinWaitlist -->
				<?php
			}else{
				?>
				<div class="pjTbSectionBody">
					<?php __('front_no_tickets_found');?>
				</div>
				<?php
			} 
			?>
		</div><!-- /.panel panel-default pjTbMain -->
		<?php
	}else{
		?>
		<div class="panel panel-default pjTbMain">
			<div class="panel-body pjTbBody">
				<?php __('front_event_not_available');?>
			</div>
		</div>
		<?php
	}
}else{
	?>
	<div class="panel panel-default pjTbMain">
		<div class="panel-body pjTbBody">
			<?php __('front_event_not_exist');?>
		</div>
	</div>
	<?php
}
?>