<?php
/**********************************************************************
***********************************************************************/

$page_security = 'SA_PROJECT_BOQ_ITEMS';

$path_to_root = "../..";

//include_once($path_to_root . "/includes/ui.inc");
//include_once($path_to_root . "/payroll/includes/db/nopay_references_db.inc");
//include_once($path_to_root . "/includes/ui/ui_input.inc");
//include_once($path_to_root . "/projects/includes/db/project_boq_items_db.inc");
//include_once($path_to_root . "/includes/session.inc");

//simple_page_mode(true);
//
//if(!isset($selected_id)){
//    global $selected_id;
//}


function display_est_boq_item_material($boq_item_id, $detail_type_code)
{
        $result = get_est_boq_item_material_details($boq_item_id, $detail_type_code);

        $n = db_num_rows($result);    
        if($n == 0){
            display_note("No Materials found.");
            return;
        }    

	start_table(TABLESTYLE, "width=90%");
	$th = array( _("ID"), _("Type") ,_("Item"), _("Description"), 
                     _("Unit"), "Current Cost", _("Applied Cost"),
                     _("Qty"), _("Total"),_("Comment"),'','');
	table_header($th);

	$k = 0;
        $j = "";
        $full_total = 0;                  
        $stock_id = 0;
       
                
	while ($myrow = db_fetch($result))
	{                       
            alt_table_row_color($k);            
            
            if($myrow['item_type'] > 0){
                $material_group = get_material_group_item($myrow['stock_id']);
                $code = $material_group["code"];
                $description = $material_group["description"];
                $unit_name = $myrow['unit_name'];
                $standard_cost = $material_group['cost'];
            }
            else{   
                $stock_item = get_stock_item_edit_info($myrow['stock_id']);
                $code = $stock_item["stock_id"];
                $description = $stock_item["description"];
                $unit_name = $myrow['unit_name'];
                $standard_cost = $stock_item['standard_cost'];                   
            }
            
            label_cell($myrow["id"], "align=right");  
            
            if((isset($myrow['item_type']) && $myrow['item_type']) == 0){
                label_cell("Stock Item");
            }else{
                label_cell("Material Group");
            }
             
            label_cell($code, "align=right");
            label_cell($description);           
            label_cell($unit_name, "align=center");
            label_cell(number_format($standard_cost, 2), "align=right");
            label_cell(number_format($myrow["tran_unit_cost"], 2), "align=right");
                        
            label_cell($myrow["tran_qty"], "align=right");          

            $total_cost = $myrow["tran_unit_cost"] * $myrow["tran_qty"];

            label_cell(number_format($total_cost, 2), "align=right");
            label_cell($myrow["comment"]);

            edit_button_cell("Edit".$myrow['id'], _("Edit"));            
            delete_button_cell("Delete_BOQ_Item_Material".$myrow['id'], _("Delete"));
            end_row();          

            $j++;

            $full_total += $total_cost ;                
	} 
        
        start_row();
            label_cell("Total :", "colspan=8 align=right");
            amount_decimal_cell($full_total);
        end_row();
                                                 
    end_table();

}

//--------------------------------------------------------------------------------------------------

 
function can_commit_material($selected_id, $boq_item_id, $detail_type_code, $primary_type)
{
    global $project_boq_item_component_primary_types;
    
    $est_boq_item = get_est_project_boq_item_record($boq_item_id);
    $project = get_est_project_record($est_boq_item['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(!(strlen($_POST['boq_material_stock_id']) > 0))
    {
        display_error( _("Item can not be empty."));
        set_focus('boq_material_stock_id');
        return false;
    }  
    
    $component = get_boq_item_component_record($boq_item_id, $detail_type_code);
    if(isset($component['id']) && $component['id'] > 0){
        if($component['primary_type'] != $primary_type){
            display_error("There are already created ".$project_boq_item_component_primary_types[$component['primary_type']]." entries for this BOQ component. 
                            Please delete those before creating entries for new primary type.");
            set_focus('primary_type');
            return false;
        }
    }
    
    return true;
}
          

function display_est_boq_material_edit_controls($boq_item_id, $detail_type_code, $selected_id, &$Mode)
{ 
    global $Ajax;    

    start_table(TABLESTYLE);    
    
    br(2);    

    if($selected_id > 0){
        
        $myrow = get_est_boq_item_material_record_by_id($selected_id);

        $_POST['boq_material_id'] = $myrow["id"];     
        $_POST['boq_material_item_type'] = $myrow["item_type"];
        $_POST['boq_material_stock_id'] = $myrow["stock_id"];
        
        if($myrow["item_type"] > 0){
            $material_group = get_material_group_record($myrow["stock_id"]);
            $_POST['boq_material_material_group_code'] = $material_group["code"];
            $_POST['boq_material_stock_item_description'] = $material_group["description"];
        }
        else{
            $stock_item = get_stock_item_edit_info($myrow["stock_id"]);
            $_POST['boq_material_stock_item_description'] = $stock_item["description"];  
        }
        $_POST['boq_material_unit_cost'] = $myrow["tran_unit_cost"];        
        $_POST['boq_material_tran_qty']  = $myrow["tran_qty"];
        $_POST['boq_material_tran_unit'] = $myrow["tran_unit"];     
        $_POST['boq_material_comment']  = $myrow["comment"];

    }
    else{
        
    }
   
    
    hidden('selected_id', $selected_id);
    
    if($selected_id > 0){// Update
        
        if($_POST['boq_material_item_type'] > 0){
            $item_type_name = "Material Group";
        }else{
            $item_type_name = "Stock Item";
        }
        
        label_row("Item Type :", $item_type_name);
        hidden('boq_material_item_type', $_POST['boq_material_item_type']);
        
        if($_POST['boq_material_item_type'] == 0){ // stock item
            label_row("Itemcode :", $_POST['boq_material_stock_id']." - ".$_POST['boq_material_stock_item_description']);            
            units_list_row("Unit :", 'boq_material_tran_unit', $_POST['boq_material_stock_id'], null, false, false); 
        }
        else{
            label_row("Itemcode :", $_POST['boq_material_material_group_code']." - ".$_POST['boq_material_stock_item_description']);
            $mg_details = get_material_group_item($_POST['boq_material_stock_id']);        
               
            label_row("Unit:", $mg_details['material_group_unit_name']);
            hidden('boq_material_tran_unit', $mg_details['unit']);
        }
        
        hidden('boq_material_stock_id', $_POST['boq_material_stock_id']);
        
    }
    else{// New
        yesno_list_row("Type:", 'boq_material_item_type', null, $name_yes="Material Group", $name_no="Stock Item", true);
        
        if($_POST['boq_material_item_type'] == 0){ // stock item
            //Stock item search
            sales_local_items_list_row(_("Itemcode:"),'boq_material_stock_id', null, false, true);
            units_list_row("Unit :", 'boq_material_tran_unit', $_POST['boq_material_stock_id'], null, false, false); 
        }
        else{ // material group
            //materialgroup list
             
            material_groups_list_row("Material Groups:", 'boq_material_stock_id', null, '', true);
            $mg_details = get_material_group_item($_POST['boq_material_stock_id']);        
               
            label_row("Unit:", $mg_details['material_group_unit_name']);
            hidden('boq_material_tran_unit', $mg_details['unit']);
        }

    }
    
//    if (list_updated('boq_material_stock_id')) 
//    {
//        $Ajax->activate('boq_material_tran_qty');
//        $Ajax->activate('boq_material_tran_unit');
//    }    
        
     

    if($_POST['boq_material_item_type'] == 0){
        $stock_item = get_stock_item_edit_info($_POST['boq_material_stock_id']);
        $standard_cost = $stock_item['standard_cost'];
        
    }else{
        $material_group = get_material_group_item($_POST['boq_material_stock_id']);
        $standard_cost = $material_group['cost'];
    }
  
    
//    if($selected_id > 0 ){
//        $display_cost = $_POST['boq_material_unit_cost']; 
//    }
//    else{
//        $display_cost = $item['standard_cost']; 
//    }
    
    
    label_row("Current Cost:", number_format($standard_cost, 2));
    amount_row("Unit Cost :", 'boq_material_unit_cost' /*number_format($display_cost,2)*/);	
    amount_row(_("Quantity :"), 'boq_material_tran_qty', null, null, null);
    textarea_row("Comment :", 'boq_material_comment', null, 35, 2);

    end_table(1);
       
        
        
    if($selected_id > 0){        
        submit_center_first('UPDATE_BOQ_ITEM_MATERIAL', _("Update Material"), '', 'default');
        submit_center_last('Cancel_Edit', _("Cancel"), '', 'default');
    }
    else{
        submit_center_first('ADD_BOQ_ITEM_MATERIAL', _("Add Material"), '', 'default');
    }
    
 } 
 
function clear_boq_item_material_data()
{
    unset($_POST['boq_material_stock_id']);
    unset($_POST['boq_material_tran_qty']);
    unset($_POST['boq_material_unit_cost']);
}
 
 //---------------------------------------------------------------------------------------------------
 
if(isset($_POST['ADD_BOQ_ITEM_MATERIAL']) && $selected_id < 0)
{
    if(can_commit($selected_id, get_post('boq_item_id'), get_post('detail_type_code'), get_post('primary_type'))){
        
        begin_transaction();
        
        
        $aboqm = add_est_boq_item_material(get_post('boq_item_id'), get_post('detail_type_code'), get_post('boq_material_stock_id'),  
                        get_post('boq_material_tran_unit'), input_num('boq_material_unit_cost'), input_num('boq_material_tran_qty'),
                        get_post('boq_material_comment'), get_post('boq_material_item_type')); 
        
        if($aboqm['success'] === true){
            commit_transaction();
            $Mode = 'RESET';
            $selected_id = -1;
            
            display_notification("A new Estimation BOQ Item Material has been added");
        }
        else{
            cancel_transaction();
        }        
    }
}

if(isset($_POST['UPDATE_BOQ_ITEM_MATERIAL']) && $selected_id > 0)
{
    if(can_commit($selected_id, get_post('boq_item_id'), get_post('detail_type_code'), get_post('primary_type'))){ 
        
        begin_transaction();
        
        $uboqm = update_est_boq_item_material($selected_id, get_post('boq_item_id'), get_post('detail_type_code'), 
                        get_post('boq_material_tran_unit'), input_num('boq_material_unit_cost'), input_num('boq_material_tran_qty'), 
                        get_post('boq_material_comment'), get_post('boq_material_item_type')); 
        
        if($uboqm['success'] === true){
            commit_transaction();
            clear_boq_item_material_data();
            $Mode = 'RESET';
            $selected_id = -1;
            
            display_notification("Selected Estimation BOQ Item Material has been updated");
        }
        else{
            cancel_transaction();
        } 
    }   
}
 

//--------------------------------------------------------------------------------------------------
$delete_boq_material_id  = find_submit("Delete_BOQ_Item_Material");
if ($delete_boq_material_id > 0)
{
    begin_transaction();
    
    $sbp_msg = delete_est_boq_item_material($delete_boq_material_id, get_post('boq_item_id'), get_post('detail_type_code'));
    if($sbp_msg['success'] === true){
        commit_transaction();
        $Mode = 'RESET';
        $selected_id = -1;

        display_notification(_('Selected Estimation BOQ Item Material has been deleted'));
    }
    else{
        cancel_transaction();
    }
	
}
//------------------------------------------------------------------------------------------

if(isset($_POST['Cancel_Edit']))
{
    clear_boq_item_material_data();
    $Mode = 'RESET';
    $selected_id = -1;
}


if ($Mode == 'RESET')
{
    $selected_id = -1;
//    $sav = get_post('show_inactive');
//    unset($_POST);
//    $_POST['show_inactive'] = $sav;
}
//-------------------------------------------------------------------------------------------

if (isset($_POST['_selected_id_update']) )
{
    $selected_id = $_POST['selected_id'];
    $Ajax->activate('_page_body');
}


function display_est_project_boq_material_page(&$selected_id, &$Mode, $boq_item_id, $detail_type_code)
{
    global $Ajax;

    start_form();

//    $Ajax->Activate('boq_material_details');
//    $Ajax->Activate('boq_material_edit_controls');
    
    div_start('boq_material_details');    
    display_est_boq_item_material($boq_item_id, $detail_type_code);
    div_end();
    

    div_start('boq_material_edit_controls');
    display_est_boq_material_edit_controls($boq_item_id, $detail_type_code, $selected_id, $Mode);
    div_end(); 
    end_form();

    
}



?>















