<?php

//--------------------------------------------------------------------------------------------------
// This script reads event data from a JSON file and outputs those events which are within the range
// supplied by the "start" and "end" GET parameters.
//
// An optional "timeZone" GET parameter will force all ISO8601 date stings to a given timeZone.
//
// Requires PHP 5.2.0 or higher.
//--------------------------------------------------------------------------------------------------

// Require our Event class and datetime utilities
require dirname(__FILE__) . '/utils.php';

// Short-circuit if the client did not give us a date range.
if (!isset($_GET['start']) || !isset($_GET['end'])) {
  ; //die("Please provide a date range.");
  $range_start = new DateTime();
  $range_end = new DateTime(); 
}
else {
// Parse the start/end parameters.
// These are assumed to be ISO8601 strings with no time nor timeZone, like "2013-12-29".
// Since no timeZone will be present, they will parsed as UTC.
	$range_start = parseDateTime($_GET['start']);
	$range_end = parseDateTime($_GET['end']);
}

// Parse the timeZone parameter if it is present.
	$time_zone = new DateTimeZone('Europe/Rome');
	if (isset($_GET['timeZone'])) {
	  $time_zone = new DateTimeZone($_GET['timeZone']);
	}

	$id = isset($_GET['id']) ? $_GET['id'] : '';

    $data = array();
    
    //database details
    $dbHost     = 'localhost';
    $dbUsername = 'root';
    $dbPassword = '';
    $dbName     = 'prenotazioni';
    
    //create connection and select DB
    $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
    if($db->connect_error){
        die("Unable to connect database: " . $db->connect_error);
    }
    
    //get user data from the database
	if ($id == '') {
		$query = $db->query("SELECT id,title as title,start,end,allday as allDay, color as backgroundColor FROM test");
	}
	else {
		//echo "ID = ".$id;
		$query = $db->query("SELECT id,title as title,start,end,allday as allDay, color as backgroundColor, descr, type FROM test WHERE id = " . $id);
	}

    if($query->num_rows > 0){
	    while($row = $query->fetch_assoc()) {
			array_push($data, $row);
		}
		$json = json_encode($data);	

		$input_arrays = json_decode($json, true);

		// Accumulate an output array of event data arrays.
		$output_arrays = array();
		foreach ($input_arrays as $array) {

		  // Convert the input array into a useful Event object
		  $event = new Event($array, $time_zone);

		  // If the event is in-bounds, add it to the output
		  if (true || $event->isWithinDayRange($range_start, $range_end)) {
			$output_arrays[] = $event->toArray();
		  }
		}
		echo json_encode($output_arrays);
		
    } else {
        $data['status'] = 'KO';
		echo json_encode($data);
    }
	
