<?php

function update_recalculated_costs_of_all_tasks($project_id)
{
    $result = get_project_task_recalculations($project_id);
    while ($row = db_fetch($result)) {
        if($row['updated_by'] == 0){
            $msg = update_task_recalculated_costs($row['task_id']);  
            if($msg['success'] !== true){
                return $msg;
            }
        }
    }
    return $msg;
}


function update_task_recalculated_costs($task_id)   
{
    $task = get_task_record($task_id);
    $task_current_row_state = $task['row_state'];
    $r = get_task_cost_recalculation_record($task_id);
    $d = substr($r['end_time'],0,4);
    if($d == '0000'){
        $m = "Budget ".$task['task_id']." - ".$task['task_code']." - ".$task['description']." recalculation has not been completed successfully. Not possible to proceed with this cost update.";
        return array("success" => false, "message" => $m);
    }
    
    if($r['task_row_state'] != $task_current_row_state){
        $m = "Budget ".$task['task_id']." - ".$task['task_code']." - ".$task['description']." has been updated after cost recalculation. Costs recalculated are now outdated. Not possible to proceed with this cost update.";
        return array("success" => false, "message" => $m);        
    }
    
    begin_transaction();
    
    delete_task_all_cost_details($task_id);
    delete_task_all_allocation_details($task_id);
    
    update_task_costs_from_rebuilt_values($task_id); 
    update_task_allocations_from_rebuilt_values($task_id); 
    
    $total_cost = get_rebuilt_task_total($task_id, 0);
    $total_allocation = get_rebuilt_task_total($task_id, 1);
    
    $n1 = update_task_cost_recalculation_cost_updated($task_id, $task_current_row_state);
    if($n1 !== 1){
        cancel_transaction();
        $m = "Budget ".$task['task_id']." - ".$task['task_code']." - ".$task['description']." has been updated after cost recalculation. Could not update the budget with recalculated values.";
        return array("success" => false, "message" => $m);
    }
    
    $n2 = update_task_cost_totals($task_id, $total_allocation, $total_cost, $task_current_row_state);
    if($n2 !== 1){
        cancel_transaction();
        $m = "Budget ".$task['task_id']." - ".$task['task_code']." - ".$task['description']." has been updated after cost recalculation. Could not update the budget with recalculated values.";
        return array("success" => false, "message" => $m);
    }
    
    commit_transaction();
    return array("success" => true, "message" => "");

}


function get_boq_group_task_recalculations($project_id, $boq_group_id)
{
    
    $sql = "SELECT t.task_id, t.task_code, t.description task_description, t.row_state,
                tg.code task_group_code, tg.description task_group_description,
                dtn.value_name detail_type_name,
                tr.created_by, tr.created_on,tr.updated_by, tr.updated_on, tr.task_row_state 
            FROM ".TB_PREF."project_tasks t 
                JOIN ".TB_PREF."project_task_groups tg ON 
                    t.task_group_id = tg.id 
                JOIN ".TB_PREF."list_values dtn ON 
                    t.detail_type_code = dtn.value_code AND dtn.list_code = 'PROJECT_TASK_DETAIL_TYPES' 
                LEFT JOIN ".TB_PREF."project_task_cost_recalculations tr ON 
                    tr.task_id = t.task_id 
            WHERE tg.boq_group_id = ".db_escape($boq_group_id)." 
                    AND t.project_id = ".db_escape($project_id)." 
                
            ORDER BY tg.description, t.task_code ";
    
    return db_query($sql, "get_boq_group_task_recalculations");
}


function get_project_task_recalculations($project_id)
{

    $sql = "SELECT t.task_id, t.task_code, t.description task_description, t.row_state,
                tr.created_by, tr.created_on,tr.updated_by, tr.updated_on, tr.task_row_state 
            FROM ".TB_PREF."project_tasks t 
                JOIN ".TB_PREF."project_task_cost_recalculations tr ON 
                    tr.task_id = t.task_id 
            WHERE t.project_id = ".db_escape($project_id);
    
    return db_query($sql, "get_project_task_recalculations");
}

function get_rebuilt_project_task_cost_details($task_id = 0, $allocations = false)
{    
    
    $sql = "SELECT pbig.description boq_group_description, 
                    pt.description task_description,
                    tcr.id,
                    tran_type,
                    tran_no,
                    amount,
                    total_cost,
                    added_on
            FROM ".TB_PREF."task_costs_rebuild tcr 
                    JOIN ".TB_PREF."project_tasks pt 
                            ON tcr.task_id = pt.task_id
                    JOIN ".TB_PREF."project_task_groups ptg 
                            ON pt.task_group_id = ptg.id 
                    LEFT JOIN ".TB_PREF."project_boq_item_groups pbig 
                            ON ptg.boq_group_id = pbig.id AND pbig.project_id = pt.project_id 
            
            WHERE pt.task_id =".db_escape($task_id)." 
                    AND tcr.allocation =".db_escape($allocations)." 
            ORDER BY tcr.task_id, tcr.added_on, tcr.id";
    
    return db_query($sql);
    

}

function get_sql_for_rebuild_project_budget_costs_inquirys($task_id)
{
    $sql = "SELECT tcr.*,
                    pt.description budget_description        
            
            FROM ".TB_PREF."task_costs_rebuild tcr
                LEFT JOIN ".TB_PREF."project_tasks pt 
                ON tcr.task_id = pt.task_id                 
            WHERE  "; 
    
    if($task_id > 0){
        
        $sql .= " tcr.task_id=".db_escape($task_id);
    }
    
    
//    $sql .= " ORDER BY order_no ";
    return db_query($sql); //send as resource
     
   
}

function update_task_costs_from_rebuilt_values($task_id)
{
//    delete_task_all_cost_details($task_id);
	
	$sql = "INSERT INTO ".TB_PREF."task_costs (
                        tran_type, tran_no, 
                        task_id, amount, total_cost, 
                        added_by, added_on)
                    
			SELECT tran_type, 
                                tran_no, 
                                task_id, 
                                amount, 
                                total_cost, 
                                added_by, 
                                added_on
			FROM ".TB_PREF."task_costs_rebuild
			WHERE task_id =  ".db_escape($task_id)." AND 
                                allocation = 0 
                        ORDER BY added_on, id   ";
        
        db_query($sql);
}

function update_task_allocations_from_rebuilt_values($task_id)
{
//    delete_task_all_allocation_details($task_id);
	
	$sql = "INSERT INTO ".TB_PREF."task_cost_allocations (
                        tran_type, tran_no, 
                        task_id, amount, total_allocation, 
                        updated_by, updated_on)
                    
			SELECT tran_type, 
                                tran_no, 
                                task_id, 
                                amount, 
                                total_cost, 
                                added_by, 
                                added_on
			FROM ".TB_PREF."task_costs_rebuild
			WHERE task_id =  ".db_escape($task_id)." AND 
                                allocation = 1 
                        ORDER BY added_on, id   ";
        
        db_query($sql);
}

function delete_task_all_cost_details($task_id)
{
    $sql = "DELETE  FROM ".TB_PREF."task_costs   
            WHERE task_id = ".db_escape($task_id);

    db_query($sql);

}

function delete_task_all_allocation_details($task_id)
{
    $sql = "DELETE  FROM ".TB_PREF."task_cost_allocations    
            WHERE task_id = ".db_escape($task_id);

    db_query($sql);

}

function get_rebuilt_task_total($task_id, $allocations = 0)
{
    $sql = "SELECT SUM(amount) total_cost   
            FROM ".TB_PREF."task_costs_rebuild   
            WHERE  task_id=".db_escape($task_id);
    
    if($allocations){
        $sql .= " AND allocation = 1";   
    }
    else{
        $sql .= " AND allocation = 0";   
    }
    
    $result = db_query($sql); 
    
    $row = db_fetch($result);
    if(isset($row['total_cost']) && $row['total_cost'] > 0){
        return $row['total_cost'];
    }
    else{
        return 0;
    }
}


        
function update_task_cost_totals($task_id, $total_allocation, $total_cost, $row_state)
{
    $sql = "UPDATE ".TB_PREF."project_tasks   
                SET budget_allocated = ".db_escape($total_allocation).", 
                    budget_used = ".db_escape($total_cost).",
                    row_state = ". db_new_row_state($row_state)." 
            WHERE task_id = ".db_escape($task_id)." AND 
                 row_state = ".db_escape($row_state);

    db_query($sql);
    return db_num_affected_rows();
}



?>