<?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/return_materials_ui.inc");
include_once($path_to_root . "/inventory/includes/mr_validations.inc");
include_once($path_to_root . "/inventory/includes/db/return_materials_db.inc");
include_once($path_to_root . "/inventory/includes/db/material_requisitions_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 . "/purchasing/includes/pr_validations.inc");

include_once($path_to_root . "/includes/ui/ui_lists_group_companies.inc");
include_once($path_to_root . "/includes/db/group_companies_db.inc");
include_once($path_to_root . "/inventory/includes/db/issue_materials_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 = "Return 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['Added_MI_ID'])) 
{
	//return;
        
    $trans_no = $_GET['Added_MI_ID'];
	$trans_type = ST_MATERIAL_RETURN;
    $message = get_session_variable('im_messages');
    clear_session_variable('im_messages');
    
	display_notification_centered($message);
        
	display_note(print_document_link($trans_no, _("&Print This Material Return"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/inventory/inquiry/material_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['Added_PR_ID'])) 
{
	//return;
        
    $pr_no = $_GET['Added_PR_ID'];
	$trans_type = ST_PURCH_REQ;

	$message = get_session_variable('im_messages');
    clear_session_variable('im_messages');
    
	display_notification_centered($message);
        
	display_note(print_document_link($pr_no, _("&Print this purchase requisition"), true, $trans_type), 0, 0);

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

        $_SESSION['rm_items'] = new items_cart(ST_MATERIAL_RETURN);
        
        populate_cart_from_database();
	
}

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

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

        $im_cart->order_id = $myrow["mr_no"];
        $im_cart->reference = $myrow["reference"];
        $im_cart->issuing_location  = $myrow["issuing_location"];
        $im_cart->issuing_location_name  = $myrow["issuing_location_name"];
        $im_cart->receiving_location  = '';
        $im_cart->receiving_location_name  = '';
        $im_cart->required_date  = $myrow["mr_required_date"];
        $im_cart->memo_  = $myrow["comments"];
        $im_cart->requestor_name  = $myrow["requestor_name"];
        $im_cart->movement_type  = $myrow["movement_type"];
        $im_cart->movement_type_name  = $myrow["movement_type_name"];
        $im_cart->linked_field_type = $myrow["linked_field_type"];
        $im_cart->linked_field_id  = $myrow["linked_field_id"];
        $im_cart->created_on  = $myrow["created_on"];
        $im_cart->project_description  = $myrow["project_description"];
        $im_cart->approval_path_description  = $myrow["approval_path_description"];
//        $im_cart->mr_complete  = $myrow["mr_complete"];
        $im_cart->project_id  = $myrow["project_id"];
        //        $im_cart->approval_path_id  = $myrow["approval_path_id"];
        $im_cart->approval_status  = $myrow["approval_status"];
        $im_cart->pr_no  = $myrow["pr_no"];
        $im_cart->row_state  = $myrow["row_state"];
  
        $im_details = get_mr_details($im_cart->order_id);

        $element_no = 0;
        while ($imtd_row = db_fetch($im_details)) 
        {
            $im_line = new line_item($imtd_row["stock_id"], 0, $imtd_row["standard_cost"], 
                    $imtd_row["description"],sql2date($imtd_row["required_date"]), $imtd_row["line_comment"],$myrow["comments"],
                    $imtd_row["id"], $imtd_row["issued_qty"], $imtd_row["requested_qty"], 0, $imtd_row["price"], null, 0, 
                    null, null, null, null, null, $imtd_row["requested_unit"], $imtd_row["requested_unit_qty"], 
                    $imtd_row["req_unit_conv_factor"]);

            $im_line->row_id = $imtd_row["id"];
            $im_line->high_value_item = $imtd_row["high_value_item"];
            $im_line->sample_item = $imtd_row["sample_item"];
            $im_line->reference_cost = $imtd_row["reference_cost"];
            $im_line->stock_control_method = $imtd_row["stock_control_method"];
            $im_line->pr_line_id = $imtd_row["pr_line_id"];
            $im_line->task_id = $imtd_row["task_id"];
            $im_line->task_description = $imtd_row["task_description"];
            $im_line->project_site_id = $imtd_row["project_site_id"];
            $im_line->project_site_description = $imtd_row["project_site_description"];
            $im_line->returned_qty = $imtd_row["returned_qty"];
            $im_line->line_ref = $im_line->row_id;
                                    
            $im_cart->line_items[$element_no] = $im_line;
            $element_no++;
        }

}

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


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

    $total_qty = 0;

    if(!($_SESSION['rm_items']->approval_status == AS_APPROVED || 
            $_SESSION['rm_items']->approval_status == AS_ISSUED || 
            $_SESSION['rm_items']->approval_status == AS_COMPLETED || 
            $_SESSION['rm_items']->approval_status == AS_CLOSED))
    {
        display_error("Status of this Material Requisition does not allow material returns against it.");
        return false;
    }
    
    if(!is_date($_POST['rm_date'])) 
	{
		display_error( _("Date entered is invalid."));
		set_focus('rm_date');
		return false;
	}
        
    if (!is_date_in_fiscalyear($_POST['rm_date'])) 
    {
        display_error(_("The entered date is not in fiscal year."));
        set_focus('rm_date');
        return false;
    } 
    
    $msg = is_accounting_period_open($_POST['rm_date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);
        set_focus('rm_date');
        return false;
    }
    
	foreach ($_SESSION['rm_items']->line_items as $line_item)
    {
        if (isset($_POST[$line_item->row_id.'_check_mr_item']) && $_POST[$line_item->row_id.'_check_mr_item'] == true)
        {
            if (!check_num($line_item->row_id.'_tran_qty',0))
            {
                display_error(_("The quantity entered for item [".$line_item->stock_id."] is negative or invalid."));
                set_focus($line_item->row_id."_tran_qty");
                return false;
            }
            if(!(isset($line_item->task_id) && $line_item->task_id > 0)){
                display_error("No task selected for the item [".$line_item->stock_id."]");
                set_focus($line_item->row_id."_tran_qty");
                return false;
            }
            
            $line_item->check_issue_item = true;
            
            $total_qty += input_num($line_item->row_id."_tran_qty");
        }
        else{
            $line_item->check_issue_item = false;
        }
    }     

    if($total_qty == 0){ 
        display_error(_("No lines with valid quantities selected."));
        set_focus($line_item->row_id."_tran_qty");
        return false;
    }
    
    if (strlen($_POST['rm_reference']) == 0) 
	{
		display_error( _("You must enter a reference."));
		set_focus('rm_reference');
		return false;
	}

    if (!$Refs->is_valid($_POST['rm_reference'])) 
	{
		display_error( _("Entered reference already exists."));
		set_focus('rm_reference');
		return false;
	}

    if(!(strlen($_POST['group_company_employee_code']) > 1)){ 
        display_error(_("Please select an employee."));
        set_focus('group_company_employee_code');
        return false;
    }
    
    $convesion_factor = 1;
    foreach ($_SESSION['rm_items']->line_items as $line_item) {		
        $stock_id = $line_item->stock_id;     
        get_convertion_factor2($stock_id, $_POST[$line_item->row_id.'_tran_unit'], $convesion_factor);
        
        $total_qty_issued = get_issue_material_details_qty_issued($line_item->row_id);
        $total_qty_returned = get_return_material_details_qty_returned($line_item->row_id);
        
        $balance_qty = ($total_qty_issued + 0.00000001) - $total_qty_returned;
        $max_returnable_qty = $balance_qty / $convesion_factor;
        
        $tran_qty = input_num($line_item->row_id.'_tran_qty');
        
        if ($tran_qty > $max_returnable_qty)	{		
            $balance_qty = $total_qty_issued - $total_qty_returned;
            $actual_max_returnable_qty = $balance_qty / $convesion_factor;
            
            display_error(_("Line #$line_item->row_id Returning quantity can not be greater than $actual_max_returnable_qty."));		
            set_focus($line_item->row_id.'_tran_qty');		
            return false;		
        }		
    }
    
    
    $vtqd_msg = validate_transaction_quantity_details($_SESSION['rm_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_MATERIAL_ISSUE])){
        return;
    }
    
    $lot_info_array =  $_SESSION['lot_info#'.ST_MATERIAL_ISSUE];

    foreach ($_SESSION['rm_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['rm_items']->line_items as $line_item)
    {

//        $tran_unit_convertion = get_convertion_factor($_POST[$line_item->row_id."_tran_unit"], $line_item->stock_id);
//        if($tran_unit_convertion == false){
//            $tran_unit_convertion_factor = 1;
//            $item = get_item($line_item->stock_id);
//            $issued_unit = $item['units'];
//        }
//        else{
//            $tran_unit_convertion_factor = $tran_unit_convertion['convertion_factor'];
//            $issued_unit = $_POST[$line_item->row_id."_tran_unit"];
//        }
        
        $tran_unit = $_POST[$line_item->row_id."_tran_unit"];
        $stock_id = $line_item->stock_id; 
        $tran_unit_convertion_factor = 1;
        
        get_convertion_factor2($stock_id, $tran_unit, $tran_unit_convertion_factor);
        
        $line_item->convertion_factor = $tran_unit_convertion_factor;
        
        $line_item->tran_qty = input_num($line_item->row_id."_tran_qty");
        $line_item->tran_unit = $tran_unit;
        
        $lot_details = get_selected_lot_serial_info('guid', $line_item);
        $line_item->lot_details = $lot_details;    
        
        
        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;
        }
    }
}

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

function end_processing($trans_no, $type = ST_MATERIAL_ISSUE)
{
        //return;
 	$_SESSION['rm_items']->clear_items();
        //return;
	unset($_SESSION['rm_items']);        
    unset($_SESSION[ST_MATERIAL_ISSUE]);   
    
    if($type == ST_MATERIAL_ISSUE){
        meta_forward($_SERVER['PHP_SELF'], "Added_MI_ID=$trans_no");
    }
    elseif($type == ST_PURCH_REQ){
        meta_forward($_SERVER['PHP_SELF'], "Added_PR_ID=$trans_no");
    }
}

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

function close_material_requisition($mr_no){
        $cmr_msg = close_mr($mr_no);
        if($cmr_msg['success'] !== true){
            display_error($cmr_msg['message']);
        }
        else{
            set_session_variable('im_messages', "Material requisition ".$mr_no." has been closed");
            end_processing($mr_no); 
        }
}

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

function create_material_return()
{
    update_cart();
    
    $result = can_process_return_materials();
    
    if($result == true)  
    {
        $aim_msg = add_return_materials($_SESSION['rm_items']->line_items, $_POST['rm_reference'],  
                                        $_POST['receiving_location'], $_SESSION['rm_items']->project_id, $_POST['memo_'], 
                                        $_SESSION['rm_items']->order_id, $_SESSION['rm_items']->row_state, $_SESSION['rm_items']->approval_status,
                                        $_POST['group_company_code'], $_POST['group_company_employee_code'], $_POST['rm_date']);
                
        if($aim_msg['success'] !== true){
            display_error("Could not add material return");
        }
        else{
            set_session_variable('im_messages', $aim_msg['message']);
            end_processing($aim_msg['tran_no']);
        }      
    }
}

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


if (isset($_POST['Create_RM']))
{
    create_material_return();
} 

//if (isset($_POST['Create_IM_Close_MR'])){
//    create_materials_issue(true);
//}
//
//if(isset($_POST['Close_MR'])){
//    close_material_requisition($_SESSION['rm_items']->order_id);
//}



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


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

$guid = ST_MATERIAL_ISSUE;
$_POST['guid'] = $guid;
hidden("guid",$guid);

display_material_return_header($_SESSION['rm_items']);

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

display_material_return_items(_("Material Requisition Items"), $_SESSION['rm_items']);
mrt_options_controls();

end_outer_table(1, false);

//submit_center_first('Update', _("Update"), '', null);
submit_center_first('Create_RM', _("Create Material Return"), '', 'default');
//submit('Create_IM_Close_MR', 'Create MI & Close MR', true, '', 'default');
//submit_center_last('Close_MR', 'Close MR ', '', 'default');

end_form();
end_page();

?>
