<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_MATERIAL_TRANSFER_REQ';
$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 . "/includes/approval_functions.inc");
include_once($path_to_root . "/includes/project_cost_functions.inc");
include_once($path_to_root . "/inventory/includes/material_transfer_requisitions_ui.inc");
include_once($path_to_root . "/inventory/includes/mtr_validations.inc");
include_once($path_to_root . "/inventory/includes/db/material_transfer_requisitions_db.inc");
include_once($path_to_root . "/reporting/includes/reporting.inc");
include_once($path_to_root . "/projects/includes/db/project_sites_db.inc");
include_once($path_to_root . "/assets/includes/db/assets_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 Transfer Requisition"), 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 (get_post('cancel')) {
    
    if($_SESSION['mtr_items']->approval_status == AS_APPROVED || $_SESSION['mtr_items']->approval_status == AS_REJECTED)
    {
        $Ajax->activate('_page_body');
    }
    else
    {
        $_SESSION['mtr_items']->clear_items();
            unset ($_SESSION['mtr_items']);
            clear_data();
	set_focus('requesting_location');
	$Ajax->activate('_page_body');
    }
}

if (isset($_GET['NewRequisition']))
{
    if(isset($_SESSION['mtr_items'])){
        $_SESSION['mtr_items']->clear_items();
        unset ($_SESSION['mtr_items']);
        clear_data();
        set_focus('requesting_location');
        $Ajax->activate('_page_body');
    }
}   

if (isset($_GET['ModifyMRNumber']) && is_numeric($_GET['ModifyMRNumber'])) 
{
    $help_context = 'Modifying Material Requisition';
    $_SESSION['page_title'] = sprintf( _("Modifying Material Requisition # %d"), $_GET['ModifyMRNumber']);
    
    	if (isset($_SESSION['mtr_items']))
	{
		$_SESSION['mtr_items']->clear_items();
		unset ($_SESSION['mtr_items']);
	}

    $_SESSION['mtr_items'] = new items_cart(ST_TRANSFERREQ);
    
    populate_cart_from_database($_GET['ModifyMRNumber']);
}        
        
        //-----------------------------------------------------------------------------------------------


function clear_data()
{
    unset ($_POST['requesting_location']);
    unset ($_POST['issuing_location']);
    unset ($_POST['mtr_reference']);
    unset ($_POST['mtr_date']);
    
    unset ($_POST['stock_id']);
    unset ($_POST['line_comment']);
}

function populate_cart_from_database($mtr_id)
{
    read_mtr($mtr_id, $_SESSION['mtr_items']);
    
    if(isset($_POST['movement_type'])){
        $_SESSION['mtr_items']->movement_type  = $_POST["movement_type"];
    }
    else{
        $_POST["movement_type"] = $_SESSION['mtr_items']->movement_type;
    }
        
}

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

        
if (isset($_GET['AddedID'])) 
{
	//return;
        
    $trans_no = $_GET['AddedID'];
	$trans_type = ST_TRANSFERREQ;
    
    $msg = get_session_variable('mtr_messages');
        
//	display_notification($msg);

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

	display_note(print_document_link($trans_no, _("&Print This Material Transfer Requisition"), true, $trans_type), 0, 0);

	hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &Another Material Transfer Requisition"));

	hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
    
    clear_session_variable('mtr_messages');

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

    $_SESSION['mtr_items'] = new items_cart(ST_TRANSFERREQ);
	$_POST['mtr_date'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['mtr_date']))
		$_POST['mtr_date'] = end_fiscalyear();
	$_SESSION['mtr_items']->tran_date = $_POST['mtr_date'];	
        $_SESSION['mtr_items']->next_approval_group_id = 0;
}

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

function can_process()
{
	global $Refs;

	$adj = &$_SESSION['mtr_items'];
        
    if($adj->order_id > 0){
        $mtr_info = get_mtr_edit_info($adj->order_id);
        if(!($mtr_info['approval_status'] == AS_NEW || $mtr_info['approval_status'] == AS_WITH_THE_APPROVER || $mtr_info['approval_status'] == AS_AWAITING_APPROVAL)){
            display_error("This Material Transfer Requisition status does not allow further updating.");
            return false;
        }
        
        $ced_msg = can_edit_document($adj->trans_type, $adj->project_id, $adj->next_approval_group_id, 
                                $_SESSION['wa_current_user']->user, $adj->created_by);
            if($ced_msg['success'] !== true){
                    display_error( $ced_msg['message']);
                    set_focus('issuing_location');
                    return false;
            }
        }
        
        if ($_POST['requesting_location'] == '') 
        {
                $input_error = 1;
                display_error( _('Select reqesting location.'));
                set_focus('requesting_location');
                return false;
        }

        if ($_POST['issuing_location'] == '') 
        {
                $input_error = 1;
                display_error( _('Select issuing location.'));
                set_focus('issuing_location');
                return false;
        }
        
        
        if (!$_POST['project_id'] > 0) 
        {
                $input_error = 1;
                display_error( _('Select a project.'));
                set_focus('project_id');
                return false;
        }
        
        if(($adj->order_id == 0 ) || ($adj->order_id == null) || ($adj->order_id == "" ))
        {
            if ($_POST['requesting_location'] == $_POST['issuing_location']) 
            {
                    display_error( _("Requesting location and Issuing location can not be same"));
                    set_focus('requesting_location');
                    return false;
            }

            if (!$Refs->is_valid($_POST['mtr_reference'])) 
            {
                    display_error( _("You must enter a reference."));
                    set_focus('mtr_reference');
                    return false;
            }

            $ref_msg = reference_exists($_POST['mtr_reference'], ST_TRANSFERREQ, $adj->order_id);
            if($ref_msg)        
            {
                    display_error( $ref_msg);
                    set_focus('mtr_reference');
                    return false;
            }

            if (!is_date($_POST['mtr_date'])) 
            {
                    display_error(_("The entered date for the material requisition is invalid."));
                    set_focus('mtr_date');
                    return false;
            } 
            elseif (!is_date_in_fiscalyear($_POST['mtr_date'])) 
            {
                    display_error(_("The entered date is not in fiscal year."));
                    set_focus('mtr_date');
                    return false;
            } 
        }
        
        if (! ($_POST['movement_type'] > 0)) {
            $input_error = 1;
            display_error( _('Select a movement type.'));
            set_focus('movement_type');
            return false;
        } else {
            $mv_tp = get_movement_type($_POST['movement_type']);
                if ($mv_tp['linked_field'] != IMLF_NOT_LINKED) {
                    
                    global $inventory_movement_type_linked_fields;
                    
                    switch ($mv_tp['linked_field']) {
                        case IMLF_EMPLOYEE:
                            if((strlen($_POST['linked_field_id']) <= 2)) {
                                $input_error = 1;
                                display_error( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                        case IMLF_ASSET:
                            if (! ($_POST['linked_field_id'] > 0)) {
                                $input_error = 1;
                                display_error( _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                        default :
                            if (! ($_POST['linked_field_id'] > 0)) {
                                $input_error = 1;
                                display_error( _('Select a '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.'));
                                set_focus('linked_field_id');
                                return false;
                            }
                            break;
                    }
                    
                    if ($mv_tp['linked_field'] == IMLF_ASSET) {
                        $asset_row = get_asset($_POST['linked_field_id']);
                            if ($asset_row['type'] == AT_VEHICLE) {
                                $message = 'Selected asset is a Vehicle. Only the assets of types "Fixed Asset" and "Tool" are allowed under this Movement Type.';
                                display_error($message);
                                set_focus('linked_field_id');
                                return false;
                            }
                    }
                }
        }
        
        if (count($adj->line_items) == 0)	
        {
            display_error(_("You must enter at least one non empty item line."));
            set_focus('stock_id');
            return false;
	}
        
	return true;
}

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

function add_mtr($release = false)
{

    clear_session_variable('mtr_messages');
    
        $amtr_msg = add_material_transfer_requisition($_SESSION['mtr_items'], $_SESSION['mtr_items']->line_items, $_POST['mtr_reference'], 
                                                    $_POST['requesting_location'], $_POST['issuing_location'], $_POST['mtr_date'], $_POST['memo_'], 0,  
                                                    $_POST['project_id'], $release, $_POST['movement_type'], $_SESSION['mtr_items']->sample_items,
                                                    get_post('linked_field_type'), $_POST['linked_field_id']);
    
    if($amtr_msg['success'] !== true){
        display_error($amtr_msg['message']);
    }
    else{
        $trans_no = $amtr_msg['tran_no'];
        new_doc_date($_POST['mtr_date']);
        $_SESSION['mtr_items']->clear_items();
        unset($_SESSION['mtr_items']);
        if($release == true){
            set_session_variable('mtr_messages', $amtr_msg['message']);
        }
        else{
            $text = $amtr_msg['tran_no'];
            set_session_variable('mtr_messages', $text);
        }
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
        
        
} 

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

function update_mtr($release = false)
{
        $amtr_msg = update_material_transfer_requisition($_SESSION['mtr_items']->order_id, $_SESSION['mtr_items'], $_POST['mtr_reference'], 
                                                    $_POST['requesting_location'], $_POST['issuing_location'], $_POST['mtr_date'], $_POST['memo_'], 0,  
                                                    $_POST['project_id'], $release, $_POST['movement_type'], $_SESSION['mtr_items']->row_state,
                                                    get_post('linked_field_type'), $_POST['linked_field_id']);
    
    $trans_no = $_SESSION['mtr_items']->order_id;
    
	if($amtr_msg['success'] !== true){
        display_error($amtr_msg['message']);
    }
    else{        
        new_doc_date($_POST['mtr_date']);
        $_SESSION['mtr_items']->clear_items();
        unset($_SESSION['mtr_items']);
        if($release == true){
            set_session_variable('mtr_messages', $amtr_msg['message']);
        }
        else{
            $text = $trans_no;
            set_session_variable('mtr_messages', $text);
        }
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
        
} 


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

function reject_mtr()
{
    if(!can_process()){
        return;
    }
    
    $mtr = $_SESSION['mtr_items'];
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rd_msg = reject_document($mtr->trans_type, $mtr->order_id, $mtr->project_id,
                    $mtr->next_approval_group_id, $current_user_id, $mtr->row_state);
    
    if($rd_msg['success'] !== true){
        cancel_transaction();
        display_error($rd_msg['message']);
    }
    else{
        $trans_no = $rd_msg['tran_no'];
        new_doc_date($_POST['mtr_date']);
        $_SESSION['mtr_items']->clear_items();
        unset($_SESSION['mtr_items']);
        set_session_variable('mtr_messages', "Material Transfer Requisition ".$rd_msg['tran_no']." has been rejected.");
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }

}


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

function send_mtr_back_to_originator()
{
    if(!can_process()){
        return;
    }
    
    $mtr = $_SESSION['mtr_items'];
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $sbdo_msg = send_back_to_document_originator($mtr->trans_type, $mtr->order_id, $mtr->project_id,
                                    $mtr->next_approval_group_id, $current_user_id, $mtr->row_state, 
                                    $mtr->created_by);
    
    if($sbdo_msg['success'] !== true){
        cancel_transaction();
        display_error($sbdo_msg['message']);
    }
    else{
        $trans_no = $sbdo_msg['tran_no'];
        new_doc_date($_POST['mtr_date']);
        $_SESSION['mtr_items']->clear_items();
        unset($_SESSION['mtr_items']);
        set_session_variable('mtr_messages', $sbdo_msg['message']);
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }

}
//-------------------------------------------------------------------------------

if (isset($_POST['Back_To_Originator'])){

    send_mtr_back_to_originator();
        
} 


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

if (isset($_POST['Reject_MTR'])){

    reject_mtr();
        
} 


//-------------------------------------------------------------------------------
if (isset($_POST['Update_MTR'])){


    $result = can_process();
    
    if($result === true){
        update_mtr();
    }
} 


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

if (isset($_POST['Update_Release'])){

    
    $result = can_process();
    
    if($result === true){
        update_mtr(true);
    }

} 
if (isset($_POST['Add_MTR'])){

    $result = can_process();
    
    if($result === true){
        add_mtr();
    }

} 


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

if (isset($_POST['Add_Release'])){


    $result = can_process();
    
    if($result === true){
        add_mtr(true);
    }

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

function check_item_data(&$order) {
    if ($_POST['stock_id'] == '') {
        display_error(_("Please select an item."));
        set_focus('stock_id');
        return false;
    } 
    
    if(isset($order->sample_items)){
        
        if(isset($_POST['sample_items']) && $order->sample_items != $_POST['sample_items']){
            if($_POST['sample_items'] == 1)
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 1)
                {
                    display_error(_("Selected item is not a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
            else
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 0)
                {
                    display_error(_("Selected item is a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
        }
        else{
            if($order->sample_items == 1)
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 1)
                {
                    display_error(_("Selected item is not a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
            else
            {
                $item = get_item($_POST['stock_id']);
                if($item['sample_item'] != 0)
                {
                    display_error(_("Selected item is a sample item."));
                    set_focus('stock_id');
                    return false;
                }    
            }
        }
             
    }
    else{
        if($_POST['sample_items'] == 1)
        {
            $item = get_item($_POST['stock_id']);
            if($item['sample_item'] != 1)
            {
                display_error(_("Selected item is not a sample item."));
                set_focus('stock_id');
                return false;
            }    
        }
        else
        {
            $item = get_item($_POST['stock_id']);
            if($item['sample_item'] != 0)
            {
                display_error(_("Selected item is a sample item."));
                set_focus('stock_id');
                return false;
            }    
        }
    }

	if (!check_num('tran_qty',0.01))
	{
		display_error(_("The quantity entered is negative or invalid."));
		set_focus('tran_qty');
		return false;
	}
        
//        if ($_POST['task_id'] <= 0 ) {
//            display_error(_("Please select a budget."));
//            set_focus('task_id');
//            return false;
//	}

   	return true;
}

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

function check_delete_item($id)
{
	global $Refs;
        
        $adj = &$_SESSION['mtr_items'];

        if ($adj->line_items[$id]->issued_qty > 0) 
	{
		display_error( _("This item has some quantities issued. Not possible to delete."));
		set_focus('stock_id');
		return false;
	}
        return true;
}
 
//-----------------------------------------------------------------------------------------------

function check_update_item($id_edit)
{
	global $Refs;

        $adj = &$_SESSION['mtr_items'];
         
        if ($_POST['qty'] < $adj->line_items[$id_edit]->issued_qty) 
	{
		display_error( _("Can not reduce quantity below issued quantity."));
		set_focus('stock_id');
		return false;
	}

        return true;
}
 
//-----------------------------------------------------------------------------------------------
   
        
function handle_update_item() {
    $id_edit = $_POST['LineNo'];
    
    
    if($_POST['UpdateItem'] != "" && check_item_data($_SESSION['mtr_items']) && check_update_item($id_edit)) {
		
    	$adj = &$_SESSION['mtr_items'];
        $convertion_factor = $adj->line_items[$id_edit]->convertion_factor;
        $tran_unit = $adj->line_items[$id_edit]->tran_unit;
        $standard_cost = $adj->line_items[$id_edit]->standard_cost;
        
        $adj->update_cart_item($id_edit, input_num('tran_qty')*$convertion_factor, $standard_cost, 
                                null, null, null, null, null, input_num('tran_qty'),$tran_unit, $convertion_factor);
        
        
            $adj->line_items[$id_edit]->requested_qty = input_num('tran_qty')*$convertion_factor;
            $adj->line_items[$id_edit]->required_date = $_POST['line_required_date'];
            $adj->line_items[$id_edit]->line_comment = $_POST['line_comment'];
            
        $task_id = 0;
        $task_description = '';
//        if($_POST['task_id'] != -1){
//            $project_task = get_task_details($_POST['task_id']);
//            $task_id = $project_task['task_id'];
//            $task_description = $project_task['description'];
//        }
        $adj->line_items[$id_edit]->task_id = $task_id;
        $adj->line_items[$id_edit]->task_description = $task_description; 
        
        $project_site_id = 0;
        $project_site_description = '';
        if($_POST['project_site_id'] != -1){
            $project_site = get_project_site_details($_POST['project_site_id']);
            $project_site_id = $project_site['id'];
            $project_site_description = $project_site['description'];
        }
        $adj->line_items[$id_edit]->project_site_id = $project_site_id;
        $adj->line_items[$id_edit]->project_site_description = $project_site_description;
        
    }
	line_start_focus();
}

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

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

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

function handle_new_item() {
    if (! check_item_data($_SESSION['mtr_items'])) {
            return false;
    }
        
        $item_info = get_stock_item_edit_info($_POST['stock_id']);
        $alternate_unit = get_convertion_factor($_POST['tran_unit'], $_POST['stock_id']);
        $convertion_factor = $alternate_unit['convertion_factor'];
        
        add_mtr_to_cart($_SESSION['mtr_items'], $_POST['stock_id'],input_num('qty'), $_POST['line_required_date'], 
                        $_POST['line_comment'], $item_info['standard_cost'], $_POST['tran_unit'], input_num('tran_qty'), 
                        $convertion_factor);
        
        $adj = &$_SESSION['mtr_items'];
        if($alternate_unit == ""){
            $convertion_factor = 1;
        }
        $current_element = (count($adj->line_items)-1);
        $adj->line_items[$current_element]->requested_qty = input_num('tran_qty')*$convertion_factor;
        $adj->line_items[$current_element]->high_value_item = $item_info["high_value_item"];
        $adj->line_items[$current_element]->sample_item = $item_info["sample_item"];
        $adj->line_items[$current_element]->reference_cost = $item_info["reference_cost"];
        
        if(count($adj->line_items) > 0 && !isset($adj->sample_items)){
            $adj->sample_items = $_POST['sample_items'];
        }
        elseif(isset($_POST['sample_items']) && $adj->sample_items != $_POST['sample_items']){
            $adj->sample_items = $_POST['sample_items'];
        }
        
        $task_id = 0;
        $task_description = '';
//        if($_POST['task_id'] != -1){
//            $project_task = get_task_details($_POST['task_id']);
//            $task_id = $project_task['task_id'];
//            $task_description = $project_task['description'];
//        }
        $adj->line_items[$current_element]->task_id = $task_id;
        $adj->line_items[$current_element]->task_description = $task_description;
        
        $project_site_id = 0;
        $project_site_description = '';
        if($_POST['project_site_id'] != -1){
            $project_site = get_project_site_details($_POST['project_site_id']);
            $project_site_id = $project_site['id'];
            $project_site_description = $project_site['description'];
        }
    $adj->line_items[$current_element]->project_site_id = $project_site_id;
    $adj->line_items[$current_element]->project_site_description = $project_site_description;
    
    
	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['mtr_items']))
{
	handle_new_order();
}

//-----------------------------------------------------------------------------------------------
start_form();

    display_mtr_header($_SESSION['mtr_items']);
    start_outer_table(TABLESTYLE, "width=80%", 10);
        $Ajax->activate('mtr_items_table');
        div_start('mtr_items_table');
            display_mtr_items(_("Material Requisition Items"), $_SESSION['mtr_items']);
        div_end();
        mtr_options_controls($_SESSION['mtr_items']);
    end_outer_table(2, false);


if((isset($_SESSION['mtr_items'])) && ($_SESSION['mtr_items']->order_id > 0))
{
    submit_center_first('Update_MTR', _("Update"), '', 'default');
    submit('Update_Release', 'Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
    br();
    submit_center_first('Back_To_Originator', "Back To Originator", '', 'default');
    submit_center_last('Reject_MTR', "Reject", '', 'default');
}
else
{
    submit_center_first('Add_MTR', _("Save Requisition"), '', 'default');
    submit('Add_Release', 'Save and Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}



end_form(3);
end_page();

?>
