<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_LOCATIONTRANSFER';
$path_to_root = "..";
include_once($path_to_root . "/includes/ui/items_cart.inc");

include_once($path_to_root . "/includes/session.inc");

include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/inventory/includes/stock_transfers_ui.inc");
include_once($path_to_root . "/inventory/includes/inventory_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/inventory/includes/db/alternate_units_db.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");
include_once($path_to_root . "/inventory/includes/lots_validation.inc");
include_once($path_to_root . "/inventory/includes/serial_no_validation.inc");
include_once($path_to_root . "/inventory/includes/db/serial_no_adjustments_db.inc");
include_once($path_to_root . "/inventory/includes/db/serial_no_db.inc");
include_once($path_to_root . "/projects/includes/db/project_sites_db.inc");
include_once($path_to_root . "/assets/includes/db/assets_db.inc");

$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(800, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();
page(_($help_context = "Inventory Location Transfers"), false, false, "", $js);

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

check_db_has_costable_items(_("There are no inventory items defined in the system (Purchased or manufactured items)."));

check_db_has_movement_types(_("There are no inventory movement types defined in the system. Please define at least one inventory adjustment type."));

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

if (isset($_GET['AddedID'])) 
{
	$trans_no = $_GET['AddedID'];
	$trans_type = ST_LOCTRANSFER;

	display_notification_centered(_("Inventory transfer ".$trans_no." has been created"));
        
	display_note(get_trans_view_str($trans_type, $trans_no, _("&View This Inventory Transfer")), 0, 1);
        
	display_note(print_document_link($trans_no, _("&Print This Inventory Transfer"), true, $trans_type), 0, 0);

	hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &Another Inventory Transfer"));

	display_footer_exit();
}
//--------------------------------------------------------------------------------------------------

function line_start_focus() {
  global 	$Ajax;

  $Ajax->activate('items_table');
  set_focus('_stock_id_edit');
}
//-----------------------------------------------------------------------------------------------

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

	$_SESSION['transfer_items'] = new items_cart(ST_LOCTRANSFER);
	$_POST['AdjDate'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['AdjDate']))
		$_POST['AdjDate'] = end_fiscalyear();
	$_SESSION['transfer_items']->tran_date = $_POST['AdjDate'];	
}

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

function can_process_transfer()
{
    global $Refs;

    $tr = &$_SESSION['transfer_items'];

    if (! (strlen($_POST['FromStockLocation']) > 0)) {
        display_error( _('Select a from location.'));
        set_focus('FromStockLocation');
        return false;
    }
    
    if (! (strlen($_POST['ToStockLocation']) > 0)) {
        display_error( _('Select a to location.'));
        set_focus('ToStockLocation');
        return false;
    }

    if (!$Refs->is_valid($_POST['ref'])) 
    {
            display_error(_("You must enter a reference."));
            set_focus('ref');
            return false;
    } 

    $ref_msg = reference_exists($_POST['ref'], ST_LOCTRANSFER);
    if($ref_msg)        
    {
        display_error( $ref_msg);
        set_focus('ref');
        return false;
    }
    
    if (!$_POST['project_id'] > 0) 
    {
        display_error( _('Select a project.'));
        set_focus('project_id');
        return false;
    }
    
            
    if (! ($_POST['movement_type'] > 0)) {
            $input_error = 1;
            display_error( _('Select a movement type.'));
            set_focus('movement_type');
            return false;
        } else {
            $mv_tp = get_movement_type($_POST['movement_type']);
                if ($mv_tp['linked_field'] != IMLF_NOT_LINKED) {
                    
                    global $inventory_movement_type_linked_fields;
                    
                    switch ($mv_tp['linked_field']) {
                        case IMLF_EMPLOYEE:
                            if((strlen($_POST['linked_field_id']) <= 2)) {
                                $input_error = 1;
                                display_error( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                        case IMLF_ASSET:
                            if (! ($_POST['linked_field_id'] > 0)) {
                                $input_error = 1;
                                display_error( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                        default :
                            if (! ($_POST['linked_field_id'] > 0)) {
                                $input_error = 1;
                                display_error( _('Select a '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                    }
                    
                    if ($mv_tp['linked_field'] == IMLF_ASSET) {
                        $asset_row = get_asset($_POST['linked_field_id']);
                            if ($asset_row['type'] == AT_VEHICLE) {
                                $message = 'Selected asset is a Vehicle. Only the assets of types "Fixed Asset" and "Tool" are allowed under this Movement Type.';
                                display_error($message);
                                set_focus('linked_field_id');
                                return false;
                            }
                    }
                }
        }

	if (!is_date($_POST['AdjDate'])) 
	{
		display_error(_("The entered transfer date is invalid."));
		set_focus('AdjDate');
		return false;
	} 
	elseif (!is_date_in_fiscalyear($_POST['AdjDate'])) 
	{
		display_error(_("The entered date is not in fiscal year."));
		set_focus('AdjDate');
		return false;
	} 
	elseif ($_POST['FromStockLocation'] == $_POST['ToStockLocation'])
	{
		display_error(_("The locations to transfer from and to must be different."));
		set_focus('FromStockLocation');
		return false;
	}
    elseif ($_POST['project_id'] == -1) 
    {
        display_error( _('Select a project.'));
        set_focus('project_id');
        return false;
    }
	else 
	{
		$failed_item = $tr->check_qoh($_POST['FromStockLocation'], $_POST['AdjDate'], true);
		if ($failed_item >= 0) 
		{
			$line = $tr->line_items[$failed_item];
        	display_error(_("The quantity entered is greater than the available quantity for this item at the source location :") .
        		" " . $line->stock_id . " - " .  $line->item_description);
        	echo "<br>";
			$_POST['Edit'.$failed_item] = 1; // enter edit mode
			return false;
		}
	}
        
    if (count($tr->line_items) == 0){
        display_error(_("You must enter at least one non empty item line."));
        set_focus('stock_id');
        return false;
    }
    
    $vtqd_msg = validate_transaction_quantity_details($tr);
    if ($vtqd_msg['success'] !== true) 
    {
        display_error($vtqd_msg['message']);
        return false;
    }
        
	return true;
}

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

if (isset($_POST['Process']))
{
    if(!can_process_transfer()){
        return;
    }
    
	$ast_msg = add_stock_transfer($_SESSION['transfer_items']->line_items, $_POST['FromStockLocation'], $_POST['ToStockLocation'],
                                $_POST['AdjDate'], $_POST['movement_type'], get_post('linked_field_type'),
                                $_POST['linked_field_id'],$_POST['ref'], $_POST['memo_'],
                                $_POST['project_id'], $_SESSION['transfer_items']->sample_items);
    if($ast_msg["success"] !== true){
        display_error($ast_msg["message"]);
    }
    else{
        new_doc_date($_POST['AdjDate']);
        $_SESSION['transfer_items']->clear_items();
        unset($_SESSION['transfer_items']);

        meta_forward($_SERVER['PHP_SELF'], "AddedID=".$ast_msg["tran_no"]);
    }
} /*end of process credit note */

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

function check_item_data(&$order)
{
    
    if(isset($order->sample_items)){
        
        if(isset($_POST['sample_items']) && $order->sample_items != $_POST['sample_items']){
            if($_POST['sample_items'] == 1)
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 1)
                {
                    display_error(_("Selected item is not a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
            else
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 0)
                {
                    display_error(_("Selected item is a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
        }
        else{
            if($order->sample_items == 1)
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 1)
                {
                    display_error(_("Selected item is not a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
            else
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 0)
                {
                    display_error(_("Selected item is a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
        }
             
    }
    else{
        if($_POST['sample_items'] == 1)
        {
            $item = get_item($_POST['stock_id']);
            if($item['sample_item'] != 1)
            {
                display_error(_("Selected item is not a sample item."));
                set_focus('stock_id');
                return false;
            }    
        }
        else
        {
            $item = get_item($_POST['stock_id']);
            if($item['sample_item'] != 0)
            {
                display_error(_("Selected item is a sample item."));
                set_focus('stock_id');
                return false;
            }    
        }
    }
    
    if ($_POST['stock_id'] == '') {
        display_error(_("Please select an item."));
        set_focus('stock_id');
        return false;
    }

	if (!check_num('tran_qty',0.0001))
	{
		display_error(_("The quantity entered is negative or invalid."));
		set_focus('tran_qty');
		return false;
	}
   	return true;
}

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

function handle_update_item()
{
    if($_POST['UpdateItem'] != "" && check_item_data($_SESSION['transfer_items']))
    {
        $tr = &$_SESSION['transfer_items'];
		$id = $_POST['LineNo'];
    	if (!isset($_POST['std_cost'])){
    		$_POST['std_cost'] = $tr->line_items[$id]->standard_cost;
        }
        
    	$convertion_factor = $tr->line_items[$id]->convertion_factor;
    	$tr->update_cart_item($id, input_num('tran_qty')*$convertion_factor, 
			$_POST['std_cost'], null, null, null, null, null, input_num('tran_qty'));
        
        //GET LOT INFO FOR $_POST['stock_id']
        $lot_details = get_selected_lot_serial_info('guid', $tr->line_items[$id]); 
        
        $tr->line_items[$id]->lot_details = $lot_details;
        
        $project_site_id = 0;
        $project_site_description = '';
        if($_POST['project_site_id'] != -1){
            $project_site = get_project_site_details($_POST['project_site_id']);
            $project_site_id = $project_site['id'];
            $project_site_description = $project_site['description'];
        }
        $tr->line_items[$id]->project_site_id = $project_site_id;
        $tr->line_items[$id]->project_site_description = $project_site_description;
    }
	line_start_focus();
}

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

function handle_delete_item($id)
{
	$_SESSION['transfer_items']->remove_from_cart($id);
	line_start_focus();
}

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

function handle_new_item()
{
	if (!check_item_data($_SESSION['transfer_items']))
		return;
	if (!isset($_POST['std_cost']))
   		$_POST['std_cost'] = 0;
        
        $item_info = get_stock_item_edit_info($_POST['stock_id']);
        $alternate_unit = get_convertion_factor($_POST['tran_unit'], $_POST['stock_id']);
        $convertion_factor = $alternate_unit['convertion_factor'];
        
	add_to_order($_SESSION['transfer_items'], $_POST['stock_id'], input_num('qty'), $_POST['std_cost'], 
                $_POST['tran_unit'], input_num('tran_qty'), $convertion_factor);
    
    $adj = &$_SESSION['transfer_items'];
    
    $current_element = (count($adj->line_items)-1);
//    $adj->line_items[$current_element]->requested_qty = $_POST['qty'];
    $adj->line_items[$current_element]->high_value_item = $item_info["high_value_item"];
    $adj->line_items[$current_element]->sample_item = $item_info["sample_item"];
    $adj->line_items[$current_element]->reference_cost = $item_info["reference_cost"];
    $adj->line_items[$current_element]->stock_control_method = $item_info["stock_control_method"];
    
    set_line_ref($adj, $current_element);
    $lot_details = get_selected_lot_serial_info('guid', $adj->line_items[$current_element]); 
    
    if(isset($lot_details) && $lot_details != ""){
        $adj->line_items[$current_element]->lot_details = $lot_details;    
    }
    
    if(count($adj->line_items) > 0 && !isset($adj->sample_items)){
        $adj->sample_items = $_POST['sample_items'];
    }
    elseif(isset($_POST['sample_items']) && $adj->sample_items != $_POST['sample_items']){
        $adj->sample_items = $_POST['sample_items'];
    }    

    $project_site_id = 0;
    $project_site_description = '';
    if($_POST['project_site_id'] != -1){
        $project_site = get_project_site_details($_POST['project_site_id']);
        $project_site_id = $project_site['id'];
        $project_site_description = $project_site['description'];
    }
    $adj->line_items[$current_element]->project_site_id = $project_site_id;
    $adj->line_items[$current_element]->project_site_description = $project_site_description;
        
    
	line_start_focus();
}

//-----------------------------------------------------------------------------------------------
$id = find_submit('Delete');
if ($id != -1)
	handle_delete_item($id);
	
if (isset($_POST['AddItem']))
	handle_new_item();

if (isset($_POST['UpdateItem']))
	handle_update_item();

if (isset($_POST['CancelItemChanges'])) {
	line_start_focus();
}
//-----------------------------------------------------------------------------------------------

if (isset($_GET['NewTransfer']) || !isset($_SESSION['transfer_items']))
{
	handle_new_order();
}

//-----------------------------------------------------------------------------------------------
start_form();
hidden("guid",substr(md5(microtime()),rand(0,26),15));
display_order_header($_SESSION['transfer_items']);

start_table(TABLESTYLE, "width=70%", 10);
start_row();
echo "<td>";
display_transfer_items(_("Items"), $_SESSION['transfer_items']);
transfer_options_controls();
echo "</td>";
end_row();
end_table(1);

submit_center_first('Update', _("Update"), '', null);
submit_center_last('Process', _("Process Transfer"), '',  'default');

end_form(3);
end_page();

?>
