<?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 == "currid")
    $pw_id = $paramValue;
  if ($paramName == "id")
    $ptr_id = $paramValue;
  if ($paramName == "scopeid")
    $lw_id = $paramValue;
  elseif ($paramName == "workday")
    $date = $paramValue;
  elseif ($paramName == "awayfromwork")
    $absent = $paramValue;
}

$dal = new DAL;

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

$sql = "SELECT personnel_id FROM login WHERE id = $lo_id LIMIT 1";
$pe_id = $dal->query($sql)->personnel_id;

$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_id = $dal->query($sql);
}

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

if (null === $pw_id) {

  $pw_id = hexdec(uniqid());

  $sql = "INSERT INTO projectworkday " .
         "(id, workday_id, parcel_id, login_id, fieldwork_day) " . 
         "VALUES ($pw_id, '$wo_id', '$parcel_id', $lo_id, 0) " ;

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

else {
  $sql = "UPDATE projectworkday " .
         "SET workday_id='$wo_id', parcel_id='$parcel_id' " .
         "WHERE id = $pw_id ";
  $return = $dal->query($sql);
}

if ($ptr_id == 0) {

  $sql = "SELECT id FROM projectworkdaypersonnel " .
         "WHERE projectworkday_id = $pw_id AND personnel_id = $pe_id LIMIT 1";
  $pwp_id = $dal->query($sql)->id;

  if (null === $pwp_id) {

    $pwp_id = hexdec(uniqid());

    $sql = "INSERT INTO projectworkdaypersonnel " .
           "(id, projectworkday_id, personnel_id, absent) " . 
           "VALUES ($pwp_id, $pw_id, $pe_id, $absent) " ;
    $result = $dal->query($sql);
  }    

}

else {
    
  $sql = "SELECT projectworkdaypersonnel_id FROM projectteamrole WHERE id = '$ptr_id' LIMIT 1";
  $pwp_id = $dal->query($sql)->projectworkdaypersonnel_id;

  $sql = "UPDATE projectworkdaypersonnel SET " .
         "absent=$absent WHERE id = $pwp_id "; 
  $result = $dal->query($sql);
    
  $sql = "UPDATE projectteamrole SET " .
         "projectworkdaypersonnel_id=$pwp_id, teamrole_id=$teamrole_id, start_time='$start_time', " .
         "moduration='$moduration', billable=$billable, rationale='$rationale', note='$note' " .
         "WHERE id = $ptr_id "; 
  $result = $dal->query($sql);

}

$_SESSION['projectworkday'] = $pw_id;
$_SESSION['workday'] = $wo_id;
$_SESSION['loginworkday'] = $lw_id;


echo json_encode ($wo_id);


