<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_ISSUE_ASSETS';
$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 . "/asset_register/includes/issue_assets_ui.inc");
include_once($path_to_root . "/asset_register/includes/db/issue_assets_db.inc");
include_once($path_to_root . "/projects/includes/db/issue_materials_db.inc");
//include_once($path_to_root . "/inventory/issue_materials.php");
include_once($path_to_root . "/asset_register/includes/db/asset_booking_request_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.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 Assets"), 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_REQTRANSFER;

	display_notification_centered(_("Material Requisition Transfer ".$trans_no." has been saved"));
        
	display_note(print_document_link($trans_no, _("&Print This Material Requisition Transfer"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/inventory/inquiry/material_transfer_requisitions_inquiry.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['ia_items']))
	{
		$_SESSION['ia_items']->clear_items();
		unset ($_SESSION['ia_items']);
	}

        $_SESSION['ia_items'] = new items_cart(ST_LOCTRANSFER);
        
        populate_cart_from_database();
	
}

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

function populate_cart_from_database()
{
    $is_issued = 0;
    
        $myrow = get_asset_booking($_GET['ab_no']);
        
        $ab_cart = $_SESSION['ia_items'];

        $ab_cart->order_id = $myrow["ab_no"];
        $ab_cart->reference = $myrow["reference"];
        if(isset($_POST['issuing_location'])){
            $ab_cart->issuing_location  = $_POST["issuing_location"];
        }
        else {
            $ab_cart->issuing_location  = $myrow["issuing_location"];
        }
        $ab_cart->required_date  = ($myrow["ab_date"]);
        $ab_cart->memo_  = $myrow["comments"];
        $ab_cart->requestor_name  = $myrow["requestor_name"];
        $ab_cart->created_on  = $myrow["created_on"];
//        $ab_cart->approval_path_id  = $myrow["approval_path_id"];
        $ab_cart->ab_complete  = $myrow["ab_complete"];
        $ab_cart->project_id  = $myrow["project_id"];
        $ab_cart->task_id  = $myrow["task_id"];
        $ab_cart->location_name = $myrow["location_name"];
        $ab_cart->project_description  = $myrow["project_description"];
        $ab_cart->task_description  = $myrow["task_description"];

        
            $ab_details = get_abd($ab_cart->order_id);
            $date = date('Y/m/d');
            $element_no = 0;
            while ($abd_row = db_fetch($ab_details)) 
            {
                $ab_line = new line_item($abd_row["asset_id"], 0, $standard_cost=null, 
                        null,null, $abd_row["line_comment"],
                        $comment=null, $abd_row["id"], null, null, null, null, null, null,
                        sql2date($abd_row["required_from_date"]), sql2date($abd_row["required_to_date"]),
                        $date, $abd_row['asset_id'], 0);

                $ab_line->row_id = $abd_row["id"];
                $ab_line->asset_id = $abd_row["asset_id"];
                $ab_line->created_by = $abd_row["created_by"];
                $ab_line->created_on = $abd_row["created_on"];
//                $ab_line->check = $abd_row["ckecked"];
                $ab_cart->line_items[$element_no] = $ab_line;
                $element_no++;
            }
//            $ab_cart->line_items = 0;

}

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

function can_process()
{

//        foreach ($_SESSION['ia_items']->line_items as $line_item)
//        {
//            if (!is_date($line_item->row_id.'_issuing_date'))
//            {
//                display_error(_("The entered date for the issuing date is invalid."));
//                set_focus($line_item->row_id."_issuing_date");
//                return false;
//            }
//        }
//        
//        if(!check_num($ia_reference, 0))
//        {
//            display_error(_("The reference entered is invalid."));
//            set_focus('ia_reference');
//            return false;
//        }

	return true;
}

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

function update_cart()
{
    foreach ($_SESSION['ia_items']->line_items as $line_item)
    {
        $line_item->issuing_date = $_POST[$line_item->row_id."_issuing_date"];
        if(!isset($_POST[$line_item->row_id."_check"]))
        {
            $line_item->check = "0";
        }
        else 
        {
           $line_item->check = $_POST[$line_item->row_id."_check"]; 
        }

    }
}

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

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

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


if (isset($_POST['Process']))
{
    $result = can_process();
    
    if($result === "close_only")
    {
        //return;
        close_mtr($_SESSION['mrt_items']->order_id);
        
        end_processing(0);
        
    }
    elseif($result == true)  
    {
	//return;
        
        update_cart();
    
        $trans_no = add_issue_assets($_SESSION['ia_items']->line_items, $_POST['iab_reference'],
		$_SESSION['ia_items']->issuing_location, $_SESSION['ia_items']->project_id,
                $_SESSION['ia_items']->task_id,
                $_POST['memo_'], $_SESSION['ia_items']->order_id, $_POST['iab_complete']);
                
	//new_doc_date($_POST['mio_date']);
        //end_processing($trans_no);
        
//        meta_forward($_SERVER['PHP_SELF'], "AddedID=$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['mrt_items']->update_cart_item($id, input_num('qty'), 
			input_num('std_cost'));
    }
	line_start_focus();
}

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

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

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

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

	add_mio_to_cart($_SESSION['mrt_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['ab_no']) && $_GET['ab_no'] > 0) 
{
    if(!isset($_SESSION['ia_items']))
    {
        handle_new_order();
    }
    
    if($_GET['ab_no'] != $_SESSION['ia_items']->order_id)
    {
        handle_new_order();
    }
}
//-----------------------------------------------------------------------------------------------
start_form();

display_ab_header($_SESSION['ia_items']);

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

display_ab_items(_("Asset Request Items"), $_SESSION['ia_items']);
ab_options_controls($_SESSION['ia_items']);

end_outer_table(1, false);

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

end_form();
end_page();

?>
