<?php

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

if (isset($_REQUEST["arg1"])) {
  $arg1 = explode (",", $_REQUEST["arg1"]);
  
  $trfrom_id = array_pop ($arg1);
  $trto_id   = array_pop ($arg1);
  $pw_id     = array_pop ($arg1);
  $to        = array_pop ($arg1);
  $from      = array_pop ($arg1);

  $dal = new DAL();
  
  for ($i=0; $i<count($arg1); $i++) {
    $pe_id = $arg1[$i];

    if ($from == "leftassign_crew" && $to == "middleassign_crew") {

      $pwp_id = hexdec(uniqid());
  
      $sql = "INSERT INTO projectworkdaypersonnel " .
             "(id, projectworkday_id, personnel_id) " .
             "VALUES ($pwp_id, $pw_id, $pe_id) " ;
      $result = $dal->query($sql);
   
      $ptr_id = hexdec(uniqid());
  
      $sql = "INSERT INTO projectteamrole " . 
	           "(id, projectworkdaypersonnel_id, teamrole_id) " .
             "VALUES ($ptr_id, $pwp_id, 2) ";
    $return = $dal->query($sql);
    $status = "Insert: projectworkday";
    }       

    else if ($from == "middleassign_crew" && $to == "leftassign_crew") {
      $sql = "SELECT id FROM projectworkdaypersonnel " .
             "WHERE projectworkday_id = $pw_id AND personnel_id = $pe_id LIMIT 1";
      $pwp_id = $dal->query($sql)->id;
      
      $sql = "DELETE FROM projectteamrole WHERE projectworkdaypersonnel_id = $pwp_id ";
      $result = $dal->query($sql);

      $sql = "DELETE FROM personneltravel WHERE projectworkdaypersonnel_id = $pwp_id ";
      $result = $dal->query($sql);

      $sql = "DELETE FROM projectworkdaypersonnel WHERE id = $pwp_id ";
      $result = $dal->query($sql);

    }
    
    else if ($from == "middleassign_crew" && $to == "rightassign_crew") {
      $sql = "SELECT id FROM projectworkdaypersonnel " .
             "WHERE projectworkday_id = $pw_id AND personnel_id = $pe_id LIMIT 1";
      $pwp_id = $dal->query($sql)->id;
      
      $sql = "UPDATE projectteamrole " .
             "SET teamrole_id = 7 " .
             "WHERE projectworkdaypersonnel_id = $pwp_id " ;
      $result = $dal->query($sql);

      $sql = "DELETE FROM personneltravel  " .
             "WHERE projectworkdaypersonnel_id = $pwp_id AND travel_id = $trfrom_id ";
      $result = $dal->query($sql);

      $sql = "DELETE FROM personneltravel  " .
             "WHERE projectworkdaypersonnel_id = $pwp_id AND travel_id = $trto_id ";
      $result = $dal->query($sql);
    }
    
    else if ($from == "rightassign_crew" && $to == "middleassign_crew") {
      $sql = "SELECT id FROM projectworkdaypersonnel " .
             "WHERE projectworkday_id = $pw_id AND personnel_id = $pe_id LIMIT 1";
      $pwp_id = $dal->query($sql)->id;

      $sql = "UPDATE projectteamrole " .
             "SET teamrole_id = 2 " .
             "WHERE projectworkdaypersonnel_id = $pwp_id " ;
      $result = $dal->query($sql);
    }
  }
}

echo json_encode($result);

?>

