<?php


if (!isset($_POST['n']))
   return header('HTTP/1.0 400 Syntax error.');

// ================================================================
//                       Database interaction
// ================================================================

function query($sql, $query)
{
   $sql = $sql->query($query);
   if (!$sql)
   	die($sql->error);

   $rows = array();
   while($row = $sql->fetch_assoc())
      $rows[] = $row;

   print(json_encode($rows).'\n');
}

// ----------------------------------------------------------------

$cut = "";
if (isset($_POST['t']))
{
    $cut = $_POST['n'].' '.$_POST['t'];

    $d = new DateTime($cut);
    if ($d->format("His")<120000)
    {
        $d->add(new DateInterval('P1D'));  // PnYnMnDTnHnMnS
        $cut = $d->format("Y-m-d H:i:s");
    }

    $cut = " AND fStart>'".$cut."' ";
}

// ----------------------------------------------------------------

require_once 'config.php';

$sql = new mysqli($dbhost, $dbuser, $dbpass);

if ($sql->connect_error)
    die($sql->connect_error);

if (!$sql->select_db($dbname))
    die($sql->error);

/*mixed date_sunrise ( int $timestamp [, int $format = SUNFUNCS_RET_STRING [, float $latitude = ini_get("date.default_latitude") [, float $longitude = ini_get("date.default_longitude") [, float $zenith = ini_get("date.sunrise_zenith") [, float $gmt_offset = 0 ]]]]] )*/

query($sql, "SELECT DISTINCT(DATE(ADDTIME(fStart, '-12:00'))) AS 'd' FROM Schedule");
query($sql, "SELECT fSourceKEY AS 'key', fSourceName AS 'val' FROM Source WHERE fSourceTypeKEY=1");
query($sql, "SELECT fMeasurementTypeKEY AS 'key', fMeasurementTypeName AS 'val' FROM MeasurementType");
query($sql, "SELECT * FROM Schedule WHERE DATE(ADDTIME(fStart, '-12:00:00')) = '".$_POST['n']."'".$cut."ORDER BY fStart ASC, fMeasurementID ASC");

//sleep(3);

//print($test1."|".$test2."|".$test3."|SELECT * FROM Schedule WHERE DATE(ADDTIME(fStart, '-12:00:00')) = '".$_POST['day']."'".$cut."ORDER BY fScheduleID ASC, fMeasurementID ASC\n");

?>
