<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_EST_PROJECT_BOQ_ITEMS';
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 . "/estimation/includes/db/est_projects_db.inc");
include_once($path_to_root . "/estimation/includes/db/est_project_boq_items_db.inc");
include_once($path_to_root . "/estimation/includes/db/est_project_boq_item_detail_edit_db.inc");

include_once($path_to_root . "/admin/db/list_values_db.inc");
include_once($path_to_root . "/includes/ui/ui_lists_estimation.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 = "Estimation BOQ Items"), 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['est_project_id']))
{
	$_POST['est_project_id'] = $_GET['est_project_id'];
}
//---------------------------------------------------------------------------------------------------

//set_global_stock_item($_POST['est_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_process($selected_id = -1)
{
        if(!(get_post('est_project_id') > 0 ))
        {
            display_error( _("Please Select an Estimation Project."));
            set_focus('code');
            return false;  
        }
        
        $project = get_est_project_record(get_post('est_project_id'));
        if(!($project['approval_status'] == AS_NEW || $project['approval_status'] == AS_WITH_THE_APPROVER || 
                $project['approval_status'] == AS_AWAITING_APPROVAL || $project['approval_status'] == AS_BACK_TO_ORIGINATOR || 
                $project['approval_status'] == AS_REOPENED)){
            display_error("This project status does not allow further updating.");
            return false;
        }
        
        if(get_post('code') == '')
        {
            display_error( _("Enter a code."));
            set_focus('code');
            return false;  
        }
        
        if (get_post('description') == '')
        {
            display_error( _("Enter description."));
            set_focus('code');
            return false;  
        }

        if(!(get_post('billing_type') > 0 ))
        {
            display_error( _("Select a billing type."));
            set_focus('code');
            return false;  
        }
        
        if(check_num('rate',0) == FALSE){
            display_error(_("Rate must be numeric and positive."));
            set_focus('rate');
            return false;
        } 

        if(!(get_post('tax_group_id') > 0 ))
        {
            display_error( _('Please select a tax group.'));
            set_focus('tax_group_id');
            return;            
        }
        
        if(check_num('max_quantity',0.000000001) == FALSE)
        {
            display_error(_("Maximum quantity must be numeric and positive."));
            set_focus('max_quantity');
            return false;
        } 
        
        
        $count = get_existing_code_from_est_project_boq_items(get_post('est_project_id'), get_post('code'), $selected_id);
        if($count > 0)
        {
           display_error("Entered code already exists.");
           set_focus('code');
           return false;        
        }
    
   // }
    return true; 
}

function display_boq_items($est_project_id, $boq_group_id)
{
    $billings_list = get_project_group_boq_items($est_project_id, $boq_group_id);

    div_start('price_table');

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

    $th = array(_("Display Order"),_("Code"), _("Description"), 
                _("Calculated Cost"),_("Manual Cost"), _("Use Cost"),
                "Billing Type", _("Unit"), _("Rate"), _("Quantity"), _("Tax Group"),
                _("Group"), "", "");

    table_header($th);

    $k = 0; //row colour counter
    $name_yes = 0;
    $calculated = false;
    $group_id = 0;

    //global $project_billing_types;

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

        label_cell($myrow["display_order"]); 
       // if($myrow["type"] == 1){
        label_cell($myrow["code"]);
        label_cell($myrow["description"]);
        
        amount_decimal_cell($myrow["calculated_cost"]);
        amount_decimal_cell($myrow["manual_cost"]);
        
        if($myrow["use_manual_cost"] == 1){
            label_cell("Manual Cost");
        }else{
            label_cell("Calculated Cost");
        }

        if($myrow["type"] == 1){
            label_cell("Lump Sum");
        }else{
            label_cell("Measure and Pay");
        }

        label_cell($myrow["unit"]);
        amount_cell($myrow["rate"]);   
        amount_cell($myrow["max_quantity"]);  
        label_cell($myrow["tax_name"]); 

        $group_name = "";
        if($myrow["group_id"] > 0){
            $group_name = $myrow["billing_item_group_code"]. '-' .$myrow["billing_item_group_description"]; 
        }
        label_cell($group_name);     

        edit_button_cell("Edit".$myrow['id'], _("Edit"));
        delete_button_cell("Delete".$myrow['id'], _("Delete"));
        end_row();
    }

    end_table();
    div_end();
}


function display_est_boq_item_edit_controls(&$Mode, $selected_id)
{
    display_heading2("Estimation BOQ Item");
    
    if ($Mode == 'Edit')
    {
        $myrow = get_est_project_boq_item_details($selected_id);

            $_POST['type_id'] = $myrow["type_id"];
            $_POST['code'] = $myrow["code"];
            $_POST['description'] = $myrow["description"];
            $_POST['billing_type'] = $myrow["billing_type"];
            $_POST['unit'] = $myrow["unit"];
            $_POST['rate'] = $myrow["rate"];
            $_POST['max_quantity'] = $myrow["max_quantity"];      
            $_POST['tax_group_id'] = $myrow["tax_group_id"]; 
           // $_POST['type'] = $myrow["type"];
            $_POST['display_order'] = $myrow["display_order"];
            $_POST['group_id'] = $myrow["group_id"];
            $_POST['long_description'] = $myrow["long_description"];
            $_POST['print_long_description'] = $myrow["print_long_description"];
            $_POST['calculated_cost'] = $myrow["calculated_cost"];  
    }
    else{
        $_POST['calculated_cost'] = 0;
    }


    hidden('selected_id', $selected_id);
    
    if (@$_GET['popup'])
    {
        hidden('_tabs_sel', get_post('_tabs_sel'));
        hidden('popup', @$_GET['popup']);
    }

//    div_start('price_details');

//    start_table(TABLESTYLE2);
//
//    table_section(1);
    
    start_outer_table(TABLESTYLE2, "width=60%");

	table_section(1);
    table_section_title(_("General"));
        
    if($Mode == 'Edit'){
        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['code'] = $list_value['value_code'];
            $_POST['description'] = $list_value['value_name'];
        }
    }
    
    text_row(_("Code:"), 'code', null, 50, 200);
    textarea_row(_("Description:"), 'description', null, 31, 3);
    text_row(_("Display Order:"), 'display_order', null, 20, 20);    
    stock_units_list_row(_("Units:"), 'unit', null);
    est_project_boq_item_groups_list_row("Estimation BOQ Item Group:", 'group_id', $_POST['est_project_id'], null, 'Select Estimation BOQ Item Group', false);
    
    table_section_title(_("Cost"));
    label_row("Calculated Cost", number_format($_POST['calculated_cost'], 2));
    
    table_section(2);
    table_section_title(_("Billing"));
    project_billing_types_list_row("Billing Type", "billing_type", null);
    amount_row(_("Rate:"), 'rate');
    amount_row(_("Quantity:"), 'max_quantity');
    tax_groups_list_row("Tax Group:", 'tax_group_id', null, ('Select a tax group'));
    
    table_section_title(_("Other"));
    textarea_row(_("Long Description:"), 'long_description', null, 31, 6);
    yesno_list_row("Print Long Description", 'print_long_description', null, "Yes", "No", false);
    
    end_outer_table(1);

    submit_add_or_update_center($selected_id == -1, '', 'both');

//    div_end();
}


function display_boq_item_components($selected_id)
{
    global $project_boq_item_component_primary_types;
    
    br(2);
    
    display_heading2("Estimation BOQ Item Components");
    start_table(TABLESTYLE, "width=60%");

    $th = array(_("Detail Type"),"Category", _("Id"), "Primary Type", _("Cost"), "", "");

    table_header($th);
    
    $result = get_est_boq_item_components($selected_id);
    
    $k = 0;
    while ($myrow = db_fetch($result))
    {
        alt_table_row_color($k);

        label_cell($myrow["detail_type_name"]);
        label_cell($myrow["category_name"]);
        label_cell($myrow["id"]);
        if($myrow["primary_type"] > 0){
            label_cell($project_boq_item_component_primary_types[$myrow["primary_type"]]);
        }
        else{
            label_cell("");
        }
        amount_decimal_cell($myrow["cost"]);
        
        delete_button_cell("Delete_BOQ_Item_Component_Costs".$myrow['id'], _("Delete"));
        
        $edit_link = get_estimation_trans_view_str(ST_EST_PROJECT_BOQ_ITEM_DETAIL_EDIT, $selected_id."|".$myrow["value_code"],"Details");
        label_cell($edit_link, "align=center");   
        
        end_row();

    }
    
    end_table();
    
    br();
    
    submit_center_first('REFRESH_BOQ_ITEM', _("Refresh"), '', 'default');
    
    br(2);
}


if ($Mode=='ADD_ITEM' && can_process($selected_id)) 
{
    if ($input_error =='0') 
    {
        if(get_post('group_id') < 0){
            $group_id = 0;
        }
        else{
            $group_id = get_post('group_id');
        }

        $new_boq_iem_id = add_est_project_boq_item(get_post('est_project_id'), get_post('type_id'), get_post('display_order'), get_post('code'),
                                               get_post('description'), get_post('billing_type'), get_post('unit'), input_num('rate'), 
                                               input_num('max_quantity'), get_post('long_description'), get_post('print_long_description'), 
                                               get_post('tax_group_id'), $group_id);
                                 
        hidden('selected_id', $new_boq_iem_id);
        $selected_id = $new_boq_iem_id;
        $Mode = "Edit";
        
        clear_task_data();
        $msg = _("The new Estimation project BOQ item has been added.");            
        display_notification($msg);
//        $Mode = 'RESET';
    }
	
}
if ($Mode=='UPDATE_ITEM' && can_process($selected_id)) 
{
if ($input_error =='0') 
    {
        if(get_post('group_id') < 0){
            $group_id = 0;
        }
        else{
            $group_id = get_post('group_id');
        }
        
        update_est_project_boq_item($selected_id, get_post('display_order'), get_post('type_id'), get_post('code'),
                                    get_post('description'), get_post('billing_type'), get_post('unit'), input_num('rate'), 
                                    input_num('max_quantity'), get_post('long_description'), get_post('print_long_description'), 
                                    get_post('tax_group_id'), $group_id);
        clear_task_data();
        $msg = _("This project BOQ item has been updated.");
        
        display_notification($msg);
        $_post['boq_item_id'] = -1;
        $selected_id = -1;
        $Mode = 'RESET';
    }
}
//------------------------------------------------------------------------------------------------------

$delete_boq_item_component_id  = find_submit("Delete_BOQ_Item_Component_Costs");
if ($delete_boq_item_component_id > 0)
{
    
    
    include_once($path_to_root . "/estimation/includes/db/est_project_boq_item_costs_db.inc");
    include_once($path_to_root . "/estimation/includes/db/est_project_boq_item_material_db.inc");
    include_once($path_to_root . "/estimation/includes/db/est_project_boq_item_labour_db.inc");
    include_once($path_to_root . "/estimation/includes/db/est_project_boq_item_assets_db.inc");
    include_once($path_to_root . "/estimation/includes/db/est_project_boq_item_transport_db.inc");
    
    begin_transaction();
    
    $sbp_msg = delete_est_boq_item_component(get_post('boq_item_id'), $delete_boq_item_component_id);
    if($sbp_msg['success'] === true){
        commit_transaction();
        $Mode = 'RESET';
        $selected_id = -1;

        display_notification(_('Selected BOQ Item Labour detail has been deleted'));
    }
    else{
        cancel_transaction();
    }
	
	
}

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

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

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

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:"), 'est_project_id', null,
//  _('Select a project'), true, check_value('show_inactive'));

est_project_list_cells(_("Project:"), 'est_project_id', null, _('Select an Estimation project'), true, check_value('show_inactive'));


$est_project_id = get_post('est_project_id');
//	check_cells(_("Show inactive:"), 'show_inactive', null, true);
end_row();
start_row();
est_project_boq_item_groups_list_cells("BOQ Item Group:", 'filtering_group_id', $est_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();
est_group_boq_items_list_cells("BOQ Item:", 'boq_item_id', $est_project_id, $filetering_group_id, get_post('boq_item_id'), 'New BOQ Item', true);
end_row();

end_table();




	
br(2);

//display_boq_items($_POST['est_project_id'], $_POST['filtering_group_id']);
//------------------------------------------------------------------------------------------------

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

$Ajax->Activate('boq_item_edit_controls');

div_start('boq_item_edit_controls');
display_est_boq_item_edit_controls($Mode, $selected_id);//header
div_end();

$Ajax->Activate('boq_item_components');

div_start('boq_item_components');

if($selected_id > 0){
    display_boq_item_components($selected_id);//details
}

div_end();

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


?>
