<?php
/**********************************************************************
***********************************************************************/
$page_security = 'SA_STOCK_RELEASE';
$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/stock_reservation_releases_ui.inc");
include_once($path_to_root . "/inventory/includes/db/stock_reservation_releases_db.inc");
include_once($path_to_root . "/inventory/includes/db/stock_reservations_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 . "/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 = "Stock Reservation Release"), 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_STOCK_RELEASE;

	display_notification_centered(_("Stock Reservation Release ".$trans_no." has been saved"));
        
	display_note(print_document_link($trans_no, _("&Print This Stock Reservation Release"), true, $trans_type), 0, 0);

	hyperlink_no_params("$path_to_root/inventory/inquiry/stock_reservation_inquiry.php", _("Process &Another Stock Reservation Release"));

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

        $_SESSION['srr_items'] = new items_cart(ST_STOCK_RELEASE);
        
        populate_cart_from_database($sr_no);
	
}

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

function populate_cart_from_database($sr_no)
{
        $myrow = get_stock_reservation($sr_no);
        
        $sr_cart = $_SESSION['srr_items'];

        $sr_cart->order_id = $myrow["id"];
        $sr_cart->reference = $myrow["reference"];
        $sr_cart->location  = $myrow["location"];
        $sr_cart->location_name  = $myrow["location_name"];
        $sr_cart->required_date  = $myrow["sr_date"];
        $sr_cart->memo_  = $myrow["comments"];
        $sr_cart->movement_type_name = $myrow["movement_type_name"];
        $sr_cart->linked_field_type = $myrow["linked_field_type"];
        $sr_cart->linked_field_id  = $myrow["linked_field_id"];
        $sr_cart->requestor_name  = $myrow["requestor_name"];
        $sr_cart->created_on  = $myrow["created_on"];
        $sr_cart->mtr_complete  = $myrow["sr_complete"];
        $sr_cart->project_id  = $myrow["project_id"];
        $sr_cart->project_description  = $myrow["project_description"];
        $sr_cart->row_state  = $myrow["row_state"];
        $sr_cart->reservation_location  = $myrow["reservation_location"];
  
        $sr_details = get_stock_reservation_details($sr_no);

        $element_no = 0;
        while ($srd_row = db_fetch($sr_details)) 
        {
            $sr_line = new line_item($srd_row["stock_id"], 0, $standard_cost=null, 
                    $srd_row["description"],sql2date($srd_row["releasing_date"]), $srd_row["line_comment"],
                    null, $srd_row["id"], $srd_row["released_qty"], $srd_row["reserved_qty"], 0, 0, null, 0,
                    null, null, null, null, null,$srd_row["reserved_unit"], $srd_row["reserved_unit_qty"], 
                    $srd_row["reserved_unit_conv_factor"]);
                    
            
            $sr_line->row_id = $srd_row["id"];
            $sr_line->stock_control_method = $srd_row["stock_control_method"];
            $sr_line->project_site_id = $srd_row["project_site_id"];
            $sr_line->line_ref = $sr_line->row_id;
            
            $sr_cart->line_items[$element_no] = $sr_line;
            $element_no++;
        }


}

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

function can_process()
{
	global $Refs;

    
    $total_qty = 0;
        
	foreach ($_SESSION['srr_items']->line_items as &$line_item){
        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;
        }
        $total_qty += $_POST[$line_item->row_id."_tran_qty"];

        if($line_item->requested_qty < $line_item->issued_qty + ($_POST[$line_item->row_id."_tran_qty"] * $line_item->convertion_factor))
        {
            display_error(_("Can not release more than the reserved quantity for item [".$line_item->stock_id."]."));
            set_focus($line_item->row_id."_qty");
            return false;
        }
    }
        
	if (!$Refs->is_valid($_POST['srr_reference'])) 
	{
		display_error( _("You must enter a reference."));
		set_focus('mio_reference');
		return false;
	}

    $ref_msg = reference_exists($_POST['srr_reference'], ST_STOCK_RELEASE);
    if($ref_msg)        
    {
            display_error( $ref_msg);
            set_focus('srr_reference');
            return false;
    }
 
	return true;
}

function add_lot_details()
{

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

    foreach ($_SESSION['srr_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['srr_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"];
        
        $line_item->convertion_factor = 1;
        get_convertion_factor2($line_item->stock_id, $_POST[$line_item->row_id."_tran_unit"], $line_item->convertion_factor);
        
        $line_item->quantity = $line_item->tran_qty * $line_item->convertion_factor;
        $item_info = get_item_edit_info($line_item->stock_id);

        $line_item->standard_cost = $item_info['standard_cost'];
        $line_item->line_comment = $_POST[$line_item->row_id."_line_comment"];
        $line_item->project_site_id = $_POST[$line_item->row_id."_project_site_id"];
        
        $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;
        }
    }
}

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

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


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

function save_srr()
{
    update_cart();
    
    if(!can_process()){
        return;
    }

    $asrr_msg = add_stock_reservation_release($_SESSION['srr_items']->line_items, $_POST['srr_reference'], 
                                                $_SESSION['srr_items']->reservation_location, $_SESSION['srr_items']->location, 
                                                $_SESSION['srr_items']->project_id, $_POST['srr_date'], $_POST['memo_'], 
                                                $_SESSION['srr_items']->order_id, $_SESSION['srr_items']->row_state);

    if($asrr_msg['success'] !== true){
        display_error($asrr_msg['message']);
    }
    else{
        //new_doc_date($_POST['mio_date']);
        //end_processing($trans_no);
        unset($_SESSION['srr_items']);
        meta_forward($_SERVER['PHP_SELF'], "AddedID=".$asrr_msg['tran_no']);
    }
    
}

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


if (isset($_POST['Process']))
{
    save_srr();
    
} 

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



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


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


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



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


//-----------------------------------------------------------------------------------------------
//$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['mio_items']))
//{
//	handle_new_order();
//}

if (isset($_GET['sr_no']) && $_GET['sr_no'] > 0) 
{
    if(!isset($_SESSION['srr_items']))
    {
        handle_new_order($_GET['sr_no']);
    }
    elseif($_GET['sr_no'] != $_SESSION['srr_items']->order_id)
    {
        handle_new_order($_GET['sr_no']);
    }
    else{
        handle_new_order($_GET['sr_no']);
    }
}
//-----------------------------------------------------------------------------------------------
start_form();

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

display_stock_reservation_release_header($_SESSION['srr_items']);

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

display_stock_reservation_release_items(_("Items to Release"), $_SESSION['srr_items']);
srr_options_controls();

end_outer_table(1, false);

submit_center_first('Update', _("Update"), '', null);
submit_center_last('Process', _("Create Store Release"), '', 'default');

end_form();
end_page();

?>
