<?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/issue_materials_ui.inc");
include_once($path_to_root . "/inventory/includes/mr_validations.inc");
include_once($path_to_root . "/inventory/includes/db/issue_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 . "/includes/db/approval_functions_db.inc");
include_once($path_to_root . "/gl/includes/db/gl_journal.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 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_ISSUE;
    $message = get_session_variable('im_messages');
    clear_session_variable('im_messages');
    
	display_notification_centered($message);
	
        display_note(get_inventory_trans_view_str($trans_type, $trans_no, _("View this Material Issue")), 1); 
	
        hyperlink_no_params("$path_to_root/inventory/inquiry/outstanding_material_requisitions_inquiry.php", _("Process &Another Material Requisition"));

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

        $_SESSION['im_items'] = new items_cart(ST_MATERIAL_ISSUE);
        
        $mr_no = $_GET['mr_no'];
        populate_mr_cart_from_database('im_items', $mr_no);
	
}


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


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

    $total_qty = 0;

    if(!($_SESSION['im_items']->approval_status == AS_APPROVED || $_SESSION['im_items']->approval_status == AS_ISSUED))
    {
        display_error("Status of this Material Requisition does not allow material issues against it.");
        return false;
    }
    
    foreach ($_SESSION['im_items']->line_items as $line_item)
    {
        $line_item->check_issue_item = false;
        
        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 budget selected for the item [".$line_item->stock_id."]");
                set_focus($line_item->row_id."_tran_qty");
                return false;
            }
            
            if(input_num2($_POST[$line_item->row_id.'_tran_qty'])){
                $line_item->check_issue_item = true;
            }
            
            $total_qty += input_num($line_item->row_id."_tran_qty");
        }
    }     

    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['employee_code']) > 1)){ 
        display_error(_("Please select issuing to employee."));
        set_focus('employee_code');
        return false;
    }
    
    if (strlen($_POST['im_reference']) == 0){
        display_error( _("You must enter a reference."));
        set_focus('im_reference');
        return false;
    }

    $ref_msg = reference_exists($_POST['im_reference'], ST_MATERIAL_ISSUE);
    if ($ref_msg) 
    {
        display_error( _($ref_msg));
        set_focus('im_reference');
        return false;
    }
    
    if(!is_date($_POST['im_date'])){ 
        display_error(_("Date entered is invalid."));
        set_focus('im_date');
        return false;
    }
    
    if (!is_date_in_fiscalyear($_POST['im_date'])) 
    {
        display_error(_("The entered date is not in fiscal year."));
        set_focus('im_date');
        return false;
    } 
    
    $msg = is_accounting_period_open($_POST['im_date']);
    if ($msg['success'] !== true)
    {
        display_error($msg['message']);
        set_focus('im_date');
        return false;
    }
/*
    foreach ($_SESSION['im_items']->line_items as $line_item) {		
	            		
        if($_POST[$line_item->row_id.'_tran_qty'] > $line_item->requested_qty + $line_item->issued_qty)		
        {		
            display_error(_("Issuing quantity can not be greater than the sum of requested quantity and issued quantity."));		
            set_focus($line_item->row_id.'_tran_qty');		
            return false;		
        }		
	}
*/    
    $vmtd_msg = validate_movement_type_data('movement_type', 'linked_field_id');
    if ($vmtd_msg['success'] !== true) 		
    {
        display_error($vmtd_msg['message']);
        return false;
    }
    
    $vtqd_msg = validate_transaction_quantity_details($_SESSION['im_items']);		
    if ($vtqd_msg['success'] !== true) 		
    {
        display_error($vtqd_msg['message']);
        return false;
    }

        
    return true;
}


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


function can_close_material_requisition()
{

    if(!($_SESSION['im_items']->approval_status == AS_APPROVED || $_SESSION['im_items']->approval_status == AS_ISSUED))
    {
        display_error("Status of this Material Requisition does not allow closing it.");
        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['im_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['im_items']->line_items as $line_item)
    {
        
        $issuing_unit = $_POST[$line_item->row_id."_tran_unit"];
        
        get_convertion_factor2($line_item->stock_id, $issuing_unit, $convesion_factor);
        
        $line_item->convertion_factor = $convesion_factor;
        $line_item->tran_unit = $issuing_unit;
        
        $line_item->tran_qty = input_num($line_item->row_id."_tran_qty");
        
        
        $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['im_items']->clear_items();
        //return;
	unset($_SESSION['im_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){
    
        if(!can_close_material_requisition()){
            return;
        }
        $cmr_msg = close_mr($mr_no, AS_CLOSED);
        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_materials_issue($close_mr = false)
{
    update_cart();
    
    if(!can_process_issue_materials()){
        return;
    }
    
    $source_mr_no = $_SESSION['im_items']->order_id;
    
    $aim_msg = add_issue_materials($_SESSION['im_items']->line_items, $_POST['im_reference'], $_POST['issuing_location'], 
                                    $_SESSION['im_items']->project_id, $_POST['memo_'], 
                                    $source_mr_no, $_SESSION['im_items']->row_state, $_SESSION['im_items']->approval_status,
                                    $_POST['employee_company_code'], $_POST['employee_code'], $_POST['im_date'],        
                                    $_POST['movement_type'], $_POST['linked_field_type'], $_POST['linked_field_id'], $_POST['group_company_code']);           

                
    if($aim_msg['success'] !== true){
        display_error("Could not add material issue");
        return;
    }
    
    $can_close_mr =  false;
    $closing_status = AS_ISSUED;
    
    if(check_all_mr_lines_issued($source_mr_no)=== true){
        $can_close_mr = true;
        $closing_status = AS_COMPLETED;
    }
    else{
        if($close_mr){
            $can_close_mr = true;
            $closing_status = AS_CLOSED;
        }        
    }    
    
    if($can_close_mr){
        $cmr_msg = close_mr($source_mr_no, $closing_status);
        if($cmr_msg['success'] !== true){
            display_error($cmr_msg['message']);
        }
    }
    set_session_variable('im_messages', $aim_msg['message']);
    end_processing($aim_msg['tran_no']);
          
    
}

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


if (isset($_POST['Create_IM']))
{
    create_materials_issue();
} 

if (isset($_POST['Create_IM_Close_MR'])){
    create_materials_issue(true);
}

if(isset($_POST['Close_MR'])){
    close_material_requisition($_SESSION['im_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['im_items']))
    {
        handle_new_order();
    }
    
    if($_GET['mr_no'] != $_SESSION['im_items']->order_id)
    {
        handle_new_order();
    }
}
//-----------------------------------------------------------------------------------------------
start_form();

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

display_material_requisition_header($_SESSION['im_items']);

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

display_material_requisition_items(_("Material Requisition Items"), $_SESSION['im_items']);
mrt_options_controls();

end_outer_table(1, false);

//submit_center_first('Update', _("Update"), '', null);
submit_center_first('Create_IM', _("Create Material Issue"), '', 'default');
br(2);
submit_center_first('Create_IM_Close_MR', _("Create MI & Close MR"), '', 'default');
//submit('Create_IM_Close_MR', 'Create MI & Close MR', true, '', 'default');
submit_center_last('Close_MR', 'Close MR ', '', 'default');

end_form(2);

br(1);
end_page();

?>
