<?php

#require_once "../../../../config/pgsql_connect-ro.php";

require_once('../classes/database.php');
require_once('../classes/templateparser.php');

date_default_timezone_set('Europe/London');

/**
 * Checks to see if the array contains the keys in the array keys.
 *
 * @param array $array Array
 * @param array $keys  Keys to be in Array
 *
 * @return boolean $result true if the array has all the keys, otherwise false.
 */
function has_keys($array, $keys)
{
   $result = true;

   foreach($keys as $key) {
      $result &= array_key_exists($key, $array);
   }

   return $result;
}

/**
 * Render the page
 */
function displayPage()
{

   // Start session
   session_start();

   // If not authenticated by apache then send to 401, otherwise store the user in the session so its easier to access
   if(array_key_exists('REMOTE_USER', $_SERVER) == false) {
      header('HTTP/1.0 401 Unauthorized');
      exit;
   } else {
      $_SESSION['user'] = $_SERVER['REMOTE_USER'];
   }

   // Connect to the new AWESOME database
   $db = new ArsfDatabase();
   $db->connect();

   // Get all data the page needs to display
   $sensors          = $db->getAllDisplayedSensors();
   $pis              = $db->getAllPIs();
   $projects         = $db->getAllProjects();
   $status_page_data = $db->getStatusOrderPage();
   $progress_values  = $db->getAllStatuses();
   $priority_values  = $db->getAllPriorities();
   $progress_values  = $db->getAllProgress();
   $search_values    = null;

   $years  = $db->getYearRange();
   $months = array(1  => 'Jan', 2 => 'Feb',
                   3  => 'Mar', 4 => 'Apr',
                   5  => 'May', 6 => 'Jun',
                   7  => 'Jul', 8 => 'Aug',
                   9  => 'Sep', 10 => 'Oct',
                   11 => 'Nov', 12 => 'Dec');

   // Sort out filtering.
   if(isset($_POST) && has_keys($_POST, array('pi', 'project', 'start_day', 'start_month', 'start_year', 'end_day', 'end_month', 'end_year', 'exclude_proj'))) {
      $status_page_data = $db->getStatusOrderPageSorted($_POST);
      $search_values    = array('pi'           => $_POST['pi'], 'project' => $_POST['project'], 'start_day' => $_POST['start_day'], 'start_month' => $_POST['start_month'],
                                'start_year'   => $_POST['start_year'], 'end_day' => $_POST['end_day'], 'end_month' => $_POST['end_month'], 'end_year' => $_POST['end_year'],
                                'exclude_proj' => $_POST['exclude_proj']);
   }

   // Close the database
   $db->close();

   // Parse template
   $template = "templates/order_page.php";
   $parser   = new TemplateParser(get_defined_vars(), $template);
   $parser->render();
}

displayPage();



