<?php
session_start();

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "selectid")
    $pwo_id = $paramValue;
  else if ($paramName == "button")
    $button = $paramValue;
}

date_default_timezone_set("Canada/Eastern");

$hours = date("H");
$minutes = date("i");
$m = ((($minutes + 7.5)/15 | 0) * 15) % 60;
$h = (((($minutes/105) + .5) | 0) + $hours) % 24;
$now = sprintf("%02d", $h) . ':' . sprintf("%02d", $m);
$return = $now;

$dal = new DAL();

if ($button == 'start') {
  $sql = "UPDATE projectworkdayoperation " .
         "SET starttime='$now' WHERE id = $pwo_id ";
  $result = $dal->query($sql);
}

else if ($button == 'stop') {
  $sql = "SELECT starttime, breakduration FROM projectworkdayoperation " .
         "WHERE id = $pwo_id LIMIT 1 ";
  $pwo = $dal->query($sql);
  
  $dur = (substr ($now, 0,2) + substr ($now, 3,2)/60)
         - (substr ($pwo->starttime, 0,2) + substr ($pwo->starttime, 3,2)/60)
         - $pwo->breakduration;

  $duration = sprintf ("%01.2f", $dur);
            

  $sql = "UPDATE projectworkdayoperation " .
         "SET stoptime='$now', duration=$duration WHERE id = $pwo_id ";
  $result = $dal->query($sql);
}

else if ($button == 'pause') {
  $sql = "SELECT breakduration FROM projectworkdayoperation " .
         "WHERE id = $pwo_id LIMIT 1 ";
  $return = $dal->query($sql)->breakduration;

  $sql = "UPDATE projectworkdayoperation " .
         "SET pausetime='$now' WHERE id = $pwo_id ";
  $result = $dal->query($sql);
}

else if ($button == 'resume') {

  $sql = "SELECT pausetime, breakduration FROM projectworkdayoperation " .
         "WHERE id = $pwo_id LIMIT 1 ";
  $pwo = $dal->query($sql);
  
  $break = (substr ($now, 0,2) + substr ($now, 3,2)/60)
    - (substr ($pwo->pausetime, 0,2) + substr ($pwo->pausetime, 3,2)/60)
    + $pwo->breakduration;
    
  $breakduration = sprintf ("%01.2f", $break);

  $sql = "UPDATE projectworkdayoperation " .
         "SET breakduration='$breakduration' WHERE id = $pwo_id ";
  $result = $dal->query($sql);
  
  $return = $breakduration;
}

else if ($button == 'duration') {
  $sql = "SELECT duration FROM projectworkdayoperation " .
         "WHERE id = $pwo_id LIMIT 1 ";
  $return = $dal->query($sql)->duration;
}

echo json_encode($return);

?>

