<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_STOCK_RESERVATION';
$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/stock_reservations_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 . "/projects/includes/db/projects_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 = "Stock Reservation"), 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['sr_items']->approval_status == AS_APPROVED || $_SESSION['sr_items']->approval_status == AS_REJECTED)
    {
        $Ajax->activate('_page_body');
    }
    else
    {
        $_SESSION['sr_items']->clear_items();
            unset ($_SESSION['sr_items']);
            clear_data();
	set_focus('requesting_location');
	$Ajax->activate('_page_body');
    }
}

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

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


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



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

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

	display_notification_centered(_("Stock Reservation ".$trans_no." has been saved"));
    
	display_note(get_trans_view_str($trans_type, $trans_no, _("&View this Stock Reservation")));

	display_note(print_document_link($trans_no, _("&Print This Stock Reservation"), true, $trans_type), 0, 0);

	hyperlink_no_params($_SERVER['PHP_SELF'], _("Enter &Another Stock Reservation"));

	//hyperlink_params("$path_to_root/admin/attachments.php", _("Add an Attachment"), "filterType=$trans_type&trans_no=$trans_no");
    
    clear_session_variable('sr_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['sr_items']))
	{
		$_SESSION['sr_items']->clear_items();
		unset ($_SESSION['sr_items']);
	}

    $_SESSION['sr_items'] = new items_cart(ST_STOCK_RESERVATION);
	$_POST['sr_date'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['sr_date'])){
		$_POST['sr_date'] = end_fiscalyear();
    }
	$_SESSION['sr_items']->tran_date = $_POST['sr_date'];	
        $_SESSION['sr_items']->next_approval_group_id = 0;
}

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

function can_process()
{
	global $Refs;

	$adj = &$_SESSION['sr_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['location'] == '') 
        {
                display_error( _('Select a location.'));
                set_focus('location');
                return false;
        }
        
        if (!$_POST['project_id'] > 0) 
        {
                display_error( _('Select a project.'));
                set_focus('project_id');
                return false;
        }

        $reservation_location_code = "";
        $reservation_location = get_reservation_location($_POST['location']);
        if ($reservation_location){
            $reservation_location_code = $reservation_location['loc_code']; 
        }
        if($reservation_location_code == null || strlen($reservation_location_code) == 0)
        {
                display_error("There is no Reservation Location set for the selected location. "
                        . "Please select another location or contact your System Administrator");
                set_focus('location');
                return false;
        }
        else{
            $adj->reservation_location = $reservation_location_code;
        }
        
        
        if(($adj->order_id == 0 ) || ($adj->order_id == null) || ($adj->order_id == "" ))
        {

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

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

            if (!is_date($_POST['sr_date'])) 
            {
                    display_error(_("The entered date for the material requisition is invalid."));
                    set_focus('sr_date');
                    return false;
            } 
            elseif (!is_date_in_fiscalyear($_POST['sr_date'])) 
            {
                    display_error(_("The entered date is not in fiscal year."));
                    set_focus('sr_date');
                    return false;
            } 
        }
        
        if (! ($_POST['movement_type'] > 0)) {
            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;
	}
    
    $asp = all_sites_belongs_to_the_project($_POST['project_id'], $adj->line_items);
    if($asp['success'] !== true){
        display_error($asp['message']);
        return false;
    }
        
	return true;
}

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

function add_sr()
{

	clear_session_variable('sr_messages');

	$amtr_msg = add_stock_reservation($_SESSION['sr_items'], $_SESSION['sr_items']->line_items, 
                $_POST['sr_reference'], $_POST['location'], $_SESSION['sr_items']->reservation_location, 
                $_POST['sr_date'], $_POST['memo_'],   
                $_POST['project_id'], $_POST['movement_type'], 
                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['sr_date']);
        $_SESSION['sr_items']->clear_items();
        unset($_SESSION['sr_items']);

        $text = $amtr_msg['tran_no'];
        set_session_variable('sr_messages', $text);
        
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
        
        
} 

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



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



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


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


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

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

} 


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


function end_processing($trans_no)
{
        //return;
 	$_SESSION['sr_items']->clear_items();
        //return;
	unset($_SESSION['sr_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;
    }
    
	$mb_flag = get_mb_flag($_POST['stock_id']);    
    if (is_service($mb_flag))
    {
        display_db_error("Cannot reserve Service item : ".$_POST['stock_id']);
        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;
	}

   	return true;
}

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

function check_delete_item($id)
{
	global $Refs;
        
        $adj = &$_SESSION['sr_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['sr_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['sr_items']) && check_update_item($id_edit))
    {
		
    	$adj = &$_SESSION['sr_items'];
        $convertion_factor = $adj->line_items[$id_edit]->convertion_factor;
        $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'), $adj->line_items[$id_edit]->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'];
        
        $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;
        
    }
    
    update_cart($adj);
    
	line_start_focus();
}

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

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

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

function handle_new_item()
{
	if (!check_item_data($_SESSION['sr_items'])){
		return false;
    }
        
        $item_info = get_stock_item_edit_info($_POST['stock_id']);
        $alternate_unit = get_convertion_factor2($_POST['stock_id'], $_POST['tran_unit'], $convertion_factor);
        
        add_stock_reservation_to_cart($_SESSION['sr_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['sr_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'];
//        }
        
        $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;
    
    update_cart($adj);
    
	line_start_focus();
}


function update_cart(&$sr)
{
    if(isset($_POST['project_id'])){
        $sr->project_id = $_POST['project_id'];
    }
    $sr->movement_type = $_POST['movement_type'];
    $sr->location = $_POST['location'];
}
//-----------------------------------------------------------------------------------------------
$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['sr_items']))
{
	handle_new_order();
}

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

display_stock_reservation_header($_SESSION['sr_items']);

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

display_stock_reservation_items(_("Stock Reservation Items"), $_SESSION['sr_items']);
stock_reservation_options_controls($_SESSION['sr_items']);

end_outer_table(1, false);


if((isset($_SESSION['sr_items'])) && ($_SESSION['sr_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_SR', _("Save Reservation"), '', false, ICON_SUBMIT);
    //submit('Add_Release', 'Save and Release for Approval', true, '', 'default');
    submit_center_last('cancel', _("Cancel"), _("Cancel Edition"), 'cancel');
}



end_form(3);
end_page();

?>
