<?php
define('_FEXEC', 1);
require('includes/application_top.php');

/* ---------- HELPERS ---------- */

function ics_escape($s) {
  $s = (string)$s;
  $s = str_replace("\\", "\\\\", $s);
  $s = str_replace(";", "\;", $s);
  $s = str_replace(",", "\,", $s);
  $s = str_replace(["\r\n", "\n", "\r"], "\\n", $s);
  return $s;
}

function ics_line($name, $value) {
  $line = $name . ':' . $value;
  $out = '';
  while (strlen($line) > 75) {
    $out .= substr($line, 0, 75) . "\r\n" . ' ';
    $line = substr($line, 75);
  }
  return $out . $line . "\r\n";
}

/* ---------- SECURITY (logged in OR guest_last_order_id) ---------- */

if ($FREQUEST->getvalue('order_id')=="" || !is_numeric($FREQUEST->getvalue('order_id'))) {
  tep_redirect(tep_href_link(FILENAME_DEFAULT, '', 'SSL'));
  exit;
}

$order_id = (int)$FREQUEST->getvalue('order_id');

$isLoggedIn = $FSESSION->is_registered('customer_id');

$guest_last_order_id = (int)$FSESSION->get('guest_last_order_id');
$isGuestOk = ($guest_last_order_id > 0 && $guest_last_order_id === $order_id);

if (!$isLoggedIn && !$isGuestOk) {
  $navigation->set_snapshot();
  tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
  exit;
}

if ($isLoggedIn) {
  $customer_info_query = tep_db_query("
    SELECT customers_id
    FROM " . TABLE_ORDERS . "
    WHERE orders_id = '" . (int)$order_id . "'
    LIMIT 1
  ");
  $customer_info = tep_db_fetch_array($customer_info_query);

  if ((int)($customer_info['customers_id'] ?? 0) !== (int)$FSESSION->customer_id) {
    tep_redirect(tep_href_link(FILENAME_ACCOUNT_HISTORY, '', 'SSL'));
    exit;
  }
}

/* ---------- LOAD ALL PRODUCTS + EVENT ADDRESS FROM CATEGORY ---------- */
/*
  - orders_products.products_model: "12-06-2026 2000" (machine datetime)
  - orders_products.concert_date/time: pretty strings (optional)
  - categories_description.concert_address: official venue address
*/
$products_query = tep_db_query("
  SELECT
    op.orders_id,
    op.products_id,
    op.products_quantity,
    op.products_model,
    op.categories_name,
    op.events_id,
    op.concert_date,
    op.concert_time,
    op.concert_venue,
    cd.concert_address
  FROM " . TABLE_ORDERS_PRODUCTS . " op
  LEFT JOIN " . TABLE_CATEGORIES_DESCRIPTION . " cd
    ON cd.categories_id = op.events_id
   AND cd.language_id = " . (int)$languages_id . "
  WHERE op.orders_id = '" . (int)$order_id . "'
  ORDER BY op.products_id
");

$products = [];
while ($p = tep_db_fetch_array($products_query)) {
  $products[] = $p;
}

if (!$products) exit;

/* ---------- GROUP BY EVENT ---------- */

$events = [];

foreach ($products as $p) {
  $key = (int)($p['events_id'] ?? 0);
  if ($key <= 0) {
    $key = md5(
      (string)($p['products_model'] ?? '') .
      (string)($p['categories_name'] ?? '') .
      (string)($p['concert_venue'] ?? '') .
      (string)($p['concert_address'] ?? '')
    );
  }

  if (!isset($events[$key])) {
    $events[$key] = [
      'events_id'       => (int)($p['events_id'] ?? 0),
      'products_model'  => trim((string)($p['products_model'] ?? '')),
      'categories_name' => (string)($p['categories_name'] ?? ''),
      'concert_date'    => (string)($p['concert_date'] ?? ''),
      'concert_time'    => (string)($p['concert_time'] ?? ''),
      'concert_venue'   => (string)($p['concert_venue'] ?? ''),
      'concert_address' => (string)($p['concert_address'] ?? ''), // from categories_description
      'qty'             => 0
    ];
  }

  $events[$key]['qty'] += (int)($p['products_quantity'] ?? 0);
}

/* ---------- HEADERS ---------- */

$dtstamp  = gmdate('Ymd\THis\Z');
$timezone = (defined('STORE_TIMEZONE') && STORE_TIMEZONE) ? STORE_TIMEZONE : 'Europe/Berlin';

header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="Calender-' . $order_id . '.ics"');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

/* ---------- OUTPUT CALENDAR ---------- */

echo "BEGIN:VCALENDAR\r\n";
echo "VERSION:2.0\r\n";
echo ics_line("PRODID", ics_escape("Stars On Ice Tickets"));
echo "CALSCALE:GREGORIAN\r\n";
echo "METHOD:PUBLISH\r\n";

if ($timezone === 'Australia/Sydney') {
  echo "BEGIN:VTIMEZONE\r\n";
  echo "TZID:$timezone\r\n";
  echo "X-LIC-LOCATION:$timezone\r\n";
  echo "BEGIN:DAYLIGHT\r\n";
  echo "TZNAME:CEST\r\n";
  echo "TZOFFSETFROM:+0100\r\n";
  echo "TZOFFSETTO:+0200\r\n";
  echo "DTSTART:19700329T020000\r\n";
  echo "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\r\n";
  echo "END:DAYLIGHT\r\n";
  echo "BEGIN:STANDARD\r\n";
  echo "TZNAME:CET\r\n";
  echo "TZOFFSETFROM:+0200\r\n";
  echo "TZOFFSETTO:+0100\r\n";
  echo "DTSTART:19701025T030000\r\n";
  echo "RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\r\n";
  echo "END:STANDARD\r\n";
  echo "END:VTIMEZONE\r\n";
}

/* ---------- OUTPUT EVENTS ---------- */

foreach ($events as $idx => $e) {

  $model = trim((string)$e['products_model']); // "12-06-2026 2000"

  $dt = DateTime::createFromFormat('d-m-Y Hi', $model, new DateTimeZone($timezone));
  if (!$dt) {
    $dt = DateTime::createFromFormat('d-m-Y H:i', $model, new DateTimeZone($timezone));
  }
  if (!$dt) continue;

  $start = $dt;
  $end   = (clone $dt)->modify('+3 hours');

  $dtstart = $start->format('Ymd\THis');
  $dtend   = $end->format('Ymd\THis');

  $title = (string)$e['categories_name'];

  $prettyDate = trim((string)$e['concert_date']);
  $prettyTime = trim((string)$e['concert_time']);
  $whenLabel  = trim($prettyDate . ($prettyTime !== '' ? ' - ' . $prettyTime : ''));

  $addr = (string)($e['concert_address'] ?? '');
	$addr = str_replace(['\\,','\\;'], [',',';'], $addr);

	$locationParts = array_filter([
	  trim((string)$e['concert_venue']),
	  trim($addr)
	]);
	$location = implode(', ', $locationParts);
  
  $locationParts = array_filter([
    trim((string)$e['concert_venue']),
    trim((string)$e['concert_address']) // from categories_description
  ]);
  $location = implode(', ', $locationParts);

  $qty = (int)$e['qty'];
  $summary = $title . ' (' . $qty . ' ' . ITEM . ($qty === 1 ? '' : 's') . ')';

  $description = 'Tickets for "' . $title . '"';
  if ($whenLabel !== '') $description .= ' am ' . $whenLabel;
  if ($location !== '')  $description .= ' in ' . $location;

  $uid = 'osconcert-' . $order_id . '-' . $idx . '@' . ($_SERVER['HTTP_HOST'] ?? 'localhost');

  echo "BEGIN:VEVENT\r\n";
  echo "DTSTAMP:$dtstamp\r\n";
  echo ics_line("UID", ics_escape($uid));
  echo ics_line("DTSTART;TZID=" . $timezone, $dtstart);
  echo ics_line("DTEND;TZID=" . $timezone, $dtend);
  echo ics_line("SUMMARY", ics_escape($summary));
  echo ics_line("DESCRIPTION", ics_escape($description));
  if ($location !== '') {
    echo ics_line("LOCATION", ics_escape($location));
  }
  echo "END:VEVENT\r\n";
}

echo "END:VCALENDAR\r\n";
exit;