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

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/sales/includes/sales_db.inc");
include_once($path_to_root . "/sales/includes/db/sales_types_db.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");
//include_once($path_to_root . "/inventory/includes/inventory_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 . "/admin/db/list_values_db.inc");


$js = '';

if (user_use_date_picker()) {
        $js .= get_js_date_picker();
}

if (!@$_GET['popup'])
        page(_($help_context = "Project Budgets"),false,false,"",$js);

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

check_db_has_projects(_("There are no projects defined in the system."));

simple_page_mode(true);
//---------------------------------------------------------------------------------------------------
$input_error = 0;

if (isset($_GET['project_id']))
{
	$_POST['project_id'] = $_GET['project_id'];
}


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

//set_global_stock_item($_POST['project_id']);
function clear_task_data()
{
    unset($_POST['task_group_id']);
    unset($_POST['type_id']);
    unset($_POST['group_code']);
    unset($_POST['group_description']);
    unset($_POST['task_name']);
    unset($_POST['long_description']);
    unset($_POST['boq_group_id']);
    unset($_POST['start_date']);
    unset($_POST['end_date']);	
}

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

function display_task_groups($project_id, $boq_group_id)
{
//    $tasks_list = get_tasks($project_id);
    
    display_heading2("Budget Groups");
    
    $tasks_list = get_boq_group_task_groups($project_id, $boq_group_id);

    div_start('price_table');

    start_table(TABLESTYLE, "width=90%");

    $th = array(_("Group ID"), _("Type Name"),_("Code"), _("Description"), _("Start date"),_("End date")
                    , _("Budget"), _("Budget Used"), _("Budget Allocated"),"", "");

    table_header($th);

    $k = 0; //row colour counter

    $calculated = false;
    $total_budget = $total_budget_used = $total_budget_allocated = 0;

    while ($myrow = db_fetch($tasks_list))
    {
        alt_table_row_color($k);

        label_cell($myrow["id"]);
        label_cell($myrow["type_name"]);
        label_cell($myrow["code"]);
        label_cell($myrow["description"]);
        label_cell(sql2date($myrow["start_date"]), 'align=center');
        label_cell(sql2date($myrow["end_date"]), 'align=center');
        amount_cell($myrow["budget"]);
        amount_cell($myrow["budget_used"]);
        amount_cell($myrow["budget_allocated"]);
        edit_button_cell("Edit".$myrow['id'], _("Edit"));
//        delete_button_cell("Delete".$myrow['task_id'], _("Delete"));
        end_row();
        
        $total_budget += ($myrow["budget"]);
        $total_budget_used += ($myrow["budget_used"]);
        $total_budget_allocated += ($myrow["budget_allocated"]);
    }
    
    start_row();
        label_cell("Total", "colspan=6 align=right");
        amount_decimal_cell($total_budget);
        amount_decimal_cell($total_budget_used);
        amount_decimal_cell($total_budget_allocated);
    end_row();

    end_table();

    div_end();    
}


function display_task_groups_summary($boq_group_id, $project_id = -1)
{
//    $tasks_list = get_tasks($project_id);
    
    display_heading2("BOQ Group Summary");
    
    $group_summary = get_boq_group_tasks_summary($boq_group_id, $project_id);

    div_start('price_table');

    start_table(TABLESTYLE, "width=50%");

    $th = array( _("Budget"), _("Budget Used"), _("Budget Allocated"));

    table_header($th);

    
    start_row();
        amount_decimal_cell($group_summary['budget']);
        amount_decimal_cell($group_summary['budget_used']);
        amount_decimal_cell($group_summary['budget_allocated']);
    end_row();

    end_table();

    div_end();    
}


function can_commit_task($selected_id, $Mode)
{
        $project = get_project($_POST['project_id']);
        
        $budget_freeze_date = sql2date($project['budget_freeze_date']);
        if(date1_greater_date2(Today(), $budget_freeze_date)){
            display_error( _("All budgets of this project are frozen and can not be updated."));
            set_focus('group_code');
            return false;
        }

        if(!($_POST['type_id'] > 0)){
                display_error( _("Please select a type for the budget group."));
                set_focus('type_id');
                return false;
        }
        
        if(!(strlen($_POST['group_code']) > 0)){
                display_error( _("Code can not be empty."));
                set_focus('group_code');
                return false;
        }
        
        $row_count = get_existing_code_from_project_task_groups(get_post('project_id'), get_post('group_code'), $selected_id);
        if($row_count > 0)
        {
           display_error("Entered code already exists.");
           set_focus('group_code');
           return false;        
        }

        if(!(strlen($_POST['group_description']) > 0)){
                display_error( _("Description can not be empty."));
                set_focus('group_description');
                return false;
        }        

        if (is_date($_POST['start_date']) == FALSE){
            display_error( _("Incorrect task start date"));
            set_focus('start_date');
            return false;
        }
        
        if (is_date($_POST['end_date']) == FALSE){
            display_error( _("Incorrect task end date"));
            set_focus('end_date');
            return false;
        }

        $project_start_date = sql2date($project['start_date']);
        $project_end_date = sql2date($project['end_date']);

        if (date1_greater_date2($project_start_date, $_POST['start_date']))
        {
            display_error( _("Budget group start date can not be ealier than project start date"));
            set_focus('start_date');
            return false;
        }
            
        if (date1_greater_date2($_POST['end_date'], $project_end_date))
        {
            display_error( _("Budget group end date can not be later than project end date"));
            set_focus('end_date');
            return false;
        }
            
        if (date1_greater_date2($_POST['start_date'], $_POST['end_date']))
        {
            display_error( _("Budget group end date can not be later than Budget group start date"));
            set_focus('end_date');
            return false;
        }
        
        $other_tasks_budget_total = get_other_task_groups_budget_total($project['project_id'], $selected_id);
        
        $count = $this_task_group_budget_total = 0;    
        $list_code = 'PROJECT_TASK_DETAIL_TYPES';
        $list_values_q = get_all_list_values($list_code);
        while ($list_value = db_fetch($list_values_q))
        {
            if(isset($_POST['selected_'.$list_value["value_code"]]) && $_POST['selected_'.$list_value["value_code"]] == 1){
                $budget = input_num('budget_'.$list_value["value_code"]);
                if(($budget < 0)){
                    display_error( _("New Budget eneterd for detail type ".$list_value["value_name"]." has to be numeric and not negative."));
                    set_focus('budget_'.$list_value["value_code"]);
                    return false;
                }                

                $task = get_task_record_by_detail_type($selected_id, $list_value['value_code']);
                if(isset($task['task_id']) && $task['task_id'] > 0){
                    $budget_allocated = $task['budget_allocated'];
                    $budget_used = $task['budget_used'];

                    if(($budget_allocated + $budget_used) > $budget){
                        $msg = "Budget eneterd for detail type ".$list_value["value_name"]." (".number_format($budget,2).") has to be higher than the total of 
                                            budget allocated and budget used (". number_format($budget_allocated + $budget_used,2).").";
                        display_error($msg);
                        set_focus('budget_'.$list_value["value_code"]);
                        return false;
                    }
                }

                $this_task_group_budget_total += $budget;
                $count++;
                
            }
        }
    
        $new_project_budget = $other_tasks_budget_total + $this_task_group_budget_total; 
        if($new_project_budget > $project['estimated_cost'])
        {
            display_error( _("With the budgets entered, the total of all the individual budgets will exceed the project total cost."));
            set_focus('budget');
            return false;
        }
        
        if($count == 0)
        {
            display_error( "No Budgets selected.");
            set_focus('budget');
            return false;
        }
        
        return true;
}

//function get_this_task_group_budget_total()
//{
//    $budgets_total = 0;
//    
//    $list_code = 'PROJECT_TASK_DETAIL_TYPES';
//    $list_values_q = get_all_list_values($list_code);
//    while ($list_value = db_fetch($list_values_q))
//    {
//        if(isset($_POST['selected_'.$list_value["value_code"]]) && $_POST['selected_'.$list_value["value_code"]] == 1){
//            $budget = input_num('budget_'.$list_value["value_code"]);
//            $budgets_total += $budget;
//        }
//    }
//    
//    return $budgets_total;
//}


function save_task_group_tasks($task_group_id, $group_code,$group_description, $type_id, $group_project_id, $add_budgets = 0)
{
    $list_code = 'PROJECT_TASK_DETAIL_TYPES';
    $list_values_q = get_all_list_values($list_code);
    while ($list_value = db_fetch($list_values_q))
    {
        if(isset($_POST['selected_'.$list_value["value_code"]]) && $_POST['selected_'.$list_value["value_code"]] == 1){
            $task_code = $group_code.'-'.$list_value["value_code"];
            if($list_value["value_code"] == "ALL"){
                $task_description = $group_description;
            }
            else{
                $task_description = $group_description.'-'.$list_value["value_name"];
            }
            $project_id = $group_project_id;
            $budget = input_num('budget_'.$list_value["value_code"]);
                    
            $task = get_task_record_by_detail_type($task_group_id, $list_value['value_code']);
            if(isset($task['task_id']) && $task['task_id'] > 0){
                update_task_details($task['task_id'], $task_code, $task_description, 
                                    $type_id, $budget, $task_group_id, $add_budgets);
            }
            else{
                add_task($project_id, $task_code, $task_description, 
                            $type_id, $budget, $task_group_id, $list_value['value_code'], $add_budgets);
            }
            
        }
    }
}


function save_details($selected_id, &$Mode)
{
//return;
        $project_id = get_post('project_id');
        $boq_group_id = get_post('boq_group_id');
        
        
        if(!($boq_group_id > 0)){
            $boq_group_id = 0;
        }
        
        $project = get_project_record($project_id);
        
        if ($selected_id > 0) 
        {
            //editing an existing taxk group
            update_task_group_details($selected_id,$_POST['group_code'], $_POST['group_description'], $_POST['type_id'], $_POST['long_description'], 
                    $_POST['start_date'], $_POST['end_date'], $boq_group_id);
            $task_group_id = $selected_id;
            $msg = _("This task has been updated.");
        }
        else
        {
            $task_group_id = add_task_group_details($project_id,$_POST['group_code'],$_POST['group_description'], $_POST['type_id'], $_POST['long_description'], 
                    $_POST['start_date'], $_POST['end_date'], $boq_group_id);
                          
            $msg = _("The new task has been added.");
        }
            
        if($task_group_id > 0){
            save_task_group_tasks($task_group_id, $_POST['group_code'],$_POST['group_description'], $_POST['type_id'], $project_id, $project['add_budgets']);
        }
        clear_task_data(); 
        display_notification($msg);
        $Mode = 'RESET';
}

function display_task_group_edit_controls(&$Mode, &$selected_id, $project_id)
{
    if(list_updated(('filtering_group_id'))){
        $selected_id = -1;
    }
    
    if ($Mode == 'Edit')
    {
        $myrow = get_task_group_details($selected_id);

        $_POST['task_group_id'] = $myrow["id"];
        $_POST['type_id'] = $myrow["type_id"];
        $_POST['group_code']=$myrow["code"];
        $_POST['group_description']=$myrow["description"];
        $_POST['task_name'] = $myrow["task_name"];
        $_POST['long_description'] = $myrow["long_description"];
        $_POST['boq_group_id'] = $myrow["boq_group_id"];
        $_POST['start_date'] = sql2date($myrow["start_date"]);
        $_POST['end_date'] = sql2date($myrow["end_date"]);

    //    if ($myrow['approval_path_id'] != 0)
    //    {
    //        $_POST['approval_path_id'] = $myrow["approval_path_id"];
    //    }
    //    else 
    //    {
    //        $_POST['approval_path_id'] = -1;
    //    }
    }
    else{
        $project = get_project($project_id);
        $_POST['start_date'] = sql2date($project["start_date"]);
        $_POST['end_date'] = sql2date($project["end_date"]);
    }


    br();
    display_heading2("Budget Group");
    

    start_table(TABLESTYLE2);

    table_section_title(_("General"));
    
    if($Mode == 'Edit'){
//        label_row(_("Name:"), $_POST['task_name']);
        value_list_row("Type :", 'type_id', 'PROJECT_TASK_TYPES', null, "Select Type Name");
    }
    else{
        value_list_row("Type :", 'type_id', 'PROJECT_TASK_TYPES', null, "Select Type Name", true);
    }
    
    if(list_updated('type_id')){
        $list_value = get_list_value($_POST['type_id']);
        if(isset($list_value['value_code'])){
            $_POST['group_code'] = $list_value['value_code'];
            $_POST['group_description'] = $list_value['value_name'];
        }
    }
    text_row(_("Code:"), 'group_code', null, 25, 50);
    text_row(_("Description:"), 'group_description', null, 50, 50);
    date_row(_("Start Date:"), 'start_date');
    date_row(_("End Date:"), 'end_date');
    textarea_row(_("Long Description:"), 'long_description', null, 50, 3);

    project_boq_item_groups_list_row("BOQ Item Group:", 'boq_group_id', $_POST['project_id'], null, 'Select BOQ Item Group', false);

    end_table(1);

    hidden('selected_id', $selected_id);

}

    
function display_task_edit_controls(&$Mode, $selected_id, $project_id)
{
        
    br();
    
    display_heading2("Budgets");
    
    start_table(TABLESTYLE, "width=90%");

    $th = array(_("Detail Type Code"),_("Detail Type Name"), 
                "Budget Id", //_("Budget Code"), _("Budget Description"), 
                _("New Budget"), _("Current Budget"), _("Budget Used"), _("Budget Allocated"), "Budget Available","", "");

    table_header($th);

    $k = 0;
    
    $tasks_list = get_task_group_tasks($project_id, $selected_id);
    while ($myrow = db_fetch($tasks_list))
    {
        alt_table_row_color($k);

//        label_cell($myrow["detail_type_id"]);
        label_cell($myrow["detail_type_code"]);
        label_cell($myrow["detail_type_name"]);
        label_cell($myrow["task_id"]);
        
        $_POST['budget_'.$myrow["detail_type_code"]] = $myrow["new_budget"];
        amount_cells(null, 'budget_'.$myrow["detail_type_code"]);
        
//        label_cell($myrow["description"]);
        if(isset($myrow["task_id"]) && $myrow["task_id"] > 0){
            amount_cell($myrow["budget"]);
            amount_cell($myrow["budget_used"]);
            amount_cell($myrow["budget_allocated"]);
            amount_cell($myrow["budget"] - ($myrow["budget_used"] + $myrow["budget_allocated"]));
        }
        else{
            label_cell('');label_cell('');label_cell('');label_cell('');
        }
        
        check_cells('', 'selected_'.$myrow["detail_type_code"],0);
        
        end_row();

    }

    end_table();
}

function display_edit_controls(&$Mode, $selected_id, $project_id)
{
    if($project_id>0){
        display_task_group_edit_controls($Mode, $selected_id, $project_id);
    

        display_task_edit_controls($Mode, $selected_id, $project_id);
        
        br();
        
        submit_add_or_update_center($selected_id == -1, '', 'both');
    }

}
    




if ($Mode=='ADD_ITEM' || $Mode=='UPDATE_ITEM') 
{
    if(!can_commit_task($selected_id, $Mode)){
        if( $Mode=='UPDATE_ITEM'){
            $Mode = "Edit";
        }
        else{
            $Mode = "";
        }
    }
    else{
        save_details($selected_id, $Mode);
	}
       // hidden('approval_path_id', $_POST['approval_path_id']);

}

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

if ($Mode == 'Delete')
{
	//the link to delete a selected record was clicked
	delete_task($selected_id);
	display_notification(_("The selected task has been deleted."));
	$Mode = 'RESET';
}

if ($Mode == 'Cancel')
{
    clear_task_data();
	$selected_id = -1;
}

if ($Mode == 'RESET')
{
    clear_task_data();
	$selected_id = -1;
}

//--------------------------------------------------------------------------------------------------------
//$tasks = get_task($_POST['project_id']);

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


start_table(TABLESTYLE_NOBORDER);
start_row();
project_list_cells(_("Project:"), 'project_id', null,
  _('New project'), true, check_value('show_inactive'));

$project_id = get_post('project_id');
//	check_cells(_("Show inactive:"), 'show_inactive', null, true);
end_row();
//end_table();
//
//start_table(TABLESTYLE_NOBORDER);
start_row();
project_boq_item_groups_list_cells("BOQ Item Group:", 'filtering_group_id', $project_id, null, '', true);
end_row();

if(get_post('filtering_group_id') > 0){
    $filetering_group_id = get_post('filtering_group_id');
}
else{
    $filetering_group_id = 0;
}

start_row();
group_task_groups_list_cells("Budget Group:", 'task_group_id', $project_id, $filetering_group_id, get_post('task_group_id'), 'New Budget Group', true);
end_row();

end_table();
	
br(2);
    
display_task_groups_summary($filetering_group_id, $project_id);

//display_task_groups($_POST['project_id'], $_POST['filtering_group_id']);
//------------------------------------------------------------------------------------------------

if(get_post('task_group_id') > 0){
    $selected_id = get_post('task_group_id');
    $Mode = 'Edit';
}
else{
    $selected_id = -1;
}

display_edit_controls($Mode, $selected_id, $project_id);

br();

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


?>
