<?php
defined('PUBLIC_ACCESS') or die('Restricted Access');
 
require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');

class modCrewTimesheet {

  private $pw_id;

  public function __construct($pw_id) {
    if (isset($pw_id)) {
      $this->pw_id = $pw_id;
    }  
    else {
      $this->pw_id = 0; 
	}
    
    $dal = new DAL();

    $sql = "SELECT PE.id, 'project' as role_type, PTR.id AS put_id, " .
           "CONCAT (surname, ', ', first_name, ' ', middle_name) as text, SPACE(0) AS '*', " .
           "PR.name AS project_name, PR.refno, TE.name as role, " .
           "(CASE WHEN PTR.moduration > 0 THEN PTR.moduration ELSE PW.duration END) AS duration, PTR.billable, PTR.rationale, PTR.note " .
           "FROM projectworkday PW, projectworkdaypersonnel PWP, personnel PE, parcel PA, project PR, " .
           "projectteamrole PTR, teamrole TE " .
           "WHERE PW.id = $this->pw_id AND PA.id = PW.parcel_id AND PR.id = PA.project_id " .
           "AND PW.id = PWP.projectworkday_id AND PWP.id = PTR.projectworkdaypersonnel_id " .
           "AND PTR.teamrole_id = TE.id AND PWP.personnel_id = PE.id "  .
           "UNION " .
           "SELECT PE.id, 'travel' as role_type, PT.id AS put_id, " .
           "CONCAT (surname, ', ', first_name, ' ', middle_name) as text, SPACE(0) AS '*', " .
           "PR.name AS project_name, PR.refno, CONCAT(TV.name, ' ', TR.destination), " .
           "(CASE WHEN PT.moduration > 0 THEN PT.moduration ELSE PT.duration END) AS duration, PT.billable, PT.rationale, PT.note " .
           "FROM projectworkday PW, projectworkdaypersonnel PWP, personnel PE, parcel PA, project PR, " .
           "personneltravel PT, travel TR,  travelrole AS TV " .
           "WHERE PW.id = $this->pw_id AND PA.id = PW.parcel_id AND PR.id = PA.project_id " .
           "AND PW.id = PWP.projectworkday_id AND PWP.id = PT.projectworkdaypersonnel_id " .
           "AND PT.travel_id = TR.id AND TV.id = PT.travelrole_id AND PWP.personnel_id = PE.id "  .
           "ORDER BY text ";
    $this->time_sheet = $dal->query($sql);

    $currentId = 0;
    foreach ($this->time_sheet as $line) {
      if ($line->id != $currentId) {
        $line->firstOf = 1;
        $currentId = $line->id;
      }  
      else
        $line->firstOf = 0;
    }     

  
    $total_dur = 0;
    foreach (array_reverse($this->time_sheet) as $line) {
      $total_dur += $line->duration;
      if ($line->firstOf) {
        $line->total_dur = $total_dur;
        $total_dur = 0;
      }
    }
  }

  public function get($prop) {
    return $this->$prop;
  }
  

}

?>
