<?php
error_reporting(E_ERROR);

// Define some constants
define('BASEDIR', dirname(__FILE__) . '/');
define('CONFIGDIR', BASEDIR . 'config');
define('APPDIR', BASEDIR . 'lib');
define('PAGEDIR', BASEDIR . 'pages');
define('UPLOADDIR', BASEDIR . 'tempuploads/');

// Get default registry settings
$settings = include_once CONFIGDIR . '/registry.php';

$__request_host_name = trim($_SERVER['SERVER_NAME'] ?? '');
if (empty($__request_host_name) || filter_var($__request_host_name, FILTER_VALIDATE_IP) !== false) {
  http_response_code(404);
  require_once PAGEDIR . '/404error.php';
  exit;
}

// Get domain-specific registry settings
$settings['SERVER_NAME'] = preg_replace('/[^\da-z.-]/i', '', $_SERVER['SERVER_NAME'] ?? '');
if (file_exists(CONFIGDIR . '/registry.' . $settings['SERVER_NAME'] . '.php')) {
  $settings = array_merge($settings, include_once CONFIGDIR . '/registry.' . $settings['SERVER_NAME'] . '.php');
}

date_default_timezone_set($settings['timezone'] ?? 'America/Chicago');
//require_once 'maintenance.html';
//exit;

// Make sure HTTPS connection
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
  header('Location: https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
  exit;
}

function convertDate($dbday)
{
  list($year, $month, $day) = explode('-', $dbday);
  return $month . '-' . $day . '-' . $year;
}

// Load Guest, Page, Database, and Log Classes
require_once APPDIR . '/vendor/autoload.php';
require_once APPDIR . '/Instructor.class.php';
require_once APPDIR . '/User.class.php';
require_once APPDIR . '/Guest.class.php';
require_once APPDIR . '/Database.class.php';
require_once APPDIR . '/Log.class.php';
require_once APPDIR . '/Email.class.php';
require_once APPDIR . '/Funcs.php';
require_once APPDIR . '/Staah.class.php';
$staah = new Staah();
$dbh = new Database();
if (!$dbh->connect()) {
  require_once 'maintenance.html';
  exit;
}
$webdb = new Database();
$webdb->connect('webdb');
$log = new Log();

// Replace any registry settings with DB version
$wsres = $webdb->query('SELECT * FROM public.settings');
if (!$wsres['error'] && $wsres['numrows']) {
  foreach ($wsres['data'] as $wsrow) {
    $settings[$wsrow['setting_name']] = $wsrow['setting_value'];
  }
}

// Start the Session
session_start();

// Get the page and query string they're requesting
$page = strtok($_SERVER['REQUEST_URI'], '?');
$querystring = strtok('?');
if (strlen($page) > 1 && substr($page, -1) == '/') {
  $page = substr($page, 0, -1);
}

// Set once on first page load
if (!isset($_SESSION['session_start_time'])) {
  $_SESSION['session_start_time'] = time();
}

// Load page details
$pagedetails = [];
$pageres = $webdb->query('SELECT *, COALESCE((SELECT string_agg(item_type_id::text, \',\') FROM public.page_item_types WHERE page_id = pages.page_id), \'0\') AS itemtypes FROM public.pages WHERE page_slug = ? AND page_enabled', [($page == '/buy' ? '/' : $page)]);
if (!$pageres['error'] && $pageres['numrows']) {
  $pagedetails = $pageres['data'][0];
}

foreach ($pagedetails as $key => $val) {
  // TODO utf8_decode() is deprecated in php 8.2 - check for other instances of utf8_decode() or utf8_encode()
  if (is_string($val)) {
    //$pagedetails[$key] = utf8_decode($val);
    $pagedetails[$key] = mb_convert_encoding($val, 'ISO-8859-1', mb_detect_encoding($val, 'UTF-8, ISO-8859-1'));
  }
}

// See if a user is logged in
if (isset($_SESSION['Guest'])) {
  $currentGuest = unserialize($_SESSION['Guest']);
  if (!in_array($page, ['/logout', '/login']) && $currentGuest->isTimedOut()) {

    // Guest has timed out, clear guest session info
    if ($currentGuest) {
      $currentGuest->logout();
    }
    if (isset($_SESSION['Guest'])) {
      unset($_SESSION['Guest']);
    }
  } else if (!in_array($page, ['/userprefs', '/logout']) && $currentGuest->passResetRequired()) {
    header('Location: /userprefs?r2p=' . urlencode($page) . '&qs=' . urlencode($querystring));
    exit;
  }
}

// See if in admin area
$currentUser = User::getCurrent();
if (substr($page, 0, 6) == '/admin') {
  $isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';

  // Not logged in and not on login page
  if ($page != '/admin/login' && empty($currentUser)) {
    if ($isAjax) {
      http_response_code(401);
      echo json_encode(['success' => false, 'error'   => 'You are not logged in. Please log in to continue.']);
    } else {
      header('Location: /admin/login?' . http_build_query(['r2p' => $page, 'qs' => !empty($querystring) ? $querystring : null]));
    }
    exit;
  }

  if (!empty($currentUser)) {

    // Password reset required
    if (
      !in_array($page, ['/admin/userprefs', '/admin/logout'], true)
      && $currentUser->passResetRequired()
    ) {
      header('Location: /admin/userprefs?' . http_build_query(['r2p' => $page, 'qs' => !empty($querystring) ? $querystring : null]));
      exit;
    }

    // Ajax permission error
    if (!empty($_GET['permissionerror']) && $isAjax) {
      http_response_code(403);
      echo json_encode(['success' => false, 'error'   => 'You do not have permission to perform this action.']);
      exit;
    }

    $permissions = $currentUser->getPermissions();
  }

  User::pruneExpiredTokens();
}

// See if in instructor portal area
if (substr($page, 0, 17) == '/instructorportal') {

  $currentInstructor = Instructor::getCurrent();

  // Not logged in and not on login page
  if ($page != '/instructorportal/login' && empty($currentInstructor)) {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
      http_response_code(401);
      echo json_encode(['success' => false, 'error' => 'You are not logged in. Please log in to continue.']);
    } else {

      header('Location: /instructorportal/login?' . http_build_query(['r2p' => $page, 'qs'  => !empty($querystring) ? $querystring : null]));
    }
    exit;
  }

  Instructor::pruneExpiredTokens();
}


// See if in rentalqueue area
if (substr($page, 0, 12) == '/rentalqueue') {
  require_once APPDIR . '/RentalQueueUser.class.php';
  $currentQueueUser = new RentalQueueUser();
  $queueUserResult = $currentQueueUser->verifyCookie();
  $currentUser = User::getCurrent();

  if ($page != '/rentalqueue/login' && empty($currentUser) && empty($queueUserResult)) {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
      http_response_code(401);
      echo json_encode(['success' => false, 'error' => 'You are not logged in. Please log in to continue.']);
    } else {
      header('Location: /rentalqueue/login?r2p=' . urlencode($page) . '&qs=' . urlencode($querystring));
    }
    exit;
  } elseif (!empty($_GET['permissionerror'])) {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
      http_response_code(403);
      echo json_encode(['success' => false, 'error' => 'You do not have permission to perform this action.']);
      exit;
    }
  }
}

// Remove old receipt info
if (isset($_SESSION['receiptdate'])) {
  $diff = $_SESSION['receiptdate']->diff(new DateTime());
  $diffinmin = $diff->days * 3600 + $diff->i;
  if ($diffinmin >= 60) {
    unset($_SESSION['receipt']);
    unset($_SESSION['receiptdate']);
    unset($_SESSION['receiptorderid']);
  }
}

// Save instructor names to session for prepopulating lesson modals
if (!empty($_GET['bookinstructor'])) {
  $_SESSION['bookinstructor'] = $_GET['bookinstructor'];
}

// Save campaign token to session
if (!empty($_GET['wptcmpgn']) && $_GET['wptcmpgn'] !== ($_SESSION['wptcmpgn'] ?? '')) {
  $result = $webdb->query(
    'SELECT ecr_id FROM public.email_campaign_recipients WHERE ecr_token = ?',
    [$_GET['wptcmpgn']]
  );
  if (!$result['error'] && $result['numrows']) {
    $_SESSION['wptcmpgn'] = $_GET['wptcmpgn'];
  }
}

// Figure out what page they want and load it
if ($page == '/') {
  // Show home page
  require_once PAGEDIR . '/buy.php';
} else if (preg_match('#^/instructors/([^/]+)$#', $page, $matches)) {
  $_REQUEST['instructor_slug'] = $matches[1];
  require_once PAGEDIR . '/instructors.php';
} else if (file_exists(PAGEDIR . $page . '.php')) {
  if (substr($page, 0, 6) == '/admin' && file_exists(PAGEDIR . $page . '.' . $settings['SERVER_NAME'] . '.php')) {
    // Load site-specific version
    require_once PAGEDIR . $page . '.' . $settings['SERVER_NAME'] . '.php';
  } else {
    // If page file exists
    require_once PAGEDIR . $page . '.php';
  }
} else if (!empty($pagedetails)) {

  if (!empty($pagedetails['page_external_url']) && filter_var($pagedetails['page_external_url'], FILTER_VALIDATE_URL)) {
    header('Location: ' . $pagedetails['page_external_url']);
    exit;
  }

  // Handle dynamic pages
  switch ($pagedetails['page_type']) {
    case 'Information Page':
      require_once BASEDIR . '/pagetemplates/information.php';
      break;
    case 'Ticket Calendar w/ Slots':
      require_once BASEDIR . '/pagetemplates/calendarslots.php';
      break;
    case 'Ticket Calendar':
      require_once BASEDIR . '/pagetemplates/calendar.php';
      break;
    case 'Ticket Calendar Promo':
      require_once BASEDIR . '/pagetemplates/calendarpromo.php';
      break;
    case 'Passholder/Membership':
      require_once BASEDIR . '/pagetemplates/passes.php';
      break;
    case 'Food/Beverages':
      require_once BASEDIR . '/pagetemplates/food.php';
      break;
    case 'Gift Card':
      require_once BASEDIR . '/pagetemplates/giftcard.php';
      break;
    case 'Registration':
      require_once BASEDIR . '/pagetemplates/registration.php';
      break;
    case 'Retail Items w/ Pics':
      require_once BASEDIR . '/pagetemplates/retail.php';
      break;
    case 'Standard Item List':
      require_once BASEDIR . '/pagetemplates/list.php';
      break;
    case 'Standard Item List Promo':
      require_once BASEDIR . '/pagetemplates/listpromo.php';
      break;
    case 'Lesson List':
      require_once BASEDIR . '/pagetemplates/lessonlist.php';
      break;
    case 'Lesson List By Class':
      require_once BASEDIR . '/pagetemplates/lessonlistbyclass.php';
      break;
    case 'Lesson Calendar':
      require_once BASEDIR . '/pagetemplates/lessoncalendar.php';
      break;
    case 'Lesson Calendar Condensed':
      require_once BASEDIR . '/pagetemplates/lessoncalendarcondensed.php';
      break;
    case 'Private Group':
      require_once BASEDIR . '/pagetemplates/privategroup.php';
      break;
    case 'Tee Time Calendar':
      require_once BASEDIR . '/pagetemplates/teetimecalendar.php';
      break;
    case 'Lodging Calendar':
      require_once BASEDIR . '/pagetemplates/lodgingcalendar.php';
      break;
    default:
      $log->error('404 Error: ' . $page);
      require_once PAGEDIR . '/404error.php';
      break;
  }
} else {
  // File not found
  $log->error('404 Error: ' . $page);
  require_once PAGEDIR . '/404error.php';
}

$dbh->close();
