<?php
chdir(dirname(__FILE__));
define("CONSOLE_MODE", true);
define('PUBLIC_FOLDER', 'public');
include "./init.php";
header("Content-type: text/plain");
ini_set('memory_limit', '4G');

ini_set("log_errors", 1);
ini_set("error_log", dirname(__FILE__)."/tmp/php-error.log");

Env::useHelper('form');
Env::useHelper('dimension');
Env::useHelper('permissions');
Env::useHelper('functions', 'crpm');

$max_depth_sql = "SELECT MAX(depth) as max_depth  FROM " . TABLE_PREFIX . "project_tasks;";
$max_depth_row = DB::executeAll($max_depth_sql);
$max_depth = $max_depth_row[0]['max_depth'] ? $max_depth_row[0]['max_depth'] : 0;
$count = 0;
Env::useHelper('additional_tasks_columns_functions', 'advanced_billing');
while($max_depth >= 0){
    $tasks_query = "SELECT `object_id` FROM " . TABLE_PREFIX . "project_tasks WHERE `depth`='".$max_depth."';";
    $rows = DB::executeAll($tasks_query);

    foreach ($rows as $row) {
        $task_id = $row['object_id'];
        $task_values = getTaskEstimatedExecutedValues($task_id);
        $estimated_cost = $task_values['estimated_cost'];
        $estimated_price = $task_values['estimated_price'];
        $earned_value = $task_values['earned_value'];
        $executed_cost = $task_values['executed_cost'];


        $update_tasks_sql = "UPDATE ".TABLE_PREFIX."project_tasks SET 
        estimated_cost=".$estimated_cost.",
        estimated_price=".$estimated_price.",
        earned_value=".$earned_value.",
        executed_cost=".$executed_cost."
        WHERE object_id=".$task_id.";\n";

        DB::executeAll($update_tasks_sql);
        $count++;

        echo date("H:i:s")." - $count tasks calculated \n";
    }
    $max_depth--;
    
}

echo date("H:i:s")." - calculation is complete \n";

