<?php
session_start();

require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');
require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/access.php');

date_default_timezone_set("Canada/Eastern");

$lo_id = $_SESSION['login'];

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

$break = substr($breakdur,0,2) + substr($breakdur,3,2)/100;

$duration = (DateTime::createFromFormat("Y-m-d H:i", "$date $stoptime")->getTimeStamp() -
            DateTime::createFromFormat("Y-m-d H:i", "$date $startime")->getTimeStamp())/3600 - $breakdur;

$textdate = date('D M j, Y', strtotime($date));

$dal = new DAL;

$sql = "SELECT id FROM workday WHERE date = '$date' LIMIT 1 ";
$wo_id = $dal->query($sql)->id;

if (count($wo_id) == 0) {
  $wo_id = hexdec(uniqid());

  $sql = "INSERT INTO workday (id, date, textdate) " .
         "VALUES ($wo_id, '$date', '$textdate') ";
  $result = $dal->query($sql);
}  

$sql = "SELECT id FROM loginworkday " .
       "WHERE workday_id = $wo_id AND login_id = $lo_id LIMIT 1";
$lw_id = $dal->query($sql)->id;

if (null === $lw_id) {
  $lw_id = hexdec(uniqid());
  
  $sql = "INSERT INTO loginworkday (id, workday_id, login_id) " .
         "VALUES ($lw_id, $wo_id, $lo_id) ";
  $result = $dal->query($sql);
}

if ($pw_id == 0) {

  $sql = "SELECT workdayvisit FROM projectworkevent " .
         "WHERE workday_id = $wo_id AND projectparcel_id = $pp_id " .
         "AND login_id = $lo_id ORDER BY workdayvisit DESC LIMIT 1 "; 
  $seq = $dal->query($sql)->workdayvisit;
  
  $seq = (null === $seq) ? 1 : ($seq + 1);

  $pw_id = hexdec(uniqid());

  $sql = "INSERT INTO projectworkevent " .
         "(id, workday_id, projectparcel_id, login_id, workdayvisit, " .
         "startime, stoptime, breakdur, duration, note) " . 
         "VALUES ($pw_id, $wo_id, $pp_id, $lo_id, $seq, " .
         "'$startime', '$stoptime', '$breakdur', $duration, '$note') " ;
  $result = $dal->query($sql);

  $return = true;
}

else {
  $sql = "UPDATE projectworkevent " .
         "SET workday_id='$wo_id', projectparcel_id='$pp_id', " .
         "startime='$startime', stoptime='$stoptime', " .
         "breakdur='$breakdur', duration=$duration, note='$note' " .
         "WHERE id = $pw_id ";
  $return = $dal->query($sql);

}

echo json_encode ($pw_id);

?>
