<?php
// Key of Project in List
$key = $_SESSION['project_id'];

// Calc task Dynamic or Group ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

$sql_1 = "SELECT
 t.`task_id`, t.`dynamic`, t.`order`
FROM tasks t
WHERE
t.`dynamic` = 1 and
t.`projects_project_id` = $key order by t.`order` desc";


if ($resql_1 = DB::Query($sql_1)) {
    /*  calc tasks Dymanic*/
		$hours_a_day = $_SESSION['Config']['hours_a_day'];
    while ($row_1 = $resql_1->fetchAssoc()) {
        $parent = $row_1['task_id'];
				$sql_2 = "
SELECT
t.`parent`,
min(t.`start_date`) start_date,
max(t.`end_date`) end_date,
sum(if (duration_type = 0,$hours_a_day,1)*duration) duration,
sum((if (duration_type = 0,$hours_a_day,1)*duration)*percent_complete/100) completed
FROM tasks t
WHERE
t.`parent` = $parent
order by 1 
";
				if ($resql_2 = DB::Query($sql_2)) {
					$row_2 = $resql_2->fetchAssoc();
					$task_parent = $row_2['parent'];
					$task_start_date = $row_2['start_date'];
					$task_end_date = $row_2['end_date'];
					$task_duration = $row_2['duration'];
					$task_completed = $row_2['completed'];

					$free_weekend = $_SESSION['Config']['free_weekend'];
					require_once "MyCode/function_dates.php";   // Function of dates
					if ( $free_weekend == 'yes' ) {
							$function_datediff = 'TOTAL_WEEKDAYS';
					} else {
							$function_datediff = 'DATEDIFF';
					}

				$sql_3="
update tasks
set
start_date = '$task_start_date',
end_date = '$task_end_date',
duration_type = 0,
duration= $function_datediff('$task_end_date','$task_start_date'),
percent_complete=ROUND($task_completed*100/$task_duration,0)
where task_id = $task_parent
";
				DB::Exec($sql_3); 
				}
    }

}
// Calc Project  ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$sql_1 = "
SELECT
min(t.`start_date`) start_date,
max(ifnull(`actual_end_date`,`end_date`)) end_date,
sum(hours_worked) hours_worked,
sum(if (duration_type = 0,$hours_a_day,1)*duration) duration,
sum((if (duration_type = 0,$hours_a_day,1)*duration)*percent_complete/100) completed
FROM tasks t
WHERE
t.`dynamic` = 0 and
t.`projects_project_id` = $key
-- order by t.`order`
";
if ($resql_1 = DB::Query($sql_1)) {
		$row_1 = $resql_1->fetchAssoc();
		$task_start_date = $row_1['start_date'];
		$task_end_date = $row_1['end_date'];
		$task_duration = $row_1['duration'];
		$task_completed = $row_1['completed'];
		$task_hours_worked = $row_1['hours_worked'];

$sql_2="
update projects
set
actual_end_date = '$task_end_date',
worked_hours = $task_hours_worked, 
scheduled_hours= $task_duration,
percent_complete=ROUND($task_completed*100/$task_duration,0)
where `project_id` = $key
";
DB::Exec($sql_2); 

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

}
?>

