<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_MATERIAL_REQ_TRANSFER';
$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/material_requisition_transfers_ui.inc");
include_once($path_to_root . "/inventory/includes/db/material_requisition_transfers_db.inc");
include_once($path_to_root . "/inventory/includes/db/material_transfer_requisitions_db.inc");
include_once($path_to_root . "/inventory/includes/material_transfer_requisitions_ui.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/projects_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 = "Material Requisition Transfer"), 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(_("Material Requisition Transfer ".$trans_no." has been saved"));
        
        display_note(get_trans_view_str($trans_type, $trans_no, _("&View this Material Requisition Transfer #$trans_no")), 0, 1);
        
	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();
}

if (isset($_GET['ClosedID']))  {
    $trans_no = $_GET['ClosedID'];
	$trans_type = ST_TRANSFERREQ;
	display_notification_centered(_("Material Transfer Requisition #$trans_no has been closed."));
        
	display_note(print_document_link($trans_no, _("&Print This Material Transfer Requisition"), true, $trans_type), 0, 0);
	hyperlink_no_params("$path_to_root/inventory/inquiry/material_transfer_requisitions_inquiry.php", _("Process &Another Material Requisition Transfer"));
	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['mrt_items']))
	{
		$_SESSION['mrt_items']->clear_items();
		unset ($_SESSION['mrt_items']);
	}

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

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

function populate_cart_from_database()
{
        $myrow = get_material_transfer_requisition($_GET['mtr_no']);
        
        $mrt_cart = $_SESSION['mrt_items'];

        $mrt_cart->order_id = $myrow["mtr_no"];
        $mrt_cart->reference = $myrow["reference"];
        $mrt_cart->issuing_location  = $myrow["issuing_location"];
        $mrt_cart->issuing_location_name  = $myrow["issuing_location_name"];
        $mrt_cart->receiving_location  = $myrow["requesting_location"];
        $mrt_cart->receiving_location_name  = $myrow["requesting_location_name"];
        $mrt_cart->required_date  = $myrow["mtr_required_date"];
        $mrt_cart->memo_  = $myrow["comments"];
        $mrt_cart->movement_type_name = $myrow["movement_type_name"];
        $mrt_cart->linked_field_type = $myrow["linked_field_type"];
        $mrt_cart->linked_field_id  = $myrow["linked_field_id"];
        $mrt_cart->requestor_name  = $myrow["requestor_name"];
        $mrt_cart->created_on  = $myrow["created_on"];
        $mrt_cart->mtr_complete  = $myrow["mtr_complete"];
        $mrt_cart->project_id  = $myrow["project_id"];
        $mrt_cart->project_description  = $myrow["project_description"];
        $mrt_cart->approval_path_description  = $myrow["approval_path_description"];
        $mrt_cart->next_approval_group_id = $myrow["next_approval_group_id"];
        $mrt_cart->approval_status = $myrow["approval_status"];
        $mrt_cart->row_state = $myrow["row_state"];
        $mrt_cart->issuing_project_id = 0;
  
        $mrt_details = get_mtr_details($mrt_cart->order_id);

        $element_no = 0;
        while ($mrtd_row = db_fetch($mrt_details)) 
        {
            $mrt_line = new line_item($mrtd_row["stock_id"], 0, $standard_cost=null, 
                    $mrtd_row["description"], sql2date($mrtd_row["required_date"]), $mrtd_row["line_comment"],
                    null, $mrtd_row["id"], $mrtd_row["issued_qty"], $mrtd_row["requested_qty"], 0, 0, null, 0,
                    null, null, null, null, null,$mrtd_row["requested_unit"], $mrtd_row["requested_unit_qty"], 
                    $mrtd_row["req_unit_conv_factor"]);
                    
            
            $mrt_line->row_id = $mrtd_row["id"];
            $mrt_line->stock_control_method = $mrtd_row["stock_control_method"];
            $mrt_line->project_site_id = $mrtd_row["project_site_id"];
            $mrt_line->line_ref = $mrt_line->row_id;
        
            $_POST[$mrt_line->row_id."_tran_unit"] = $mrtd_row["requested_unit"];
            $mrt_line->requested_unit_quantity = $mrtd_row["requested_unit_qty"];
            
            $mrt_cart->line_items[$element_no] = $mrt_line;
            $element_no++;
        }


}

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

function can_process() {
    global $Refs, $approval_statuses;

    if(!($_SESSION['mrt_items']->approval_status == AS_APPROVED || $_SESSION['mrt_items']->approval_status == AS_TRANSFERRED))
    {
        $a = AS_APPROVED;
        $i = AS_TRANSFERRED;
        display_error("Material can be transferred when the status is $approval_statuses[$a] or $approval_statuses[$i] only.");
        return false;
    }   
    
    if (! is_date($_POST['tran_date'])) {
        display_error(_("Entered date is not valid."));
        set_focus('tran_date');
        return false;
    } 
        
    $total_qty = 0;
    
    	foreach ($_SESSION['mrt_items']->line_items as $line_item) {
            if (isset($_POST[$line_item->row_id."_check"]) && $_POST[$line_item->row_id."_check"] == 1) {
                if (! check_num($line_item->row_id.'_tran_qty', 0.0001))
                {
                    display_error(_("Line Id ".$line_item->row_id.": The quantity entered for item [".$line_item->stock_id."] is negative or invalid."));
                    set_focus($line_item->row_id."_tran_qty");
                    return false;
                }
                $total_qty += $_POST[$line_item->row_id."_tran_qty"];
            }
        }
        
        if ($total_qty == 0) { 
            display_error(_("Please check at least one item before saving."));
            return false;
        }
        
        foreach ($_SESSION['mrt_items']->line_items as $line_item) {
            if (isset($_POST[$line_item->row_id."_check"]) && $_POST[$line_item->row_id."_check"] == 1) {
                $stock_id = $line_item->stock_id;
                $alternate_unit = $_POST[$line_item->row_id."_tran_unit"];
                $convesion_factor = 1;
                get_convertion_factor2($stock_id, $alternate_unit, $convesion_factor);
                $requested_tran_unit_qty = $line_item->requested_qty / $convesion_factor;
                $issued_tran_unit_qty = $line_item->issued_qty / $convesion_factor;
                $this_issue_tran_unit_qty = input_num($line_item->row_id."_tran_qty");
                
                if($requested_tran_unit_qty < $issued_tran_unit_qty + $this_issue_tran_unit_qty) {
    //                display_error(_("Can not issue more than the requested quantity for item [".$line_item->stock_id."]."));
                    $allowed_maximum_tran_unit_qty = $requested_tran_unit_qty - $issued_tran_unit_qty;
                    $msg = "In record #".$line_item->row_id." Maximum allowed transderring quantity is ". number_format($allowed_maximum_tran_unit_qty,2);
                    display_error($msg);
                    set_focus($line_item->row_id."_qty");
                    return false;
                }
//                if (! ($_POST[$line_item->row_id."_issuing_task_id"] > 0)) {
//                    display_error(_("Line Id ".$line_item->row_id.": Budgect cannot be empty."));
//                    set_focus($line_item->row_id."_issuing_task_id");
//                    return false;
//                }
            }
        }
        
	if (!$Refs->is_valid($_POST['mrt_reference'])) 
	{
		display_error( _("You must enter a reference."));
		set_focus('mio_reference');
		return false;
	}

    $ref_msg = reference_exists($_POST['mrt_reference'], ST_REQTRANSFER);
    if($ref_msg)        
    {
        display_error( $ref_msg);
        set_focus('mrt_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;
//	} 
    $vtqd_msg = validate_transaction_quantity_details($_SESSION['mrt_items']);
    if ($vtqd_msg['success'] !== true) 
    {
        display_error($vtqd_msg['message']);
        return false;
    }   
	return true;
}

function add_lot_details()
{

    if(!isset($_SESSION['lot_info#'.ST_REQTRANSFER])){
        return;
    }
    
    $lot_info_array =  $_SESSION['lot_info#'.ST_REQTRANSFER];

    foreach ($_SESSION['mrt_items']->line_items as $line_item) {
       	if($line_item->stock_control_method != SKCM_NORMAL){
            $line_item->lot_details = $lot_info_array[$line_item->stock_id] ;
        } 
    }    
}
//-------------------------------------------------------------------------------

function update_cart()
{
    foreach ($_SESSION['mrt_items']->line_items as $line_item)
    {
        $line_item->tran_qty = $_POST[$line_item->row_id."_tran_qty"];
        $line_item->tran_unit = $_POST[$line_item->row_id."_tran_unit"];
        
        $alternate_unit = get_convertion_factor($_POST[$line_item->row_id."_tran_unit"], $line_item->stock_id);
        if($alternate_unit == false){
            $issue_convertion_factor = 1;
        }
        else{
            $issue_convertion_factor = $alternate_unit['convertion_factor'];
        }
        $line_item->convertion_factor = $issue_convertion_factor;
//        $line_item->quantity = $line_item->tran_qty * $line_item->convertion_factor;
        
        $item_info = get_stock_item_edit_info($line_item->stock_id);

//        if($item_info["stock_control_method"] == 1){
//          $a = "lot_info#".$_POST['guid'];  
//          $lot_details = get_session_variable($a)[$_POST['stock_id']];  
//        }
        
        //$adj = &$_SESSION['mrt_items'];
        //$current_element = (count($adj->line_items)-1);
        
        $lot_details = get_selected_lot_serial_info('guid', $line_item);         
        $line_item->lot_details = $lot_details; 
        
//        $adj->line_items[$current_element]->requested_qty = $_POST['qty'];
        $line_item->high_value_item = $item_info["high_value_item"];
        $line_item->sample_item = $item_info["sample_item"];
        $line_item->reference_cost = $item_info["reference_cost"];
        $line_item->stock_control_method = $item_info["stock_control_method"];

        
        if($_POST[$line_item->row_id."_project_site_id"] > 0){
            $line_item->project_site_id = $_POST[$line_item->row_id."_project_site_id"];
        }
        else{
             $line_item->project_site_id = 0;
        }
        
//        $line_item->task_id = $_POST[$line_item->row_id."_issuing_task_id"];
    }
}

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

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

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

function close_material_transfer_requisition($mtr_no) {
    global $approval_statuses;
    if (! ($_SESSION['mrt_items']->approval_status == AS_APPROVED || $_SESSION['mrt_items']->approval_status == AS_TRANSFERRED)) {
        $a = AS_APPROVED;
        $i = AS_TRANSFERRED;
        display_error("Material can be closed when the status is $approval_statuses[$a] or $approval_statuses[$i] only.");
        return false;
    }
    
        begin_transaction();
            $cmr_msg = close_mtr($mtr_no, AS_CLOSED);
                if ($cmr_msg['success'] !== true) {
                    cancel_transaction();
                    display_error($cmr_msg['message']);
                } else {
                    commit_transaction();
                    unset($_SESSION['mrt_items']);
                    meta_forward($_SERVER['PHP_SELF'], "ClosedID=$mtr_no");
                }
}

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

if (isset($_POST['Process'])) {
    create_material_requisition_transfer(false);
} elseif (isset($_POST['Create_MRT_Close_MTR'])) {
    create_material_requisition_transfer(true);
} elseif (isset($_POST['Close_MTR'])) {
    close_material_transfer_requisition($_SESSION['mrt_items']->order_id);
}

function create_material_requisition_transfer($close_mtr=false) {
    update_cart();
    
    $source_mtr_no = $_SESSION['mrt_items']->order_id;
    
    if (! can_process()) {
        return;
    }
    
        $amrt_msg = add_material_requisition_transfer($_SESSION['mrt_items']->line_items, $_POST['mrt_reference'], 
                                                      $_SESSION['mrt_items']->issuing_location, $_SESSION['mrt_items']->receiving_location, 
                                                      0 , $_POST['memo_'], $_SESSION['mrt_items']->order_id, 
                                                      $_SESSION['mrt_items']->row_state, $_POST['tran_date']);
        
            if ($amrt_msg['success'] !== true) {
                display_error($amrt_msg['message']);
                return;
            }
        
            $can_close_mtr =  false;
            $closing_status = AS_TRANSFERRED;
            if (check_all_mtr_lines_issued($source_mtr_no) === true) {
                $can_close_mtr = true;
                $closing_status = AS_COMPLETED;
            } else {
                if ($close_mtr) {
                    $can_close_mtr = true;
                    $closing_status = AS_CLOSED;
                }        
            }    
            if ($can_close_mtr) {
                $cmr_msg = close_mtr($source_mtr_no, $closing_status);
                    if ($cmr_msg['success'] !== true) {
                        display_error($cmr_msg['message']);
                        return;
                    }
            }
            
            commit_transaction();
        
                unset($_SESSION['mrt_items']);
                meta_forward($_SERVER['PHP_SELF'], "AddedID=".$amrt_msg['tran_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 can_delete_item($id)
{
    if($_SESSION['mrt_items']->line_items[$id]->issued_qty > 0){
        display_error("This item has some quantity issued. Can not delete this line.");
        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)
{
    if(can_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['mtr_no']) && $_GET['mtr_no'] > 0) 
{
    if(!isset($_SESSION['mrt_items']))
    {
        handle_new_order();
    }
    
    if($_GET['mtr_no'] != $_SESSION['mrt_items']->order_id)
    {
        handle_new_order();
    }
}
//-----------------------------------------------------------------------------------------------
start_form();

    global $Ajax;
    $guid = ST_REQTRANSFER;
    $_POST['guid'] = $guid;
    hidden("guid",$guid);
    display_material_requisition_transfer_header($_SESSION['mrt_items']);
        start_outer_table(TABLESTYLE, "width=95%", 10);
            $Ajax->activate('mat_req_trn');
            div_start('mat_req_trn');
                display_material_requisition_transfer_items(_("Material Requisition Items"), $_SESSION['mrt_items']);
            div_end();
            mrt_options_controls();
        end_outer_table(1, false);
    submit_center_first('Process', _("Create Material Requisition Transfer"), 'Create '.$systypes_array[ST_REQTRANSFER], 'default');    br(2);
    submit_center_first('Create_MRT_Close_MTR', _("Create Transfer and Close Requisition"), 
                        'Create '.$systypes_array[ST_REQTRANSFER].' & Close '.$systypes_array[ST_TRANSFERREQ], 'default');
    submit_center_last('Close_MTR', 'Close Requisition', 'Close '.$systypes_array[ST_TRANSFERREQ], false, ICON_ESCAPE);
    
end_form(3);

end_page();

?>