<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_COPY_BOQ_ITEMS_TO_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/project_boq_items_db.inc");
include_once($path_to_root . "/projects/includes/db/project_boq_item_detail_edit_db.inc");
include_once($path_to_root . "/projects/includes/db/copy_project_boq_items_to_tasks_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 ($SysPrefs->use_popup_windows) {
	$js .= get_js_open_window(900, 500);
}

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

page(_($help_context = "Copy BOQ Item Components to Budegts"), 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['type_id']);
    unset($_POST['code']);
	unset($_POST['description']);
    unset($_POST['billing_type']);
	unset($_POST['rate']);
	unset($_POST['unit']);
	unset($_POST['max_quantity']);
    unset($_POST['long_description']);	
    unset($_POST['tax_group_id']);	
}
//----------------------------------------------------------------------------------------------------
function can_copy_project_task_group($project, $row, $task_group_code, $task_group_description,
                                        $task_group_start_date, $task_group_end_date, $type_id)
{        
        $boq_item_id = $row['boq_item_id'];
        if(!($type_id > 0))
        {
            $message = "No Type defined for the BOQ item ".$row['boq_item_code']." - ".$row['boq_item_description'].". Can not save a Budget Group without a Type. Please save the BOQ Item with a Type first.";
            $set_focus = 'task_group_code_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);  
        }
        
        if(!(strlen($task_group_code) > 0))
        {
            $message = "Budget group code can not be empty.";
            $set_focus = 'task_group_code_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);  
        }
        
        if(!(strlen($task_group_description) > 0))
        {
            $message = "Budget group description can not be empty.";
            $set_focus = 'task_group_description_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);  
        }

        $nrows = get_existing_code_from_project_task_groups($project['project_id'], $task_group_code, 0);
        if($nrows > 0 )
        {
            $message = ( _("Budget group code already exists."));
            $set_focus = 'task_group_code_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);   
        }

        if(!(is_date($task_group_start_date)))
        {
            $message = ( _("Budget group start date is not a valid date."));
            $set_focus = 'start_date_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);           
        }
        
        if(!(is_date($task_group_end_date)))
        {
            $message = ( _("Budget group end date is not a valid date."));
            $set_focus = 'end_date_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);           
        }
        
        if (date1_greater_date2($task_group_start_date, $task_group_end_date))
        {
            $message = ( _("Budget group end date can not be earlier than Budget group start date"));
            $set_focus = 'end_date_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);    
        }
        
        $project_start_date = sql2date($project['start_date']);
        $project_end_date = sql2date($project['end_date']);

        if (date1_greater_date2($project_start_date, $task_group_start_date))
        {
            $message = ( _("Budget group start date can not be ealier than project start date"));
            $set_focus = 'end_date_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);  
        }
            
        if (date1_greater_date2($task_group_end_date, $project_end_date))
        {
            $message = ( _("Budget group end date can not be later than project end date"));
            $set_focus = 'end_date_'.$boq_item_id;
            return array("success" => false, "set_focus" => $set_focus, 'message' => $message);  
        }
        
        return array("success" => true, 'message' => '');  
}

function can_copy_project_task($project, $component, $task_id)
{
    $this_task_budget = $component['cost'];
    if(!($this_task_budget > 0))
    {
        $message = ( _("Budget value entered is zero. Can not save budget record."));
        $set_focus = 'budget_'.$component['component_id'];
        return array("success" => false, "set_focus" => $set_focus, 'message' => $message);  
    }

    $other_tasks_budget_total = get_other_task_budgets_total($project['project_id'], $task_id);
    $new_project_budget = $other_tasks_budget_total + $this_task_budget; 
    if($new_project_budget > $project['estimated_cost'])
    {
        $message = ( _("With the cost entered for detail type ".$component['detail_type_name'].", the total of all the individual budgets will exceed the project total cost."));
        $set_focus = 'budget_'.$component['component_id'];
        return array("success" => false, "set_focus" => $set_focus, 'message' => $message);  
    }    
    
    return array("success" => true, 'message' => '');  
}


function display_tasks_and_boq_items($project_id, $boq_group_id, $copy_type)
{
    if(!($boq_group_id > 0)){
        $boq_group_id = 0;
    }
    
    $project = get_project($project_id);
    
    start_table(TABLESTYLE, "width=90%");
    $th = array(_('Detil Type'),_('BOQ Item'),_('Budget Group Code'), "Budget Group Description", "Start Date", "Start Date", "Budget", "");
//inactive_control_column($th);

    table_header($th);
    $k = 0; //row colour counter

    $result = get_all_budget_group_codes_and_boq_item_codes($project_id, $boq_group_id);
    
    while ($group_code = db_fetch($result)) {
        
        $boq_item = get_project_boq_item_record_by_code($project_id, $group_code['code']);
        $boq_item_id = $boq_item['id'];
        $boqi_code = $boq_item['code'];
        $boqi_description = $boq_item['description'];
        
        $task_group = get_task_group_details_by_code($project_id, $group_code['code']);
        $tg_code = $task_group['code'];
        $tg_description = $task_group['description'];
        
        start_row();
        label_cell('');
        if(strlen($boqi_code) > 0){
            label_cell('<b>'.$boqi_code.' - '.$boqi_description.'</b>');
        }
        else{
            label_cell('');
        }
        
        if(strlen($tg_code) > 0){
            label_cell('<b>'.$tg_code.'</b>');
            label_cell('<b>'.$tg_description.'</b>');
            label_cell('');
            label_cell('');
        }
        else{
            if(strlen($boqi_code) > 0){
                if(!isset($_POST['task_group_code_'.$boq_item_id])){
                    $_POST['task_group_code_'.$boq_item_id] = $boqi_code;
                }
                if(!isset($_POST['task_group_description_'.$boq_item_id])){
                    $_POST['task_group_description_'.$boq_item_id] = $boqi_description;
                }
                if(!isset($_POST['start_date_'.$boq_item_id])){
                    $_POST['start_date_'.$boq_item_id] = sql2date($project['start_date']);
                }
                if(!isset($_POST['end_date_'.$boq_item_id])){
                    $_POST['end_date_'.$boq_item_id] = sql2date($project['end_date']);
                }
                text_cells(null, 'task_group_code_'.$boq_item_id, null, 25, 50);
                text_cells(null, 'task_group_description_'.$boq_item_id, null, 50, 200);
                date_cells(null, 'start_date_'.$boq_item_id);
                date_cells(null, 'end_date_'.$boq_item_id);
            }
            else{
                label_cell('');
                label_cell('');
                label_cell('');
                label_cell('');
            }
            
            label_cell('');
        }
        
        label_cell('');
        end_row();
        
        $list_values_result = get_all_list_values('PROJECT_TASK_DETAIL_TYPES');
        while ($detail_type = db_fetch($list_values_result)) {
            $has_boqic = $has_task = false;
            $boqi_component_id = 0;
            $boqi_component = get_boq_item_component_record($boq_item['id'], $detail_type['value_code']);
            if(isset($boqi_component['id']) && $boqi_component['id'] > 0){
                $has_boqic = true;
                $boqi_component_id = $boqi_component['id'];
            }
            
            $task = get_task_record_by_detail_type($task_group['id'], $detail_type['value_code']);
            if(isset($task['task_id']) && $task['task_id'] > 0){
                $has_task = true;
            }
            
            if($has_boqic || $has_task){
                alt_table_row_color($k);
                label_cell($detail_type['value_name']);
                
                if($has_boqic){
                    amount_decimal_cell($boqi_component['cost']);
                }
                else{
                    label_cell('No BOQ item', 'align=center');
                }
                
                label_cell('', 'colspan=4');
                        
                if($has_task){
                    amount_decimal_cell($task['budget']);
                }
                else{
                    label_cell('No budget', 'align=center');
                }
                
                _show_copy_select_check_box($boqi_component_id, $has_boqic, $has_task, $copy_type);
                end_row();
            }
        
        }
        
    }    
        
    end_table(1);
        
        
    
}
    
function _show_copy_select_check_box($id, $has_boqic, $has_task, $copy_type)
{
    if($copy_type === 0){
        unset($_POST['line_selected_'.$id]);
        label_cell('');
        return;
    }
    
    switch ($copy_type) {
        case 'CREATE_BUDGETS':
            if($has_boqic === true && $has_task === false){
                check_cells(null, 'line_selected_'.$id);
            }
            else{
                label_cell('');
            }
            break;
        case 'UPDATE_BUDGETS':
            if($has_boqic === true && $has_task === true){
                check_cells(null, 'line_selected_'.$id);
            }
            else{
                label_cell('');
            }
            break;
        case 'CREATE_UPDATE_BUDGETS':
            if($has_boqic === true){
                check_cells(null, 'line_selected_'.$id);
            }
            else{
                label_cell('');
            }
            break;
        default:
            unset($_POST['line_selected_'.$id]);
            label_cell('');
            break;
    }
}





function save_selected_budgets($project_id, $boq_group_id, $copy_type) 
{
    if($copy_type === 0){
        return array("success" => false, "message" => "No Copy Type selected. Not possible to proceed with coping budgets.");
    }
    
    if(!($boq_group_id > 0)){
        $boq_group_id = 0;
    }
    $project = get_project_record($project_id);
    
    $budget_freeze_date = sql2date($project['budget_freeze_date']);
    if(date1_greater_date2(Today(), $budget_freeze_date)){
        $m = "All budgets of this project are frozen and can not be updated.";
        return array("success" => false, "message" => $m);
    }
    
    $result = get_project_boq_group_boq_item_components($project_id, $boq_group_id);
    while ($row = db_fetch($result)){
        if(!(isset($_POST['line_selected_'.$row['component_id']]) && $_POST['line_selected_'.$row['component_id']] == true)){
            continue;
        }
        
        //Save this budget
        $boq_item_id = $row['boq_item_id'];
        $task_group = get_task_group_record_by_code($project_id, $row['boq_item_code']);
        
        begin_transaction();
        if(isset($task_group['id']) && $task_group['id'] > 0){
            $task_group_id = $task_group['id'];
        }
        else{
            
            $task_group_code = $_POST['task_group_code_'.$boq_item_id];
            $task_group_description = $_POST['task_group_description_'.$boq_item_id];
            $task_group_start_date = $_POST['start_date_'.$boq_item_id];
            $task_group_end_date = $_POST['end_date_'.$boq_item_id];
            $type_id = $row['boq_item_type_id'];
            $long_description = $row['boq_item_long_description'];
            
            $ccptg_msg = can_copy_project_task_group($project, $row, $task_group_code, $task_group_description,
                                        $task_group_start_date, $task_group_end_date, $type_id);
            if($ccptg_msg['success'] !== true){
                $ccptg_msg['message'] = "Coping terminated @ BOQ Item ".$row['boq_item_code']." - ".$row['boq_item_description']." - "
                                        .$ccptg_msg['message'];
                return $ccptg_msg;
            }
            
            $task_group_id = add_task_group_details($project_id, $task_group_code, $task_group_description, $type_id, 
                                                    $long_description, $task_group_start_date, $task_group_end_date, $boq_group_id);

        }
        
        $ssb_msg = save_selected_budget($project, $row, $task_group_id, $copy_type);
        if($ssb_msg['success'] !== true){
            cancel_transaction();
            $ssb_msg['message'] = "Coping terminated @ BOQ Item ".$row['boq_item_code']." - ".$row['boq_item_description']." - "
                                    .$ssb_msg['message'];
            return $ssb_msg;
        }
        else{
            commit_transaction();
        }
    }
    
    return array("success" => true, "message" => "");
}

function save_selected_budget($project, $row, $task_group_id, $copy_type)
{
    $project_id = $project['project_id'];
    $task_id = 0;
    $task = get_task_record_by_detail_type($task_group_id, $row['detail_type_code']);
    if(isset($task['task_id']) && $task['task_id'] > 0){
        $task_id = $task['task_id'];
    }
    
    $ccpt_msg = can_copy_project_task($project, $row, $task_id);
    if($ccpt_msg['success'] !== true){
        return $ccpt_msg;
    }
    
    $task_code = $row['boq_item_code'].'-'.$row["detail_type_code"];
    
    if($row["detail_type_code"] == "ALL"){
        $task_description = $row['boq_item_description'];
    }
    else{
        $task_description = $row['boq_item_description'].'-'.$row["detail_type_name"];
    }

    $type_id = $row['boq_item_type_id'];
    $budget = $row['cost'];
    $detail_type_code = $row['detail_type_code'];
    
    switch ($copy_type) {
        case 'CREATE_BUDGETS':
            if($task_id > 0){
                return array("success" => false, "message" => "A budget already exists for detail type ".$row['detail_type_code']);
            }
            else{
                add_task($project_id, $task_code, $task_description, $type_id, $budget, $task_group_id, $detail_type_code);
                unset($_POST['line_selected_'.$row['component_id']]);
                return array("success" => true, "message" => "");
            }
            break;
        case 'UPDATE_BUDGETS':
            if(!($task_id > 0)){
                return array("success" => false, "message" => "No existing budget for the detail type ".$row['detail_type_code']);
            }
            else{
                update_task_details($task_id, $task_code, $task_description, $type_id, $budget, $task_group_id);
                unset($_POST['line_selected_'.$row['component_id']]);
                return array("success" => true, "message" => "");
            }
            break;
        case 'CREATE_UPDATE_BUDGETS':
            if($task_id > 0){
                update_task_details($task_id, $task_code, $task_description, $type_id, $budget, $task_group_id);
                unset($_POST['line_selected_'.$row['component_id']]);
                return array("success" => true, "message" => "");
            }
            else{
                add_task($project_id, $task_code, $task_description, $type_id, $budget, $task_group_id, $detail_type_code);
                unset($_POST['line_selected_'.$row['component_id']]);
                return array("success" => true, "message" => "");
            }
            break;
        default:
            return array("success" => false, "message" => "Unknown Copy Type $copy_type.");
    }
}


if (isset($_POST['Copy_BOQ_Items_To_Budgets'])) 
{
    $ssb_msg = save_selected_budgets($_POST['project_id'], $_POST['filtering_group_id'], $_POST['copy_type']);
    if($ssb_msg['success'] !== true){
        display_error($ssb_msg['message']);
    }
    else{
        display_notification("Selected BOQ Item Components have been copied to Budgets.");
    }
}

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



if(isset($_POST['Cancel']))
{
    $Mode = 'RESET';
	$selected_id = -1;
}


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

global  $Ajax;

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

	br();


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

$project_id = get_post('project_id');
//	check_cells(_("Show inactive:"), 'show_inactive', null, true);
end_row();
start_row();
project_boq_item_groups_list_cells("BOQ Item Group:", 'filtering_group_id', $project_id, null, 'No BOQ Item Group', 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_boq_items_list_cells("BOQ Item:", 'boq_item_id', $project_id, $filetering_group_id, get_post('boq_item_id'), 'All BOQ Items', true);
//end_row();

if(!isset($_POST['copy_type'])){
    $_POST['copy_type'] = 'CREATE_BUDGETS';
}
start_row();

$values_array['CREATE_BUDGETS'] = "Create New Budgets";
$values_array['UPDATE_BUDGETS'] = "Update Existing Budgets for Matching BOQ Items";
$values_array['CREATE_UPDATE_BUDGETS'] = "Create New Budgets and Update Existing Budgets";

custom_values_list_cells("Copy Type:", 'copy_type', $values_array, null, null, true);
end_row();

end_table();


$Ajax->activate('boq_component_details');

	
br(2);

div_start('boq_component_details');

display_tasks_and_boq_items($_POST['project_id'], $_POST['filtering_group_id'], $_POST['copy_type']);

div_end();

submit('Copy_BOQ_Items_To_Budgets', 'Process', true, '', 'default');


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


?>
