<?php

date_default_timezone_set("America/New York");

require_once("../includes/php/config.php");
require_once("../includes/php/data.php");
require_once("../includes/php/functions.php");
require_once("../libraries/classes.php");

// Inputs: user, camera, time

// Set header
header('content-type: application/json');

$data = array();

$_GET['start'] = strtotime('midnight ' . date('m/d/Y', $_GET['start']));
$_GET['end'] = strtotime('midnight ' . date('m/d/Y', $_GET['end']));

//$_GET['start'] = strtotime(date('c', $_GET['start']));
//$_GET['end'] = strtotime(date('c', $_GET['end']));

// Validate post
if (empty($_GET['user'])) {
  $data['success'] = 0;
  $data['error'] = 'No user specified';
  die(json_encode($data));
}
if (empty($_GET['door'])) {
  $data['success'] = 0;
  $data['error'] = 'No camera specified';
  die(json_encode($data));
}

// Validate user
$user_information = select_record("users_key", $_GET['user'], "users", "users_id, users_first_name, users_last_name", $MASTER);

if (empty($user_information)) {
  $data['success'] = 0;
  $data['error'] = 'Invalid user';
  die(json_encode($data));
}

// Validate door
$door_information = select_record("doors_id", $_GET['door'], "doors", "doors_id, doors_unit, doors_unit_door, doors_default_mode", $MASTER);

if (empty($door_information)) {
  $data['success'] = 0;
  $data['error'] = 'Invalid door (1)';
  die(json_encode($data));
}

$user = new user($user_information['users_id']);

if (!$user->door_access($door_information['doors_id'])) {
  $data['success'] = 0;
  $data['error'] = 'Invalid door (2)';
  die(json_encode($data));
}

// Get unit
$unit_information = select_record('units_id', $door_information['doors_unit'], 'units', '*', $MASTER);

if (!$user->door_access($door_information['doors_id'])) {
  $data['success'] = 0;
  $data['error'] = 'Invalid unit';
  die(json_encode($data));
}

// Validation passed; retrieve schedule
$schedule = select_table('schedule', 'WHERE `schedule_unit`='.$unit_information['units_id'].' AND `schedule_door`='.$door_information['doors_unit_door'].' ORDER BY `schedule_priority` ASC', $MASTER);

if (empty($schedule)) {
  $data['success'] = 0;
  $data['error'] = 'No scheduled modes';
  die(json_encode($data));
}

$modes_temp = select_table('modes', 'WHERE `modes_scheduler`=1', $MASTER);
$modes = array();
foreach ($modes_temp as $mode) {
  $modes[$mode['modes_id']] = $mode['modes_label'];
}

$output_index = 1;
$output = array();
$full_schedule = array();
$times = array();
foreach ($schedule as $schedule_item) {
  ksort($times);
  // Determine start time
  switch ($schedule_item['schedule_repeat']) {
    case 'daily':
      $current_time = 0;
      $index = 0;
      while ($current_time < $_GET['end']) {
        if ($index == 0) {
          $day = 'today';
        } else {
          $day = $index.' days';
        }
        $index++;

        $start_time = $day . ' '.$schedule_item['schedule_start_hour'].':'.$schedule_item['schedule_start_minute'].':'.$schedule_item['schedule_start_second'];
        $end_time = $day . ' '.$schedule_item['schedule_end_hour'].':'.$schedule_item['schedule_end_minute'].':'.$schedule_item['schedule_end_second'];

        $start_timestamp = strtotime($start_time);
        $current_time = $start_timestamp;
        $end_timestamp = strtotime($end_time);

        if ($end_timestamp < $start_timestamp) {
          $end_timestamp = $end_timestamp + 86400;
        }

        if ($end_timestamp < $_GET['start']) {
          continue;
        }
        if ($start_timestamp > $_GET['end']) {
          break;
        }

        if (empty($times)) {
          $times[$start_timestamp] = $end_timestamp;

          $start_iso8601 = date('c', $start_timestamp);
          $end_iso8601 = date('c', $end_timestamp);

          $output[] = array(
            'id' => $output_index,
            'title' => $modes[$schedule_item['schedule_mode']],
            'start' => $start_iso8601,
            'end' => $end_iso8601,
            'allDay'=> false
          );
          $output_index++;
        } else {

          $continue = false;
          foreach ($times as $time_start => $time_end) {
            if (($start_timestamp > $time_start && $start_timestamp < $time_end) && ($end_timestamp > $time_start && $end_timestamp < $time_end)) {
              $continue = true;
              break;
            } else {
              if ($start_timestamp > $time_start && $start_timestamp <= $time_end) {
                $start_timestamp = $time_end + 1;
              }
              if ($end_timestamp >= $time_start && $end_timestamp < $time_end) {
                $end_timestamp = $time_start - 1;
              }
            }
          }
          if ($continue) {
            continue;
          }

          ksort($times);

          $current_start = 0;
          $current_index = 0;
          foreach ($times as $time_start => $time_end) {
            if ($time_end < $start_timestamp) {
              continue;
            }
            if ($current_start > $end_timestamp) {
              break;
            }
            if ($output_index == 0 && $time_start > $start_timestamp && empty($current_start)) {
              $current_start = $start_timestamp;
            }
            if (!empty($current_start)) {

              $start_iso8601 = date('c', $current_start);
              $end_iso8601 = date('c', $time_start - 1);

              $times[$current_start] = $time_start - 1;

              $output[] = array(
                'id' => $output_index,
                'title' => $modes[$schedule_item['schedule_mode']],
                'start' => $start_iso8601,
                'end' => $end_iso8601,
                'allDay'=> false
              );
              $output_index++;
            }
            $current_index++;
            $current_start = $time_end + 1;
          }

          // Check if time frame is already defined
          foreach ($times as $time_start => $time_end) {
            // Continue if time falls within a single scheduled object
            if (($start_timestamp > $time_start && $start_timestamp < $time_end) && ($end_timestamp > $time_start && $end_timestamp < $time_end)) {
              $continue = true;
              break;
            } else {
              if ($start_timestamp > $time_start && $start_timestamp <= $time_end) {
                $start_timestamp = $time_end + 1;
              }
              if ($end_timestamp >= $time_start && $end_timestamp < $time_end) {
                $end_timestamp = $time_start - 1;
              }
            }
          }
        }
      }
      break;
    case 'weekly':
      break;
    case 'monthly':
      break;
    case 'yearly':
      break;
    default:
      $start_time = $schedule_item['schedule_start_year'] .'-'.$schedule_item['schedule_start_month'] .'-'.$schedule_item['schedule_start_day'] . ' '.$schedule_item['schedule_start_hour'].':'.$schedule_item['schedule_start_minute'].':'.$schedule_item['schedule_start_second'];
      $end_time = $schedule_item['schedule_end_year'] .'-'.$schedule_item['schedule_end_month'] .'-'.$schedule_item['schedule_end_day'] . ' '.$schedule_item['schedule_end_hour'].':'.$schedule_item['schedule_end_minute'].':'.$schedule_item['schedule_end_second'];
      $start_timestamp = strtotime($start_time);

      $end_timestamp = strtotime($end_time);

      $continue = false;
      $item_times = array();

      // Check if time frame is already defined

      if (empty($times)) {
        $times[$start_timestamp] = $end_timestamp;


        $start_iso8601 = date('c', $start_timestamp);
        $end_iso8601 = date('c', $end_timestamp);

        $output[] = array(
          'id' => $output_index,
          'title' => $modes[$schedule_item['schedule_mode']],
          'start' => $start_iso8601,
          'end' => $end_iso8601,
          'allDay'=> false
        );
        $output_index++;
      } else {

        foreach ($times as $time_start => $time_end) {
          if (($start_timestamp > $time_start && $start_timestamp < $time_end) && ($end_timestamp > $time_start && $end_timestamp < $time_end)) {
            $continue = true;
            break;
          } else {
            if ($start_timestamp > $time_start && $start_timestamp <= $time_end) {
              $start_timestamp = $time_end + 1;
            }
            if ($end_timestamp >= $time_start && $end_timestamp < $time_end) {
              $end_timestamp = $time_start - 1;
            }
          }
        }

        ksort($times);

        $current_start = 0;
        foreach ($times as $time_start => $time_end) {
          if ($time_end < $start_timestamp) {
            continue;
          }
          if ($current_start > $end_timestamp) {
            break;
          }
          if ($output_index == 0 && $time_start > $start_timestamp && empty($current_start)) {
            $current_start = $start_timestamp;
          }
          if (!empty($current_start)) {

            $start_iso8601 = date('c', $current_start);
            $end_iso8601 = date('c', $time_start - 1);

            $times[$current_start] = $time_start - 1;

            $output[] = array(
              'id' => $output_index,
              'title' => $modes[$schedule_item['schedule_mode']],
              'start' => $start_iso8601,
              'end' => $end_iso8601,
              'allDay'=> false
            );
            $output_index++;
          }
          $current_start = $time_end + 1;
        }
      }

      break;
  }

}
// Loop through schedule to fill with default
$current_index = 0;
$current_start = 0;
ksort($times);
foreach ($times as $time_start => $time_end) {
  if ($current_index == 0 && $time_start > $_GET['start'] && empty($current_start)) {
    $current_start = $_GET['start'];
  }
  if ($current_start == $time_start) {
    $current_start = 0;
  }
  if (!empty($current_start)) {

    $start_iso8601 = date('c', $current_start);
    $end_iso8601 = date('c', $time_start - 1);

    $output[] = array(
      'id' => $output_index,
      'title' => $modes[$door_information['doors_default_mode']],
      'start' => $start_iso8601,
      'end' => $end_iso8601,
      'allDay'=> false
    );
  }
  $current_start = $time_end + 1;
  $output_index++;
  $current_index++;
}

if (!empty($output)) {
  die(json_encode($output));
}

?>