<?php
/**********************************************************************
***********************************************************************/
//$page_security = 'SA_INVENTORY_RECEIPT';
$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/inventory_adjustments_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 . "/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");

if(!isset($_POST['Increase'])){
    if (isset($_GET['Positive']) && $_GET['Positive'] == 1){
        $page_security = 'SA_INVENTORY_RECEIPT';
        $_POST['Increase'] = 1;
        $_SESSION['movement_type'] = ST_INVENTORY_RECEIPT;
        $mv_type = ST_INVENTORY_RECEIPT;
    }
    else{
        $page_security = 'SA_INVENTORY_ISSUE';
        $_POST['Increase'] = 0;
        $_SESSION['movement_type'] = ST_INVENTORY_ISSUE;
        $mv_type = ST_INVENTORY_ISSUE;
    }
}
else{
    if ($_POST['Increase'] == 1){
        $page_security = 'SA_INVENTORY_RECEIPT';
        $_SESSION['movement_type'] = ST_INVENTORY_RECEIPT;
        $mv_type = ST_INVENTORY_RECEIPT;
    }
    else{
        $page_security = 'SA_INVENTORY_ISSUE';
        $_SESSION['movement_type'] = ST_INVENTORY_ISSUE;
        $mv_type = ST_INVENTORY_ISSUE;
    }
}

$order_name = 'inv_adjust_'.$mv_type;

$js = "";
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(800, 500);
if (user_use_date_picker())
	$js .= get_js_date_picker();

if($_SESSION['movement_type'] == ST_INVENTORY_RECEIPT){
    page(_($help_context = "Inventory Receipts"), false, false, "", $js);
}
elseif($_SESSION['movement_type'] == ST_INVENTORY_ISSUE){
    page(_($help_context = "Inventory Issues"), false, false, "", $js);
}

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

check_db_has_costable_items(_("There are no inventory items defined in the system which can be adjusted (Purchased or Manufactured)."));

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 = $_SESSION['movement_type'];

    if($trans_type == ST_INVENTORY_RECEIPT){
        $type_name = "Inventory Receipt";
        $positive = 1;
    }
    elseif($trans_type == ST_INVENTORY_ISSUE){
        $type_name = "Inventory Issue";
        $positive = 0;
    }
    
	display_notification_centered(_($type_name." ".$trans_no." has been created"));
        
	display_note(get_trans_view_str($trans_type, $trans_no, _("&View this $type_name")), 0, 1);

	display_note(get_gl_view_str($trans_type, $trans_no, _("View the GL &Postings for this $type_name")), 0, 1);

	display_note(print_document_link($trans_no, _("&Print This $type_name"), true, $trans_type), 0, 0);

    hyperlink_no_params($_SERVER['PHP_SELF']."?Positive=$positive", _("Enter &Another $type_name"));

	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");

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

function line_start_focus() {
  global 	$Ajax;

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

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($_SESSION['movement_type']);
	$_POST['AdjDate'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['AdjDate']))
		$_POST['AdjDate'] = end_fiscalyear();
	$_SESSION[$order_name]->tran_date = $_POST['AdjDate'];	
}

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

function can_process_adjustment($order_name)
{
	global $Refs;

	$adj = &$_SESSION[$order_name];

	if (count($adj->line_items) == 0)	{
		display_error(_("You must enter at least one non empty item line."));
		set_focus('stock_id');
		return false;
	}
    if ($_POST['project_id'] == -1) 
    {
            $input_error = 1;
            display_error( _('Select a project.'));
            set_focus('project_id');
            return;
    }

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

    $ref_msg = reference_exists($_POST['ref'], $_SESSION['movement_type']);
    if($ref_msg)        
    {
        display_error( $ref_msg);
        set_focus('ref');
        return false;
    }

    if (!$_POST['movement_type'] > 0) 
    {
            $input_error = 1;
            display_error( _('Select a movement type.'));
            set_focus('movement_type');
            return false;
    }
        
	if (!is_date($_POST['AdjDate'])) 
	{
		display_error(_("The entered date for the adjustment 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;
	} else {
		$failed_item = $adj->check_qoh($_POST['StockLocation'], $_POST['AdjDate'], !$_POST['Increase']);
		if ($failed_item >= 0) 
		{
			$line = $adj->line_items[$failed_item];
    		display_error(_("The adjustment cannot be processed because an adjustment item would cause a negative inventory balance :") .
    			" " . $line->stock_id . " - " .  $line->item_description);
			$_POST['Edit'.$failed_item] = 1; // enter edit mode
			unset($_POST['Process']);
		return false;
		}
	}

    
    $vtqd_msg = validate_transaction_quantity_details($adj);
    if ($vtqd_msg['success'] !== true) 
    {
        display_error($vtqd_msg['message']);
        return false;
    }
	return true;
}

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

if (isset($_POST['Process']) && can_process_adjustment($order_name)){

	$asa_msg = add_stock_adjustment($_SESSION[$order_name]->line_items,
		$_POST['StockLocation'], $_POST['AdjDate'], $_POST['Increase'],
		$_POST['ref'], $_POST['memo_'], $_POST['movement_type'], $_POST['project_id'], $_POST['task_id'], $_SESSION[$order_name]->sample_items, 
        $_SESSION[$order_name]->trans_type, $_POST['linked_field_type'], $_POST['linked_field_id']);
        
    if($asa_msg['success'] !== true){
        display_error($asa_msg['message']);  
    }
    else{
        $trans_no = $asa_msg['tran_no'];
        if($_SESSION[$order_name]->trans_type == ST_INVENTORY_RECEIPT){
            $positive = 1;
        }
        elseif($_SESSION[$order_name]->trans_type == ST_INVENTORY_ISSUE){
            $positive = 0;
        }
        new_doc_date($_POST['AdjDate']);
        $_SESSION[$order_name]->clear_items();
        unset($_SESSION[$order_name]);

        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no&Positive=$positive");
    }
} /*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 (!check_num('tran_qty',0.01))
	{
		display_error(_("The quantity entered is negative or invalid."));
		set_focus('tran_qty');
		return false;
	}

//	if (!check_num('std_cost', 0.01))
//	{
//		display_error(_("The entered standard cost must be positive."));
//		set_focus('std_cost');
//		return false;
//	}

    if ($_POST['task_id'] <= 0 )
	{
		display_error(_("Please select a budget."));
		set_focus('task_id');
		return false;
	}
   	return true;
}

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

function handle_update_item($order_name)
{
    //if($_POST['UpdateItem'] != "" && check_item_data($_SESSION[$order_name]))
    
    if(!check_item_data($_SESSION[$order_name])){
        $_POST['Edit'.get_post('LineNo')] = 1;
        return;
    }
 

    $inv_adj = &$_SESSION[$order_name];
    $id = $_POST['LineNo'];
    $convertion_factor = $inv_adj->line_items[$id]->convertion_factor;
    $inv_adj->update_cart_item($id, input_num('tran_qty')*$convertion_factor, 
        input_num('std_cost'), null, null, null, null, null, input_num('tran_qty'));

    $lot_details = get_selected_lot_serial_info('guid', $inv_adj->line_items[$id]); 

    $inv_adj->line_items[$id]->lot_details = $lot_details;

    $task_id = 0;
    $task_description = '';
    if($_POST['task_id'] != -1){
        $project_task = get_task_details($_POST['task_id']);
        $task_id = $project_task['task_id'];
        $task_description = $project_task['description'];
    }
    $inv_adj->line_items[$id]->task_id = $task_id;
    $inv_adj->line_items[$id]->task_description = $task_description;

    $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'];
    }
    $inv_adj->line_items[$id]->project_site_id = $project_site_id;
    $inv_adj->line_items[$id]->project_site_description = $project_site_description;
    
    
	line_start_focus();
}

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

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

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

function handle_new_item($order_name)
{
	if (!check_item_data($_SESSION[$order_name])){
		return;
    }
        
    $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[$order_name], $_POST['stock_id'], 
                        input_num('qty'), input_num('std_cost'), $_POST['tran_unit'], input_num('tran_qty'), $convertion_factor);
    
    $adj = &$_SESSION[$order_name];
        
    $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"];
    $adj->line_items[$current_element]->stock_control_method = $item_info["stock_control_method"];
    
    //$adj->line_items[$current_element]->line_ref = 
    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'];
    }
	
        $task_id = 0;
    $task_description = '';
    if($_POST['task_id'] != -1){
        $project_task = get_task_details($_POST['task_id']);
        $task_id = $project_task['task_id'];
        $task_description = $project_task['description'];
    }
    $adj->line_items[$current_element]->task_id = $task_id;
    $adj->line_items[$current_element]->task_description = $task_description;
    
    $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($order_name, $id);

if (isset($_POST['AddItem']))
	handle_new_item($order_name);

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

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

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

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

start_outer_table(TABLESTYLE, "width=80%", 10);

display_adjustment_items(_("Adjustment Items"), $_SESSION[$order_name]);
adjustment_options_controls();

end_outer_table(1, false);

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

end_form();
end_page();

?>
