<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');

$login_id = $_SESSION['login'];

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "fkid")
    $pr_id = $paramValue;
  if ($paramName == "id")
    $pw_id = $paramValue;
  else if ($paramName == "projectparcel_id")
    $pp_id = $paramValue;
  elseif ($paramName == "date")
    $date = $paramValue;
  elseif ($paramName == "startime") 
    $startime = $paramValue;  
  elseif ($paramName == "stoptime") 
    $stoptime = $paramValue;  
}

$result = [0, ""];  

if ($startime >= $stoptime)
  $result= [1, "Start > End"];

else {  

  $dal = new DAL();
  // Get ids to store in Session
  $sql = "SELECT PW.id, PW.startime, PW.stoptime, WO.textdate " . 
         "FROM projectworkevent PW, workday WO " .
         "WHERE PW.id <> $pw_id AND PW.login_id = $login_id " .
         "AND PW.projectparcel_id = $pp_id " .
         "AND PW.workday_id = WO.id AND WO.date = '$date' " ;
  $projectworkevents = $dal->query($sql);

  if (count($projectworkevents) > 0) {

    $overlap = true;
    $intervalstart = '00:00';
      
    foreach ($projectworkevents as $pw) {
      $interval_end = $pw->startime;

      if ($startime >= $intervalstart && $startime <= $interval_end && $stoptime >= $intervalstart && $stoptime <= $interval_end)
        $overlap = false;
 
      $intervalstart = $pw->stoptime;
    }

    if ($startime >= $intervalstart && $stoptime >= $intervalstart)
      $overlap = false;

    if ($overlap)
      $result = [1, "Overlap with $pw->textdate: $pw->startime-$pw->stoptime"];

  }    
}

echo json_encode($result);

?>

