<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_ASSET_ENTRY';
$path_to_root = "..";
//include($path_to_root . "/includes/session.inc");

//page(_($help_context = "Email Template"));

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 . "/asset_register/includes/db/asset_material_db.inc");


simple_page_mode(false);
//----------------------------------------------------------------------------------

if (isset($_GET['asset_id']) && $_GET['asset_id'] > 0) 
{
    $asset_id = $_GET['asset_id'];
}


function display_asset_process_name($bom_process)
{
    start_row();
    $name = $bom_process["sequence"]." - ".$bom_process["workcentre_name"]." - ".$bom_process["description"];
    label_cell("<b>".$name."</b>", "colspan=7 align=center");
    end_row();
}


function display_asset_material($asset_id)
{
    $result = get_asset_material($asset_id);
    
    start_table(TABLESTYLE, "width=60%");

    $th = array(_("Component"),_("Location"),_("Unit"),
                _("Quantity"));
    
    table_header($th);   
	
	$k = 0;
	while ($myrow = db_fetch($result))
	{
	    alt_table_row_color($k);

	    label_cell($myrow["stock_id"] ,"align=right");
	    label_cell($myrow["loc_code"] ,"align=center");
            label_cell($myrow["tran_unit"] ,"align=center");
            label_cell($myrow["tran_qty"] ,"align=right");            
        
 	    //edit_button_cell("Edit"."Material_".$myrow['asset_id'], _("Edit"));
 	   // delete_button_cell("Delete"."Material_".$myrow['asset_id'], _("Delete"));
        end_row();

	} //END WHILE LIST LOOP
 
        end_table(1);
}

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

function handle_new_order($order_name)
{
	if (isset($_SESSION[$order_name]))
	{
		$_SESSION[$order_name]->clear_items();
		unset ($_SESSION[$order_name]);
	}

    $_SESSION[$order_name] = new items_cart(ST_ISSUE_TO_ASSETS);

}

function display_asset_material_edit_controls($asset_id, &$Mode, $selected_id)
{
    global $Ajax, $Refs;
    
    div_start('bom_material_controls');
    start_table(TABLESTYLE2);
    
    if ($selected_id != -1)
	{
 		if ($Mode == 'Edit') {
			//editing a selected component from the link to the line item
            $asset_id = substr($selected_id,9);
			$a_result = get_asset_material_for_editing($asset_id);                          
                        
                        while($a_myrow = db_fetch($a_result)) 
                        {
                            $_POST['asset_material_component'] = $a_myrow["stock_id"];
                            $_POST['asset_material_loc_code'] = $a_myrow["loc_code"];  // by Tom Moulton	
                            $_POST['asset_material_tran_unit'] = $a_myrow["tran_unit"];
                            $_POST['asset_material_tran_qty'] = $a_myrow["tran_qty"];                           
                        
                        }
                        
		}
                
		hidden('selected_id', $selected_id);
                
	}
	
    br(2);
    
    //bom_processes_list_row('Process', 'bom_material_process_id', $parent);

    
    ref_row(_("Reference:"), 'ref', '', $Refs->get_next(ST_ISSUE_TO_ASSETS));
    project_list_row(_("Project:"), 'project_id', null ,false, true);
    tasks_list_row("Task:", 'task_id', $_POST['project_id']);
    date_row(_("Date:"), 'AdjDate', '', true);
    asset_locations_list_row(_("Location:"), 'asset_material_loc_code', null);
    yesno_list_row("Return", 'is_return', null, "Yes", "No");   
    
    if(isset($_POST['movement_type'])){
        $movement_type = $_POST['movement_type'];
    }
    else{
        $movement_type = '';
    }
    
    movement_types_list_row(_("Movement Type:"), 'movement_type', ST_ISSUE_TO_ASSETS, $movement_type , '', true);
    $movement_type = get_movement_type($_POST['movement_type']);
    switch ($movement_type['linked_field']) {
        case IMLF_CUSTOMER:
            customer_list_row(_("Customer:"), 'linked_field_id', null);
            break;
        case IMLF_SUPPLIER:
            supplier_list_row(_("Supplier:"), 'linked_field_id', null);
            break;
        case IMLF_EMPLOYEE:
            employees_simple_list_row("Employee", 'linked_field_id', null);
            break;
        default:
            hidden('linked_field_id', 0);
            break;
    }

    hidden('linked_field_type', $movement_type['linked_field']);
    
    start_row();
    label_cell(_("Component:"), "class='label'");
    
    echo "<td>";
    if(isset($_POST['asset_material_component'])){
        //echo stock_component_items_list('bom_material_component', $parent, $_POST['bom_material_component'], false, true);
        echo stock_items_list('asset_material_component', null, false, true);
    }
    else{
        //echo stock_component_items_list('bom_material_component', $parent, null, false, true);
        echo stock_items_list('asset_material_component', null, false, true);
    }
    
    if (list_updated('asset_material_component')) 
    {
        $Ajax->activate('asset_material_tran_qty');
        $Ajax->activate('asset_material_tran_unit');
    }
    echo "</td>";
    end_row();
	
	hidden('stock_id', $asset_id);        

    
    
    
    if(isset($_POST['asset_material_component'])){
        units_list_row("Unit", 'asset_material_tran_unit', $_POST['asset_material_component']);
    }
    else{
        units_list_row("Unit", 'asset_material_tran_unit', '');
    }
	//workcenter_list_row(_("Work Centre Added:"), 'workcentre_added', null);
	$dec = get_qty_dec(get_post('asset_material_component'));
	$_POST['asset_material_tran_qty'] = number_format2(input_num('asset_material_tran_qty',1), $dec);
	qty_row(_("Quantity:"), 'asset_material_tran_qty', null, null, null, $dec);    
    
	end_table(1);
	div_end();
    
    submit_add_or_update_center($selected_id == -1, '', 'both');
    
//    if (strlen($selected_id) > 5) {
//        submit_center_first('Update_BOM_Item', _("Update"), '', 'default');
//        submit_center_last('Delete_BOM_Item', _("Delete"), _("Cancel Edition"), 'cancel');
//    }
//    else
//    {
//        submit_center_first('Add_BOM_Item', _("Save"), '', 'default');
//    }

    
    
    }

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

function can_commit_asset_material($alt_unit_info, $bom_process)
{
    if($_POST['asset_material_tran_unit'] == ''){
        display_error("Please select units");
        set_focus('asset_material_tran_unit');
        return false;
    }
    
    if(input_num('asset_material_tran_qty') < 0.01){
        display_error("Quantity entered should be possitive.");
        set_focus('asset_material_tran_qty');
        return false;
    }
    
    if(!$alt_unit_info){
        display_error("Alternative unit conversion factor is not defined for the selected unit.");
        set_focus('asset_material_tran_unit');
        return false;
    }
    
    if(!$bom_process){
        display_error("No details found for the selected BOM Process.");
        set_focus('asset_material_process_id');
        return false;
    }
    return true;
}

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

function save_asset_material($selected_id, $new = true){
    
    //$alt_unit_info = get_alternate_unit_info($_POST['bom_parent'], $_POST['bom_material_tran_unit']);
    
    handle_new_order("issue_to_assets");
    $adj = $_SESSION["issue_to_assets"];
    $increase = 1;
    
    add_stock_adjustment($adj->line_items,
		$_POST['asset_material_loc_code'], $_POST['AdjDate'], $increase,
		$_POST['ref'], $_POST['comment'], $_POST['movement_type'], $_POST['project_id'], $_POST['task_id'], false, 
        ST_INVENTORY_ISSUE, $_POST['linked_field_type'], $_POST['linked_field_id']);
    
    
    	$_POST['AdjDate'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['AdjDate'])){
		$_POST['AdjDate'] = end_fiscalyear();
    }
	$adj->tran_date = $_POST['AdjDate'];	
    
    $alt_unit_info = get_alternate_unit_info($_POST['asset_material_component'], $_POST['asset_material_tran_unit']);
    $bom_process = get_bom_process($_POST['asset_material_tran_qty']);
    
    $qty = $_POST['asset_material_tran_qty'];
    if(!$_POST['is_return']){
       $qty *= -1; 
    }
    if(can_commit_asset_material($alt_unit_info, $bom_process)){        
        if($new){
            add_asset_material($_POST['asset_id'], $_POST['asset_material_component'], $_POST['asset_material_loc_code'], 
                               $_POST['asset_material_tran_unit'], $qty );
        }
       /* else{
            $asset_id = substr($selected_id,9);
            if($asset_id > 0){
                update_asset_material($asset_id, //get_post(''), 
                                      $_POST['asset_material_component'], $_POST['asset_material_loc_code'], 
                                      $_POST['asset_material_tran_unit'], $_POST['asset_material_tran_qty'] );
                               
            }
        }*/
        
        return array("success" => true); 
    }
    
    return array("success" => false); 
}

//--------------------------------------------------------------------------------------------------
if ($Mode=='ADD_ITEM') 
{
    $sbp_msg = save_asset_material(-1);   
    if($sbp_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
}

/*if ($Mode=='UPDATE_ITEM') 
{
    $sbp_msg = save_asset_material($selected_id, false);  
    if($sbp_msg['success'] === true){
        $Mode = '';
        $selected_id = -1;
    }
}*/
//--------------------------------------------------------------------------------------------------

//if(isset($_POST['Add_BOM_Process'])){
//    $sbp_msg = save_bom_process();   
//    if($sbp_msg['success'] === true){
//        $Mode = '';
//        $selected_id = -1;
//    }
//    
//}
//
//if(isset($_POST['Update_BOM_Process'])){
//    $sbp_msg = save_bom_process(false);  
//    if($sbp_msg['success'] === true){
//        $Mode = '';
//        $selected_id = -1;
//    }
//}

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

if ($Mode == 'Delete')
{
        $asset_id = substr($selected_id,9);
        delete_asset_material($asset_id);
        display_notification(_('Selected item has been deleted'));
	$Mode = 'RESET';
}

if ($Mode == 'RESET')
{
	$selected_id = '';
	$sav = get_post('show_inactive');
	unset($_POST);
	$_POST['show_inactive'] = $sav;
}

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

global $Ajax;

start_form();

display_asset_material($asset_id);

$Ajax->Activate('asset_material_controls');

if(substr($selected_id,0,8) == "Material"){
    display_asset_material_edit_controls($asset_id, $Mode, $selected_id);
}
else{
    display_asset_material_edit_controls($asset_id, $Mode, -1);
}
    

end_form();

//end_page();

?>
