<?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 == "id")
    $pw_id = $paramValue;
  elseif ($paramName == "rowproject_name")
    $pr_id = $paramValue;
  elseif ($paramName == "project_name")
    $projectName = $paramValue;
  elseif ($paramName == "parcel_id")
    $pa_id = $paramValue;
  elseif ($paramName == "date")
    $date = $paramValue;
  elseif ($paramName == "start_time") 
    $start_time = $paramValue;  
  elseif ($paramName == "end_time") 
    $end_time = $paramValue;  
  elseif ($paramName == "break_dur") 
    $break_dur = $paramValue;  
}

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

$duration = (DateTime::createFromFormat("Y-m-d H:i", "$date $end_time")->getTimeStamp() -
            DateTime::createFromFormat("Y-m-d H:i", "$date $start_time")->getTimeStamp())/3600 - $break;

$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 (null === $wo_id) {
  $wo_id = hexdec(uniqid());

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

$dal = new DAL;
$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) {
  $pw_id = hexdec(uniqid());

  $sql = "INSERT INTO projectworkday " .
         "(id, start_time, end_time, break_dur, duration, workday_id, parcel_id, login_id) " . 
         "VALUES ($pw_id, '$start_time', '$end_time', '$break_dur', $duration, '$wo_id', '$pa_id', $lo_id) " ;

  $result = $dal->query($sql);
  $return = true;
}

else {
  $sql = "UPDATE projectworkday " .
         "SET start_time='$start_time', end_time='$end_time', break_dur='$break_dur', " .
         "duration=$duration, workday_id='$wo_id', parcel_id='$pa_id', login_id=$lo_id " .
         "WHERE id = $pw_id ";
  $return = $dal->query($sql);
}

$_SESSION['project'] = $pr_id;
$_SESSION['parcel'] = $pa_id;
$_SESSION['workday'] = $wo_id;
$_SESSION['loginworkday'] = $lw_id;
$_SESSION['projectworkday'] = $pw_id;

echo json_encode ($pw_id);

?>
