<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_APPROVE_BUDGET_REVISIONS';
if (!@$_GET['popup'])
	$path_to_root = "..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/projects/includes/db/unapproved_project_budgets_db.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_item_groups_db.inc");
include_once($path_to_root . "/projects/includes/db/tasks_db.inc");
include_once($path_to_root . "/projects/includes/db/projects_db.inc");
include_once($path_to_root . "/projects/includes/ui/approve_projects_ui.inc");
include_once($path_to_root . "/includes/approval_functions.inc");

page(_($help_context = "Approve Budget Revisions"));

//------------------------------------------------------------------------------------

if (!@$_GET['popup'])
	start_form();


if (!@$_GET['popup'])
{
//	echo "<center>" . _("Item:"). "&nbsp;";
//	echo stock_costable_items_list('stock_id', $_POST['stock_id'], false, true);
//
//	echo "<hr></center>";
}
else
	br(2);
div_start('show_heading');

br();
div_end();

function can_approve_budget_revision($error_frefix, $task)
{
    $current_task_new_biudget = $task['new_budget'];
    
    $available_consumed = $task['budget_used'] + $task['budget_allocated'];
    if($current_task_new_biudget < $available_consumed){
        $m = $error_frefix."New budget value can not be less than Rs. ".number_format($available_consumed,2).", the total of budget allocated 
                                                        Rs." .number_format($task['budget_allocated'],2)." and budget used 
                                                        Rs." .number_format($task['budget_used'],2);
        return array("success" => false, "message" => $m);
    }
    
    return array("success" => true, "message" => "");
    
}

function can_approve_all_budgets($project_id)
{
    $approved_budgets_total = get_approved_task_budgets_total($project_id);
    $unapproved_budgets_total = get_unapproved_task_budgets_total($project_id);
    
    $project = get_project_record($project_id);
    $stimated_cost = $project['estimated_cost'];
    
    $new_all_budgets_total = $approved_budgets_total + $unapproved_budgets_total;

    if($new_all_budgets_total > $stimated_cost + 0.00000001){
        $m = "Approved all budgets total of ".number_format($new_all_budgets_total,2)." will be higher than the project estimated cost of ".number_format($stimated_cost,2);
        return array("success" => false, "message" => $m);
    }
    
    return array("success" => true, "message" => "");
    
}

function build_unapproved_project_tasks_array(&$tasks, $project_id)
{

    $boq_item_group_res = get_project_boq_item_groups($project_id);
    while($boqg = db_fetch($boq_item_group_res))
    {
        $result = get_unapproved_project_tasks($project_id, $boqg['id']);
        if(db_num_rows($result)){
            while($line = db_fetch_assoc($result)){
                $tasks[] = $line;
            }            
        }
        
    }
    
    if($project_id > 0){
        $result = get_unapproved_project_tasks($project_id, 0);
        if(db_num_rows($result)){
            while($line = db_fetch_assoc($result)){
                $tasks[] = $line;
            }            
        }
    }
    
}

function save_unapproved_project_tasks($project_id)
{    
    $tasks = array();
    
    build_unapproved_project_tasks_array($tasks, $project_id);
    
    $caab_msg = can_approve_all_budgets($project_id);
    if($caab_msg['success'] !== true){
        return $caab_msg;
    }
    
    begin_transaction();
    
    foreach ($tasks as $task) {
        $supt_msg = save_unapproved_project_task($task);
        if($supt_msg['success'] !== true){
            cancel_transaction();
            return $supt_msg;
        }
    }
    
    commit_transaction();
    return array("success" => true, "message" => "");
    
}


function save_unapproved_project_task($task)
{      
    $project_updated = 0;
    $myrow = get_task_record($task['task_id']);


    $error_frefix = "Budget Id: ".$myrow['task_id'].", ".$myrow['task_code']." - ".$myrow['description']." - ";

    $msg = can_approve_budget_revision($error_frefix, $myrow);
    if($msg['success'] !== true){
        return $msg;
    }


    $n = update_project_task_approved_budget($myrow['task_id'], $myrow['new_budget'], $task['row_state']); 
    if($n != 1){
        cancel_transaction();
        return array("success" => false, "message" => $error_frefix."Another user has updated this budget.");
    }
    $approver_id = $_SESSION['wa_current_user']->user;
    add_task_budget_revision($myrow['task_id'], $myrow['budget'], $myrow['budget_used'], $myrow['budget_allocated'], $myrow['new_budget'], $approver_id);

    if($project_updated == 0){
        $project = get_project_record($myrow['project_id']);
        $rp_msg = reopen_project($project);
        if($rp_msg['success'] !== true){
            return $rp_msg;
        }
        $project_updated = 1;
    }
            
    return array("success" => true, "message" => "");
    
}

function display_project_task_budgets_summary($project_id)
{
    $approved_budgets_total = get_approved_task_budgets_total($project_id);
    $unapproved_budgets_total = get_unapproved_task_budgets_total($project_id);
    
    $project = get_project_record($project_id);
    $estimated_cost = $project['estimated_cost'];
    
    $new_all_budgets_total = $approved_budgets_total + $unapproved_budgets_total;

    start_table(TABLESTYLE, "width=30%");
    label_row("Project Estimated Cost", number_format($estimated_cost,2), '', 'align=right');
    label_row("Approved Budgets Total", number_format($approved_budgets_total,2), '', 'align=right');
    label_row("Approving Budgets Total", number_format($unapproved_budgets_total,2), '', 'align=right');
    label_row("Budgets Total After Approval", number_format($new_all_budgets_total,2), '', 'align=right');
    end_table(2);
 
}

function display_unapproved_project_tasks($project_id){
    
    start_table(TABLESTYLE, "width=90%");

    $th = array(_("Budget Group"), _("Budget Id"), _("New Budget"), _("Current Budget"), _("Difference"),
                _("Used"), _("Allocated"), _("Available"));
      
    table_header($th);

    $j = 1;
    $k = $count = 0; //row colour counter
    $totals = array();
    $totals['new_budgets'] = 0;
    $totals['current_budgets'] = 0;
    $totals['differences'] = 0;
    
    $boq_item_group_res = get_project_boq_item_groups($project_id);
    while($boqg = db_fetch($boq_item_group_res))
    {
        $result = get_unapproved_project_tasks($project_id, $boqg['id']);
        if(db_num_rows($result)){
//            table_header($th);
            start_row();
            label_cell(spaces(10*($boqg['depth']-1))."<b>".$boqg['code']."-".$boqg['item_description']."</b>");
            end_row();


            display_boq_group_unapproved_tasks($totals, $result);
            $count++;
        }
        
    }
    
    if($project_id > 0){
        $result = get_unapproved_project_tasks($project_id, 0);
        if(db_num_rows($result)){
//            table_header($th);
            start_row();
            label_cell("<b>No BOQ Item Group</b>");
            end_row();

            display_boq_group_unapproved_tasks($totals, $result);
            $count++;
        }
    }
    
    if($count > 0 && $project_id > 0){
        start_row();
            label_cell(text_bold("Totals"), 'align=right colspan=2');
            amount_cell($totals['new_budgets'], true);
            amount_cell($totals['current_budgets'],true);
            amount_cell($totals['differences'], true);
            label_cell("", 'colspan=3');
        end_row();
    }
    
    end_table(2);
    
    if($count > 0 && $project_id > 0){
        display_project_task_budgets_summary($project_id);
    }
    
    if($count > 0){
        submit_center('UpdateData', _("Approve"), true, false, 'default');
    }
    else{
        display_note("No unapproved budget revisions for this project");
        br(2);
    }
    
}

function display_boq_group_unapproved_tasks(&$totals, $result)
{
    $total_new_budgets = $total_current_budgets = $total_difference = 0;
    
        while($myrow = db_fetch($result))
        {
            alt_table_row_color($k);

            label_cell(spaces(10).$myrow['task_code']."-".$myrow['description']);

            label_cell($myrow['task_id'], "align=center");
            amount_cell($myrow['new_budget'], true);
            amount_decimal_cell($myrow['budget']);
            
            $difference = $myrow['new_budget'] - $myrow['budget'];
            
            amount_cell($difference, true);
            amount_decimal_cell($myrow['budget_used']); 
            amount_decimal_cell($myrow['budget_allocated']);
            
            $available = $myrow['budget'] - ($myrow['budget_used'] + $myrow['budget_allocated']);
            amount_decimal_cell($available);

//            check_cells('', 'selected_'.$myrow['task_id']);
//            'select_'.$myrow['task_id'] //- checkbox eke nama

            $total_new_budgets += $myrow['new_budget'];
            $total_current_budgets += $myrow['budget'];
            $total_difference += $difference;
        }
        
        $totals['new_budgets'] += $total_new_budgets;
        $totals['current_budgets'] += $total_current_budgets;
        $totals['differences'] += $total_difference;
}

if(isset($_POST['UpdateData'])){
    
    $msg = save_unapproved_project_tasks($_POST['project_id']);
    if($msg['success'] !== true){
        display_error($msg['message']);
    }
    else{
        display_notification("Selected budgets have been approved and budget revisions have been created.");
    }
   
}

start_table(TABLESTYLE_NOBORDER);
start_row();
project_list_cells("Project:", 'project_id', null, 'Please select a project', true); 
end_row();
end_table();


br(2);
   
$Ajax->activate('reorders');

div_start('reorders');

display_unapproved_project_tasks($_POST['project_id']);
div_end();


br(2);

if (!@$_GET['popup'])
{
	end_form();
	end_page(@$_GET['popup'], false, false);
}


?>
