<?php

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

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "copyid")
    $copytr_id = $paramValue;
  else if ($paramName == "listid")
    $pw_id = $paramValue;
}

$dal = new DAL();

$tr_id = hexdec(uniqid());

$sql = "INSERT INTO travel (id, type, destination, vehicle_id) " .
       "SELECT $tr_id, TR.type, 'from', TR.vehicle_id FROM travel TR WHERE TR.id = $copytr_id ";
$result = $dal->query($sql);

$sql = "SELECT id, projectworkdaypersonnel_id, travelrole_id " .
       "FROM personneltravel WHERE travel_id = $copytr_id ";      
$pt_to = $dal->query($sql);

foreach ($pt_to as $pt) {

  $pt_id = hexdec(uniqid());;

  $sql = "INSERT INTO personneltravel (id, projectworkdaypersonnel_id, travelrole_id, travel_id) " .
         "VALUES ($pt_id, $pt->projectworkdaypersonnel_id, '$pt->travelrole_id', $tr_id) " ;
  $result = $dal->query($sql);
}

$sql = "SELECT TR.id, CONCAT (VE.name, ' (', VE.seating, ') ', VE.descr) text, 0 added " .
       "FROM (travel TR, vehicle VE, projectworkdaypersonnel PWP) " .
       "LEFT JOIN personneltravel PT ON PT.travel_id = TR.id " .
       "WHERE PT.projectworkdaypersonnel_id = PWP.id " .
       "AND PWP.projectworkevent_id = $pw_id AND TR.destination = 'from' " .
       "AND VE.id = TR.vehicle_id AND TR.id != $tr_id " .
       "GROUP BY TR.id " .
       "UNION " .
       "SELECT TR.id, CONCAT (VE.name, ' (', VE.seating, ') ', VE.descr) text, 2 added " .
       "FROM vehicle VE, travel TR WHERE VE.id = TR.vehicle_id AND TR.id = $tr_id ";         
$result = $dal->query($sql);

echo json_encode($result);

?>

