<?php
/**********************************************************************
***********************************************************************/

function can_process_boq_item($boq_item)
{
    if(!($boq_item['project_id'] > 0 ))
        {
            $message = ( _("Please Select a Project."));
            $set_focus = ('code');
            return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);  
        }
        
        if($boq_item['code'] == '')
        {
            $message = ( _("Enter a code."));
            $set_focus = ('code');
            return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);  
        }
        
        if ($boq_item['description'] == '')
        {
            $message = ( _("Enter description."));
            $set_focus = ('code');
            return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);   
        }

//        if(!($boq_item['billing_type'] > 0 ))
//        {
//            $message = ( _("Select a billing type."));
//            $set_focus = ('code');
//            return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);  
//        }
        
        $actual_start_date = $boq_item['actual_start_date'];
        if ($boq_item['started'] == 1) {
            if (! is_date($actual_start_date)) {
                $message = (_("Entered actual start date is not a valid date."));
                $set_focus = ('actual_start_date');
                return array("success" => false, "set_focus"=> $set_focus, "message" => $message);  
            }
        }
        
        $actual_end_date = $boq_item['actual_end_date'];
        if ($boq_item['completed'] == 1) {
            if (! is_date($actual_end_date)) {
                $message = (_("Entered actual end date is not a valid date."));
                $set_focus = ('actual_end_date');
                return array("success" => false, "set_focus"=> $set_focus, "message" => $message);  
            }
        }
        
        if ($boq_item['started'] == 1 && $boq_item['completed'] == 1) {
            if (date1_greater_date2($actual_start_date, $actual_end_date)) {
                $message = (_("Actual start date cannot bigger than actual end date."));
                $set_focus = ('actual_start_date');
                return array("success" => false, "set_focus"=> $set_focus, "message" => $message);  
            }
        }
        
        if ($boq_item['id'] > 0) {
            $wd_ft_row = get_first_work_done_entry_detail_boq_item_record($boq_item['id']);
                if (isset($wd_ft_row['id']) && $wd_ft_row['id'] > 0) {
                    if ($boq_item['started'] == 0) {
                        $message = (_("Started value cannot select as 'No' because work done records are already added."));
                        $set_focus = ('started');
                        return array("success" => false, "set_focus"=> $set_focus, "message" => $message); 
                    }

                    $wd_ft_tran_date = sql2date($wd_ft_row['tran_date']);
                    if (date1_greater_date2($actual_start_date, $wd_ft_tran_date)) {
                        if ($boq_item['started'] == 0) {
                            $message = (_("Cannot set started value as 'No' and start date cannot bigger than work done first tran date on $wd_ft_tran_date."));
                            $set_focus = ('started');
                        } else {
                            $message = (_("Actual start date cannot bigger than work done first date on $wd_ft_tran_date."));
                            $set_focus = ('actual_start_date');
                        }
                        return array("success" => false, "set_focus"=> $set_focus, "message" => $message);  
                    }
                }

            if ($boq_item['completed'] == 1) {
                $wd_lt_row = get_boq_item_last_work_done_entry_date_from_details($boq_item['id']);
                    if (isset($wd_lt_row['id']) && $wd_lt_row['id'] > 0) {
                        $wd_lt_tran_date = sql2date($wd_lt_row['tran_date']);
                        if (date1_greater_date2($wd_lt_tran_date, $actual_end_date)) {
                            $message = (_("Actual end date cannot smaller than work done last tran date on $wd_lt_tran_date."));
                            $set_focus = ('actual_end_date');
                            return array("success" => false, "set_focus"=> $set_focus, "message" => $message);  
                        }
                    }
            }
        }
        
        if(check_num2($boq_item['rate'],0) == FALSE){
            $message = (_("Rate must be numeric and positive."));
            $set_focus = ('rate');
            return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);  
        } 

//        if(!($boq_item['tax_group_id'] > 0 ))
//        {
//            $message = ( _('Please select a tax group.'));
//            $set_focus = ('tax_group_id');
//            return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);            
//        }
        
        if(check_num2($boq_item['max_quantity'],0) == FALSE)
        {
            $message = (_("Quantity must be numeric and positive."));
            $set_focus = ('max_quantity');
            return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);  
        } 
        
        $max_quantity = $boq_item['max_quantity'];
        $row = get_project_boq_item_record($boq_item['id']);
            if (isset($row['id']) && $row['id'] > 0) {
                $completed_qty = $row['completed_qty'];
                    if ($completed_qty > $max_quantity) {
                        $set_focus = ('max_quantity');
                        return array("success" => false, "set_focus" => $set_focus, 
                                     "message" => "Quantity cannot smaller than total work done quantity $completed_qty against this BOQ item.");  
                    }
                    
                $row_state = $row['row_state'];  
            } else {
                $row_state = 0;
            }
            
        $count = get_existing_code_from_project_boq_items($boq_item['project_id'], $boq_item['code'], $boq_item['id']);
        if($count > 0)
        {
           $message = ("Entered code already exists.");
           $set_focus = ('code');
           return array("success"=>false, "set_focus"=>$set_focus, "message"=>$message);      
        }
    
    return array("success"=>true, "set_focus"=>'', "message"=>'', 'row_state' => $row_state);  
}

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

    $th = array(_("Id"), _("Detail Type"),"Category", 
                _("Costs"), _("Materials"),
                //_("Labour"), _("Asstes"), _("Transport"), 
                _("Total Cost"),"");

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

        label_cell($myrow["id"]);
        
        label_cell($myrow["detail_type_name"]);
        label_cell($myrow["category_name"]);
        
        
        
//        if($myrow["primary_type"] > 0){
//            label_cell($project_boq_item_component_primary_types[$myrow["primary_type"]]);
//        }
//        else{
//            label_cell("");
//        }

        $costs = recalculate_boq_item_component_cost($myrow['boq_item_id'], $myrow['detail_type_code']);
        $costs_link = get_project_trans_view_str(ST_PROJECT_BOQ_ITEM_DETAIL_EDIT, $selected_id."&dtype=".$myrow["value_code"]."&ptype=".BOQPT_COST, number_format($costs,2));
        label_cell($costs_link, "align=right"); 

        $material = recalculate_boq_item_component_material($myrow['boq_item_id'], $myrow['detail_type_code']);
        $material_link = get_project_trans_view_str(ST_PROJECT_BOQ_ITEM_DETAIL_EDIT, $selected_id."&dtype=".$myrow["value_code"]."&ptype=".BOQPT_MATERIAL, number_format($material,2));
        label_cell($material_link, "align=right");
        
//        $labour = recalculate_boq_item_component_labour($myrow['boq_item_id'], $myrow['detail_type_code']);
//        $labour_link = get_project_trans_view_str(ST_PROJECT_BOQ_ITEM_DETAIL_EDIT, $selected_id."&dtype=".$myrow["value_code"]."&ptype=".BOQPT_LABOUR, number_format($labour,2));
//        label_cell($labour_link, "align=right");
//        
//        $assets = recalculate_boq_item_component_assets($myrow['boq_item_id'], $myrow['detail_type_code']);
//        $assets_link = get_project_trans_view_str(ST_PROJECT_BOQ_ITEM_DETAIL_EDIT, $selected_id."&dtype=".$myrow["value_code"]."&ptype=".BOQPT_ASSET, number_format($assets,2));
//        label_cell($assets_link, "align=right");
//        
//        $transport = recalculate_boq_item_component_transport($myrow['boq_item_id'], $myrow['detail_type_code']);
//        $transport_link = get_project_trans_view_str(ST_PROJECT_BOQ_ITEM_DETAIL_EDIT, $selected_id."&dtype=".$myrow["value_code"]."&ptype=".BOQPT_TRANSPORT, number_format($transport,2));
//        label_cell($transport_link, "align=right");
        
        amount_decimal_cell($myrow["cost"]);
        
        delete_button_cell("Delete_BOQ_Item_Component_Costs".$myrow['id'], _("Delete"));
        
//        $edit_link = get_project_trans_view_str(ST_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);
}

function build_boq_item_array(&$boq_item, $selected_id)
{
    $boq_item['id']=$selected_id;
    $boq_item['group_id']=$_POST['group_id'];
    $boq_item['project_id'] = $_POST['project_id'];
    $boq_item['type_id']=$_POST['type_id'];
    $boq_item['display_order']=$_POST['display_order'];
    $boq_item['code']=$_POST['code'];
    $boq_item['description']=$_POST['description'];
    $boq_item['billing_type']=$_POST['billing_type'];
    $boq_item['unit']=$_POST['unit'];
    $boq_item['rate']=input_num('rate');
    $boq_item['max_quantity']=input_num('max_quantity');
    $boq_item['long_description']=$_POST['long_description'];
    $boq_item['print_long_description']=$_POST['print_long_description'];
    $boq_item['tax_group_id']=$_POST['tax_group_id'];     
    $boq_item['started'] = $_POST['started'];     
    $boq_item['actual_start_date'] = $_POST['actual_start_date'];     
    $boq_item['completed'] = $_POST['completed'];    
    if ($boq_item['completed'] == 1) {
        $boq_item['actual_end_date'] = $_POST['actual_end_date'];  
    } else {
        $boq_item['actual_end_date'] = sql2date(INFINITE_START_DATE);     
    }
}


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 display_boq_items($project_id, $boq_group_id)
{
    $billings_list = get_project_group_boq_items($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_boq_item_edit_controls(&$Mode, $selected_id)
{
    display_heading2("BOQ Item");
    
    $boq_group_name = "No BOQ item group";
    
    if ($Mode == 'Edit')
    {
        $myrow = get_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"];
            
            $boq_group_name = "";
            if($myrow["group_id"] > 0){
                $boq_group_name = $myrow["billing_item_group_code"]. '-' .$myrow["billing_item_group_description"]; 
            }

            $_POST['long_description'] = $myrow["long_description"];
            $_POST['print_long_description'] = $myrow["print_long_description"];
            $_POST['calculated_cost'] = $myrow["calculated_cost"];  
            
            if (! isset($_POST['started']) || isset($_POST['REFRESH_BOQ_ITEM']) || list_updated('filtering_group_id') || list_updated('boq_item_id')) {
                $_POST['started'] = $myrow["started"];  
            }
            if (! isset($_POST['actual_start_date']) && $myrow["actual_start_date"] != INFINITE_START_DATE || isset($_POST['REFRESH_BOQ_ITEM']) 
                || list_updated('filtering_group_id') || list_updated('boq_item_id')) {
                $_POST['actual_start_date'] = sql2date($myrow["actual_start_date"]);  
            }
            if (! isset($_POST['completed']) || isset($_POST['REFRESH_BOQ_ITEM']) || list_updated('filtering_group_id') || list_updated('boq_item_id')) {
                $_POST['completed'] = $myrow["completed"];  
            }
            if (! isset($_POST['actual_end_date']) && $myrow["actual_end_date"] != INFINITE_START_DATE || isset($_POST['REFRESH_BOQ_ITEM']) 
                 || list_updated('filtering_group_id') || list_updated('boq_item_id')) {
                $_POST['actual_end_date'] = sql2date($myrow["actual_end_date"]);  
            }
    }
    else{
        $_POST['code'] = "";
        $_POST['description'] = "";
        $_POST['long_description'] = "";
        $_POST['display_order'] = 0;
        $_POST['group_id'] = 0;
        $_POST['boq_group_name'] = "";
        $_POST['calculated_cost'] = 0;
    }

    if($_POST["group_id"] == 0){
        $boq_group_name = "No BOQ item group"; 
    }

    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);
//    }
    
    hidden('type_id', 0);
//    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);
    label_row(_("Code:"), $_POST['code']);
    hidden('code', $_POST['code']);
//    textarea_row(_("Description:"), 'description', null, 31, 3);
//    textarea_row(_("Long Description:"), 'long_description', null, 31, 6);
    label_row(_("Description:"), $_POST['description']);
    hidden('description', $_POST['description']);
    
    label_row(_("Long Description:"), $_POST['long_description']);
    hidden('long_description', $_POST['long_description']);
    
//    text_row(_("Display Order:"), 'display_order', null, 20, 20);    
    hidden('display_order', $_POST['display_order']);
    
//    project_boq_item_groups_list_row("BOQ Item Group:", 'group_id', $_POST['project_id'], null, 'Select BOQ Item Group', false);
    label_row("BOQ Group", $boq_group_name);
    hidden('group_id', $_POST['group_id']);
    
    
    table_section_title(_("Dates"));
        $task_group_row = get_task_group_record_by_id($selected_id);
            if (isset($task_group_row['id']) && $task_group_row['id'] > 0) {
                label_row('Planed_Start_Date:', sql2date($task_group_row['start_date']));
                label_row('Planed End Date:', sql2date($task_group_row['end_date']));
                
                if (! isset($_POST['actual_start_date']) || (isset($_POST['actual_start_date']) && $_POST['actual_start_date'] == sql2date(INFINITE_START_DATE))) {
                    $_POST['actual_start_date'] = sql2date($task_group_row['start_date']);  
                }
                if (! isset($_POST['actual_end_date']) || (isset($_POST['actual_end_date']) && $_POST['actual_end_date'] == sql2date(INFINITE_START_DATE))) {
                    $_POST['actual_end_date'] = sql2date($task_group_row['end_date']);  
                }
            }
            
        yesno_list_row('Started:', 'started', null, "Yes", "No", true);
        if ($_POST['started'] == 1) {
            date_row('Actual Start Date:', 'actual_start_date');
        } elseif (isset($_POST['actual_start_date'])) {
            hidden('actual_start_date', $_POST['actual_start_date']);
        } else {
            hidden('actual_start_date', sql2date(INFINITE_START_DATE));
        }
            
        yesno_list_row('Completed:', 'completed', null, "Yes", "No", true);
        if ($_POST['completed'] == 1) {
            date_row('Actual End Date:', 'actual_end_date');
        } elseif (isset($_POST['actual_end_date'])) {
            hidden('actual_end_date', $_POST['actual_end_date']);
        } else {
            hidden('actual_end_date', sql2date(INFINITE_START_DATE));
        }
    
    table_section(2);
    table_section_title(_("Cost"));
    label_row("Calculated Cost", number_format($_POST['calculated_cost'], 2));
    stock_units_list_row(_("Units:"), 'unit', null, true, '');
    
    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'));
    hidden('tax_group_id', 0);
    
//    table_section_title(_("Other"));
//    yesno_list_row("Print Long Description", 'print_long_description', null, "Yes", "No", false);
    hidden('print_long_description', 0);
    
    

    
    end_outer_table(1);

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

//    div_end();
}

