<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_RAW_MATERIAL_ISSUE_OUT';
$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 . "/manufacturing/includes/material_issue_outs_ui.inc");
include_once($path_to_root . "/manufacturing/includes/db/material_issue_outs_db.inc");
include_once($path_to_root . "/manufacturing/includes/db/material_requisitions_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 = "Issue Out Raw Materials"), 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'])) 
{
	//return;
        
        $trans_no = $_GET['AddedID'];
	$trans_type = ST_MATERIAL_ISSUE;

	display_notification_centered(_("Material Requisition has been saved"));
	//display_note(get_trans_view_str($trans_type, $trans_no, _("&View this adjustment")));

	hyperlink_no_params("$path_to_root/manufacturing/inquiry/material_requisitions_view.php", _("Process &Another Material Requisition"));

	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()
{
	if (isset($_SESSION['mio_items']))
	{
		$_SESSION['mio_items']->clear_items();
		unset ($_SESSION['mio_items']);
	}

        $_SESSION['mio_items'] = new items_cart(ST_MATERIAL_ISSUE);
        
        populate_cart_from_database();
	
}

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

function populate_cart_from_database()
{
        $myrow = get_material_requisition($_GET['mr_no']);
        
        $mr_cart = $_SESSION['mio_items'];

        $mr_cart->order_id = $myrow["mr_no"];
        $mr_cart->reference = $myrow["reference"];
        $mr_cart->issuing_location  = $myrow["issuing_location"];
        $mr_cart->receiving_location  = $myrow["requesting_location"];
        $mr_cart->required_date  = $myrow["mr_required_date"];
        $mr_cart->memo_  = $myrow["comments"];
        $mr_cart->requestor_name  = $myrow["requestor_name"];
        $mr_cart->created_on  = $myrow["created_on"];
        $mr_cart->receiving_location  = $myrow["requesting_location"];
        $mr_cart->mr_complete  = $myrow["mr_complete"];
  
        $mr_details = get_mr_details($mr_cart->order_id);

        $element_no = 0;
        while ($mrd_row = db_fetch($mr_details)) 
        {
            $mr_line = new line_item($mrd_row["stock_id"], 0, $standard_cost=null, 
                    $mrd_row["description"],sql2date($mrd_row["required_date"]), $mrd_row["line_comment"],
                    $mrd_row["id"], $mrd_row["issued_qty"], $mrd_row["requested_qty"]);
            
            $mr_line->row_id = $mrd_row["id"];
            //$mr_line->mb_flag = $mrd_row["id"];
            //$mr_line->price = $mrd_row["id"];
            //$mr_line->standard_cost = $mrd_row["id"];
                                    
            $mr_cart->line_items[$element_no] = $mr_line;
            $element_no++;
        }

}

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

function can_process()
{
	global $Refs;

        $total_qty = 0;
        
	foreach ($_SESSION['mio_items']->line_items as $line_item)
        {
            if (!check_num($line_item->row_id.'_qty',0))
            {
                display_error(_("The quantity entered for item [".$line_item->stock_id."] is negative or invalid."));
                set_focus($line_item->row_id."_qty");
                return false;
            }
            $total_qty += $_POST[$line_item->row_id."_qty"];
        }
        
        if($total_qty == 0)
        {      
            if($_POST['mr_complete'] == "1")
            {
                return "close_only";
            }
            else
            {
                display_error(_("You must enter a possitive quantity for one item at least."));
                set_focus($line_item->row_id."_qty");
                return false;
            }
	}
        
        
	if (!$Refs->is_valid($_POST['mio_reference'])) 
	{
		display_error( _("You must enter a reference."));
		set_focus('mio_reference');
		return false;
	}

	if (!is_new_reference($_POST['mio_reference'], ST_MATERIAL_ISSUE)) 
	{
		display_error( _("The entered reference is already in use."));
		set_focus('mio_reference');
		return false;
	}

	if (!is_date_in_fiscalyear(date("Y/m/d"),true)) 
	{
		display_error(_("Today's date is not in fiscal year."));
		return false;
	} 
        
	return true;
}

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

function update_cart()
{
    foreach ($_SESSION['mio_items']->line_items as $line_item)
    {
        $line_item->quantity = $_POST[$line_item->row_id."_qty"];
    }
}

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

function end_processing($trans_no)
{
        //return;
 	$_SESSION['mio_items']->clear_items();
        //return;
	unset($_SESSION['mio_items']);         
        
   	meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
}

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


if (isset($_POST['Process']))
{
    $result = can_process();
    
    if($result === "close_only")
    {
        //return;
        close_mr($_SESSION['mio_items']->order_id);
        
        end_processing(0);
        
    }
    elseif($result == true)  
    {
	//return;
        
        update_cart();
    
        $trans_no = add_material_issue_out($_SESSION['mio_items']->line_items, $_POST['mio_reference'],
		$_SESSION['mio_items']->issuing_location, $_SESSION['mio_items']->receiving_location, 
                $_POST['memo_'], $_SESSION['mio_items']->order_id, $_POST['mr_complete']);
                
	//new_doc_date($_POST['mio_date']);
        end_processing($trans_no);
      
    }

} 

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

function check_item_data()
{
	if (!check_num('qty',0))
	{
		display_error(_("The quantity entered is negative or invalid."));
		set_focus('qty');
		return false;
	}
        
	if (input_num('qty') == 0)
	{
		display_error(_("The quantity entered has to be greater than zero."));
		set_focus('qty');
		return false;
	}
   	return true;
}

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

function handle_update_item()
{
    if($_POST['UpdateItem'] != "" && check_item_data())
    {
		$id = $_POST['LineNo'];
    	$_SESSION['mio_items']->update_cart_item($id, input_num('qty'), 
			input_num('std_cost'));
    }
	line_start_focus();
}

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

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

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

function handle_new_item()
{
	if (!check_item_data())
		return;

	add_mio_to_cart($_SESSION['mio_items'], $_POST['stock_id'],input_num('qty'), 
                                $_POST['required_date'], $_POST['line_commnet']);
	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['NewAdjustment']) || !isset($_SESSION['mio_items']))
//{
//	handle_new_order();
//}

if (isset($_GET['mr_no']) && $_GET['mr_no'] > 0) 
{
    if(!isset($_SESSION['mio_items']))
    {
        handle_new_order();
    }
    
    if($_GET['mr_no'] != $_SESSION['mio_items']->order_id)
    {
        handle_new_order();
    }
}
//-----------------------------------------------------------------------------------------------
start_form();

display_mio_header($_SESSION['mio_items']);

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

display_mio_items(_("Material Requisition Items"), $_SESSION['mio_items']);
mio_options_controls();

end_outer_table(1, false);

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

end_form();
end_page();

?>
