<?php
/**********************************************************************
***********************************************************************/
//-------------------------------------------------------------------------------------------------------------
include_once($path_to_root . "/inventory/includes/db/adjustments_db.inc");
include_once($path_to_root . "/includes/common_functions.inc");
include_once($path_to_root . "/inventory/includes/db/lot_adjustments_db.inc");


//-------------------------------------------------------------------------------
function display_inventory_adjustment_request_header(&$order)
{
    global $Refs, $Ajax;
    
    div_start('header_tbl');
    start_outer_table(TABLESTYLE2, "width=70%"); // outer table
    table_section(1);
        if(isset($_POST['ref'])){
            $reference = $_POST['ref'];
        }
        else{
            if($order->trans_no > 0){
                $reference = $order->reference;
            }
            else{
                $reference = $Refs->get_next($order->trans_type);
            }
        }
        ref_row(_("Reference:"), 'ref', '', $reference);
        
        locations_list_row(_("Location:"), 'StockLocation', null);

        date_row(_("Date:"), 'AdjDate', '', true);        

    table_section(2, "33%");
      
        if($order->count_items() > 0){
            if(isset($_POST['project_id'])){
                $order->project_id = $_POST['project_id'];
            }
            else{
                $_POST['project_id'] = $order->project_id;
            }
            
            $job_ref = get_job_ref($order->project_id);
            $order->job_reference = $job_ref['description'];
            hidden("project_id", $order->project_id);       
            label_row(_("Project:"), $order->job_reference);
        }
        else{
            project_list_row(_("Project:"), 'project_id', $order->project_id,FALSE,TRUE);
        }
        
        if(list_updated('project_id') && $_POST['project_id'] != -1)
        {
            $job_ref = get_job_ref($_POST['project_id']);
            $order->job_reference = $job_ref['description'];
            label_row(_("Project:"), $order->job_reference);
        }
        
        

        

        if(count($order->line_items) > 0 && isset($order->sample_items)){
            $Ajax->activate('header_tbl');
            if($order->sample_items == 1){
                label_row(_("Sample Items:"), 'Yes');
            }
            else{
                label_row(_("Sample Items:"), 'No');
            }
        }
        else{
            $Ajax->activate('header_tbl');
            yesno_list_row(_("Sample Items:"), 'sample_items');
        }
    //	table_section(3, "33%");
    //
    //    if($_POST['Increase'] == 1){
    //        movement_types_list_row(_("Type:"), 'type', ST_INVENTORY_RECEIPT, null);
    //    }
    //    else{
    //        movement_types_list_row(_("Type:"), 'type', ST_INVENTORY_ISSUE, null);
    //    }
    
    table_section(3, "33%");
    
        if(isset($_POST['movement_type'])){
            $order->movement_type = $_POST['movement_type'];
        }
        else{
            //$order->movement_type = '';
        }

        $movement_trans_type = 0;
        if($order->trans_type == ST_INVENTORY_RECEIPT_REQUEST){
            $movement_trans_type = ST_INVENTORY_RECEIPT;
        }
        elseif($order->trans_type == ST_INVENTORY_ISSUE_REQUEST){
            $movement_trans_type = ST_INVENTORY_ISSUE;
        }
        movement_types_list_row(_("Type:"), 'movement_type', $movement_trans_type, $order->movement_type , '', true);
        
        if(!isset($_POST['linked_field_id'])){
            $_POST['linked_field_id'] = $order->movement_type;
        }
        
        $movement_type = get_movement_type($_POST['movement_type']);
        switch ($movement_type['linked_field']) {
            case IMLF_CUSTOMER:
                customer_list_row(_("Customer:"), 'linked_field_id', null);
                break;
            case IMLF_SUPPLIER:
                supplier_list_row(_("Supplier:"), 'linked_field_id', null);
                break;
            case IMLF_EMPLOYEE:
                employees_simple_list_row("Employee", 'linked_field_id', null);
                break;
            default:
                hidden('linked_field_id', 0);
                break;
        }

        hidden('linked_field_type', $movement_type['linked_field']);

        hidden('Increase', $_POST['Increase']);
    end_outer_table(1); // outer table
}

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

function display_inventory_adjustment_request_items($title, &$order)
{
	global $path_to_root;

	display_heading($title);
        div_start('items_table');
	start_table(TABLESTYLE, "width=100%");
	$th = array(_("Item Code"), _("Item Description"), _("Unit"),
		_("Quantity"), _("Unit Cost"), _("Budget"), _("Job"), _("Total"), "");
	if ( count($order->line_items)) $th[] = '';

	table_header($th);
	$total = 0;
	$k = 0;  //row colour counter

	$id = find_submit('Edit');
	foreach ($order->line_items as $line_no=>$stock_item)
	{

		$total += ($stock_item->standard_cost * ($stock_item->tran_qty * $stock_item->convertion_factor));

		if ($id != $line_no)
		{
    		alt_table_row_color($k);

			view_stock_status_cell($stock_item->stock_id);
			label_cell($stock_item->item_description);
            label_cell($stock_item->alternate_unit_name);
            qty_cell($stock_item->tran_qty, false, get_qty_dec($stock_item->stock_id));
			amount_decimal_cell($stock_item->standard_cost);
            label_cell($stock_item->task_description);
            label_cell($stock_item->project_site_description);
			amount_cell($stock_item->standard_cost * ($stock_item->tran_qty * $stock_item->convertion_factor));

			edit_button_cell("Edit$line_no", _("Edit"),
				_('Edit document line'));
			delete_button_cell("Delete$line_no", _("Delete"),
				_('Remove line from document'));
			end_row();
		}
		else
		{
			inventory_adjustment_request_edit_item_controls($order, $line_no);
		}
	}

	if ($id == -1)
		inventory_adjustment_request_edit_item_controls($order);

	label_row(_("Total"), number_format2($total,user_price_dec()), "align=right colspan=5", "align=right", 2);

    end_table();
	div_end();
}

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

function inventory_adjustment_request_edit_item_controls(&$order, $line_no=-1)
{
	global $Ajax;
	start_row();

	$dec2 = 0;
	$id = find_submit('Edit');
	if ($line_no != -1 && $line_no == $id)
	{
		$_POST['stock_id'] = $order->line_items[$id]->stock_id;
		$_POST['qty'] = qty_format($order->line_items[$id]->quantity, $order->line_items[$id]->stock_id, $dec);
		$_POST['tran_qty'] = qty_format($order->line_items[$id]->tran_qty, $order->line_items[$id]->stock_id, $dec);
		$_POST['std_cost'] = price_decimal_format($order->line_items[$id]->standard_cost, $dec2);
		$_POST['units'] = $order->line_items[$id]->units;
                $_SESSION['lot_detail_line'] = $order->line_items[$id]->lot_details;
                $_POST['stock_control_method'] = $order->line_items[$id]->stock_control_method;
		hidden('stock_id', $_POST['stock_id']);
		label_cell($_POST['stock_id']);
		label_cell($order->line_items[$id]->item_description, 'nowrap');
	    $Ajax->activate('items_table');
	}
	else
	{
                stock_costable_items_list_cells(null, 'stock_id', null, false, true);
		if (list_updated('stock_id')) {
			    $Ajax->activate('units');
                $Ajax->activate('tran_unit');
                $Ajax->activate('tran_qty');
			    $Ajax->activate('qty');
			    $Ajax->activate('std_cost');
		}
        if (list_updated('tran_unit')) {
            $Ajax->activate('std_cost');
        } 
               
        $item_info = get_item_edit_info($_POST['stock_id']);
        $dec = $item_info['decimals'];
        $_POST['qty'] = number_format2(0, $dec);
        $_POST['std_cost'] = price_decimal_format($item_info["standard_cost"], $dec2);
        $_POST['units'] = $item_info["units"];
        $_POST['stock_control_method'] = $item_info["stock_control_method"];

        hidden('qty', $_POST['qty']);
        hidden('units', $_POST['units']);
            
    }
        
    if ($line_no != -1 && $line_no == $id){
        label_cell($order->line_items[$id]->alternate_unit_name);
        $unit_of_parent = $order->line_items[$id]->tran_unit;
    }
    else{
        units_list_cells(null, 'tran_unit', $_POST['stock_id'], null, false, true);
        $unit_of_parent = $_POST['tran_unit'];
    }
    
    if ($line_no != -1 && $line_no == $id){
        $line_ref = $order->line_items[$id]->line_ref;
        $tran_qty = $order->line_items[$id]->tran_qty;
    }
    else{
        $line_ref = $order->get_line_ref();
        $tran_qty = 0;
    }
    
    $cell_prefix = '';
    
    display_quantity_cells(get_post('guid'), $order->trans_type, $line_ref, $_POST['stock_id'], 
                            $_POST['stock_control_method'], $cell_prefix, $tran_qty, $unit_of_parent, 
                            $dec = 2, "items_table");
    
//    if($_POST['stock_control_method'] == SKCM_LOTS){
//        $Ajax->activate('items_table');
//        //$lot_popup = viewer_link('', 'inventory/manage/lot_list.php?stock_id='.$_POST['stock_id'].'&popup=1&parent=tran_qty', '', '',  ICON_VIEW);
//        $lot_popup = viewer_link('', 'inventory/manage/lot_list.php?value_ref='.get_post('guid').'&line_ref='.$order->get_line_ref().'&stock_id='.$_POST['stock_id'].'&popup=1&parent=tran_qty&unit_of_parent='.$unit_of_parent, '', '',  ICON_VIEW);
//        qty_cells(null, 'tran_qty', null, null, $lot_popup, $dec);
//    }
//    elseif($_POST['stock_control_method'] == SKCM_SERIAL_NOS){
//        $Ajax->activate('items_table');
//        //$lot_popup = viewer_link('', 'inventory/manage/lot_list.php?stock_id='.$_POST['stock_id'].'&popup=1&parent=tran_qty', '', '',  ICON_VIEW);
//        $lot_popup = viewer_link('', 'inventory/manage/serial_no_list.php?value_ref='.get_post('guid').'&stock_id='.$_POST['stock_id'].'&popup=1&parent=tran_qty&unit_of_parent='.$unit_of_parent, '', '',  ICON_VIEW);
//        qty_cells(null, 'tran_qty', null, null, $lot_popup, $dec);
//    }
//    else{
//        $Ajax->activate('items_table');
//        qty_cells(null, 'tran_qty', null, null, null, $dec);
//    }
//        
//        if ($line_no != -1 && $line_no == $id)
//        {
//            label_cell($order->line_items[$id]->alternate_unit_name);
//        }
//        else{
//            units_list_cells(null, 'tran_unit', $_POST['stock_id'], null, false, true);
//        }
    
    //amount_cells(null, 'std_cost', null, null, null, $dec2);
    amount_decimal_cell(input_num('std_cost'));
    
    tasks_list_cells(null, 'task_id', $_POST['project_id'], null, _('Select a budget'));
    project_sites_list_cells(null, 'project_site_id', $_POST['project_id'], null,'');
    
	label_cell("&nbsp;");

	if ($id != -1)
	{
		button_cell('UpdateItem', _("Update"),
				_('Confirm changes'), ICON_UPDATE);
		button_cell('CancelItemChanges', _("Cancel"),
				_('Cancel changes'), ICON_CANCEL);
		hidden('LineNo', $line_no);
        hidden('line_ref', $order->get_line_ref());
 		set_focus('qty');
	}
	else
	{
		submit_cells('AddItem', _("Add Item"), "colspan=2",
		    _('Add new item to document'), true);
        hidden('line_ref', $order->get_line_ref());
	}

	end_row();
}

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

function adjustment_request_options_controls($adj)
{
        echo "<br>";
        start_table();

        if(isset($_POST['memo_'])){
            $memo = $_POST['memo_'];
        }
        else{
            $memo = $adj->comment;
        }
        
        textarea_row(_("Memo"), 'memo_', $memo, 50, 3);

        end_table(1);
}

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


function can_commit_inventory_adjustment_request($order_name)
{
    global $Refs;

    $adj = &$_SESSION[$order_name];
    
    if($_SESSION[$order_name]->trans_no > 0){
        $sah = get_stock_adjustment_request_header($_SESSION[$order_name]->trans_no);
        if(!($sah['approval_status'] == AS_NEW || $sah['approval_status'] == AS_WITH_THE_APPROVER || $sah['approval_status'] == AS_AWAITING_APPROVAL || $sah['approval_status'] == AS_BACK_TO_ORIGINATOR)){
            $message = ("This Inventory Adjustment Request status does not allow further updating.");
            return array("success" => false, "focus_to" => '', "message" => $message);
        }
        
        $current_user_id = $_SESSION['wa_current_user']->user;
        $ced_msg = can_edit_document($sah['type'], $sah['project_id'], $sah['next_approval_group_id'] , $current_user_id, $sah['created_by'], $_SESSION[$order_name]->trans_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
        
    }

    if (count($adj->line_items) == 0){
            $message = (_("You must enter at least one non empty item line."));
            $focus = ('stock_id');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    if ($_POST['project_id'] == -1){
            $input_error = 1;
            $message = ( _('Select a project.'));
            $focus = ('project_id');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
    }

    if (!$Refs->is_valid($_POST['ref'])){
            $message = ( _("You must enter a reference."));
            $focus = ('ref');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
    }

        
    $ref_msg = reference_exists($_POST['ref'], $_SESSION['movement_type'], $adj->trans_no);
    if($ref_msg){
        $message = ( $ref_msg);
        $focus = ('ref');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }

    if (!($_POST['movement_type'] > 0)){
            $input_error = 1;
            $message = ( _('Select a movement type.'));
            $focus = ('movement_type');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
        
    $movement_type = get_movement_type($_POST['movement_type']);
    if($movement_type['linked_field'] > 0){
        if(!($_POST['linked_field_id'] > 0)){
            switch ($movement_type['linked_field']) {
                case IMLF_CUSTOMER:
                    $message = "Please select a customer";
                    break;
                case IMLF_SUPPLIER:
                    $message = "Please select a suppler";
                    break;
                case IMLF_EMPLOYEE:
                    $message = "Please select an employee";
                    break;
            }
        
            $input_error = 1;
            $focus = ('linked_field_id');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
        }
    }
        
        
    if (!is_date($_POST['AdjDate'])){
            $message = (_("The entered date for the adjustment is invalid."));
            $focus = ('AdjDate');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
    }elseif (!is_date_in_fiscalyear($_POST['AdjDate'])){
            $message = (_("The entered date is not in fiscal year."));
            $focus = ('AdjDate');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
    } else {
            $failed_item = $adj->check_qoh($_POST['StockLocation'], $_POST['AdjDate'], !$_POST['Increase']);
            if ($failed_item >= 0){
                    $line = $adj->line_items[$failed_item];
            $message = (_("The adjustment cannot be processed because an adjustment item would cause a negative inventory balance :") .
                    " " . $line->stock_id . " - " .  $line->item_description);
                    $_POST['Edit'.$failed_item] = 1; // enter edit mode
                    unset($_POST['Process']);
            return array("success" => false, "focus_to" => $focus, "message" => $message);
            }
    }

    
    $vtqd_msg = validate_transaction_quantity_details($adj);
    if ($vtqd_msg['success'] !== true){
        $message = ($vtqd_msg['message']);
        $focus = "";
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
	return array("success" => true);
}


function save_inventory_adjustment_request($items, $location, $date_, $increase, $reference, $memo, $movement_type, $project_id, $task_id, 
                                          $sample_item, $tran_type, $linked_field_type = 0, $linked_field_id = '', $trans_no=0,
                                          $project_site_id=0, $next_approval_group_id, $row_state, $release = false)
{
    global $loc_notification, $path_to_root, $Refs, $systypes_array;
    
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    begin_transaction();
    $args = func_get_args();
    $args = (object)array_combine(array('items', 'location', 'date_', 'increase', 'reference', 'memo', 'movement_type', 'project_id', 
                                        'task_id', 'sample_item', 'tran_type', 'linked_field_type', 'linked_field_id',
                                        'trans_no', 'project_site_id', 'next_approval_group_id', '$row_state', 'release'), $args);

    if($trans_no > 0){
        $adj_no = update_inventory_adjustment_request_header($trans_no, $date_, $reference, $location, $project_id, $increase, $tran_type, 
                                   $memo, $movement_type, $sample_item, $linked_field_type, $linked_field_id);
    }else{
        $adj_no = add_inventory_adjustment_request_header($date_, $reference, $location, $project_id, $increase, $tran_type, $memo, 
                                $movement_type, $sample_item, $linked_field_type, $linked_field_id);
        
        $Refs->save($tran_type, $adj_no, $reference);
    }  
    

    if(!($adj_no > 0)){
        cancel_transaction();
        return array("success" => false, "message" => "Could not save inventory adjustment request.");
    }
        
        delete_stock_adjustment_request_details($adj_no);
        foreach ($items as $line_item){
            if ($loc_notification == 1 && !$increase){
                    $loc = calculate_reorder_level($location, $line_item, $st_ids, $st_names, $st_num, $st_reorder); 
            }
//            if (!$increase){
//                    $line_item->quantity = -$line_item->quantity;
//            }
            if($tran_type == ST_INVENTORY_RECEIPT_REQUEST || $tran_type == ST_INVENTORY_RECEIPT_REQUEST){
                $standard_cost = get_standard_cost($line_item->stock_id);
            }
            else{
                // Get the user entered new cost
                $standard_cost = $line_item->standard_cost;
            }
            
            save_stock_adjustment_request_detail($line_item->row_id, $adj_no, $line_item->stock_id, $location, $date_, $reference, $line_item->quantity, 
                                                $standard_cost, $line_item->tran_unit, $line_item->tran_qty, 
                                                $line_item->convertion_factor, $tran_type, $line_item->task_id, $line_item->project_site_id,
                                                $line_item->created_by, $line_item->created_on);       
                           
        }
    
    
    
//	add_comments($tran_type, $adj_no, $date_, $memo_);
        
        
        if(!($release == true)){
            commit_transaction();
            return array("success" => true, "message" => $systypes_array[$tran_type]." #".$adj_no." has beeen saved.", "tran_no" => $adj_no);
        }
        
//            if($pr_complete == 1){
//                $tasks_summary = $total;
//            }
//            else{
//                $tasks_summary = calculate_pr_task_remaining_totals($items);
//            }  
        
        $tasks_summary = 0;  
        foreach ($items as $line_item){
            $tasks_summary += $line_item->standard_cost * $line_item->quantity;
        }
        
        
//        $row_state = db_new_row_state($row_state);

            $info = approve_document($tran_type, $adj_no, $project_id, $tasks_summary, 
                                     $next_approval_group_id, $current_user_id, $row_state);

            if($info['success'] !== true){
                cancel_transaction();
                return array("success" => $info['success'], "message" => $info['message']);
            }

            
            commit_transaction();
            return array("success" => true, "tran_no" => $trans_no, "message" => $info['message']);
    
}

function commit_stock_adjustment_request($order_name)
{
    	$asa_msg = save_inventory_adjustment_request($_SESSION[$order_name]->line_items, $_POST['StockLocation'], $_POST['AdjDate'], $_POST['Increase'],
                                                    $_POST['ref'], $_POST['memo_'], $_POST['movement_type'], $_POST['project_id'], $_POST['task_id'], 
                                                    $_SESSION[$order_name]->sample_items, $_SESSION[$order_name]->trans_type, $_POST['linked_field_type'], 
                                                    $_POST['linked_field_id'], $_SESSION[$order_name]->trans_no, $_POST['project_site_id'],
                                                    $_SESSION[$order_name]->next_approval_group_id, $_SESSION[$order_name]->row_state,  false);
        
    if($asa_msg['success'] !== true){
        display_error($asa_msg['message']);  
    }
    else{
        $trans_no = $asa_msg['tran_no'];
        if($_SESSION[$order_name]->trans_type == ST_INVENTORY_RECEIPT_REQUEST){
            $positive = 1;
        }
        elseif($_SESSION[$order_name]->trans_type == ST_INVENTORY_ISSUE_REQUEST){
            $positive = 0;
        }
        new_doc_date($_POST['AdjDate']);
        $_SESSION[$order_name]->clear_items();
        unset($_SESSION[$order_name]);

        set_session_variable('ST_INV_ADJ_REQ_messages', $asa_msg['message']);
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
}

function save_stock_adjustment_request_detail($row_id=null, $adj_no, $stock_id, $location, $date_, $reference, $quantity, 
                                             $standard_cost, $tran_unit, $tran_qty, 
                                             $convertion_factor, $tran_type, $task_id, $project_site_id, 
                                             $created_by=0, $created_on='0000-00-00 00:00:00')
{
    $mb_flag = get_mb_flag($stock_id);

    if (is_service($mb_flag)){
    	display_db_error("Cannot do inventory adjustment for Service item : $stock_id", "");
    }
    
       
    if(isset($row_id) && $row_id > 0){
        $trans_id = add_existing_stock_adjustment_request_details($row_id, $tran_type, $stock_id, $adj_no, $location,
                                                                  $date_, $reference, $quantity, $standard_cost, null, null, null, null,  
                                                                  $tran_unit, $tran_qty, $convertion_factor, $task_id, $project_site_id, 
                                                                  $created_by, $created_on);
    }else{
            add_stock_adjustment_request_detail($tran_type, $stock_id, $adj_no, $location,
                                                 $date_, $reference, $quantity, $standard_cost, null, null, null, null,  
                                                 $tran_unit, $tran_qty, $convertion_factor, $task_id, $project_site_id);
    }

}

function release_inventory_adjustment_request_for_approval($order_name)
{
    $asa_msg = save_inventory_adjustment_request($_SESSION[$order_name]->line_items, $_POST['StockLocation'], $_POST['AdjDate'], $_POST['Increase'],
                                                $_POST['ref'], $_POST['memo_'], $_POST['movement_type'], $_POST['project_id'], $_POST['task_id'], 
                                                $_SESSION[$order_name]->sample_items, $_SESSION[$order_name]->trans_type, $_POST['linked_field_type'], 
                                                $_POST['linked_field_id'], $_SESSION[$order_name]->trans_no, $_POST['project_site_id'], 
                                                $_SESSION[$order_name]->next_approval_group_id, $_SESSION[$order_name]->row_state, true);

    if($asa_msg['success'] !== true){
        display_error($asa_msg['message']);  
    }
    else{
        $trans_no = $asa_msg['tran_no'];
        if($_SESSION[$order_name]->trans_type == ST_INVENTORY_RECEIPT_REQUEST){
            $positive = 1;
        }
        elseif($_SESSION[$order_name]->trans_type == ST_INVENTORY_ISSUE_REQUEST){
            $positive = 0;
        }
        new_doc_date($_POST['AdjDate']);
        $_SESSION[$order_name]->clear_items();
        unset($_SESSION[$order_name]);

        set_session_variable('ST_INV_ADJ_REQ_messages', $asa_msg['message']);
        meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    }
}

function send_inventory_adjustment_request_back_to_originator($trans_no)
{        
    begin_transaction();
     
    $sarh = get_stock_adjustment_request_header($trans_no);
    $current_user_id = $_SESSION['wa_current_user']->user;

    $sbdo_msg = send_back_to_document_originator($sarh['type'], $trans_no, $sarh['project_id'],
                                                 $sarh['next_approval_group_id'], $current_user_id, $sarh['row_state'], 
                                                 $sarh['created_by']);
    
    if($sbdo_msg['success'] !== true){
        display_error_cancel($sbdo_msg['message']);
        return;
    }

    commit_transaction();
    set_session_variable('ST_INV_ADJ_REQ_messages', $sbdo_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
        
}


function reject_inventory_adjustment_request($trans_no)
{
    begin_transaction();
    $sarh = get_stock_adjustment_request_header($trans_no);
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $rj_msg = reject_document($sarh['type'], $trans_no, $sarh['project_id'],
                              $sarh['next_approval_group_id'], $current_user_id, $sarh['row_state']);
    
    if($rj_msg['success'] !== true){
        display_error_cancel($rj_msg['message']);
        return;
    }

    commit_transaction();
    set_session_variable('ST_INV_ADJ_REQ_messages', $rj_msg['message']);
    meta_forward($_SERVER['PHP_SELF'], "AddedID=$trans_no");
    

}


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

function line_start_focus() {
  global 	$Ajax;

  $Ajax->activate('items_table');
  set_focus('_stock_id_edit');
}
//-----------------------------------------------------------------------------------------------

function handle_new_order($order_name)
{
	if (isset($_SESSION[$order_name])){
            $_SESSION[$order_name]->clear_items();
            unset ($_SESSION[$order_name]);
	}

        $_SESSION[$order_name] = new items_cart($_SESSION['movement_type']);
	$_POST['AdjDate'] = new_doc_date();
	if (!is_date_in_fiscalyear($_POST['AdjDate']))
		$_POST['AdjDate'] = end_fiscalyear();
	$_SESSION[$order_name]->tran_date = $_POST['AdjDate'];	
}

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

function handle_load_existing_order($order_name, $order_no)
{
	if (isset($_SESSION[$order_name])){
            unset($_SESSION[$order_name]);
//            $_SESSION[$order_name]->clear_items();
            unset ($_SESSION[$order_name]);
	}

         $test = new items_cart($_SESSION['movement_type'], $order_no);
         $_SESSION[$order_name] = $test;
        
        if(!is_date(sql2date($_SESSION[$order_name]->tran_date))){
            $_POST['AdjDate'] = new_doc_date();
            if (!is_date_in_fiscalyear($_POST['AdjDate']))
                    $_POST['AdjDate'] = end_fiscalyear();
            $_SESSION[$order_name]->tran_date = $_POST['AdjDate'];	
        }
}


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

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

function check_item_data(&$order)
{
    
    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 (!check_num('std_cost', 0.01))
//	{
//		display_error(_("The entered standard cost must be positive."));
//		set_focus('std_cost');
//		return false;
//	}

    if ($_POST['task_id'] <= 0 ){
		display_error(_("Please select a budget."));
		set_focus('task_id');
		return false;
	}
   	return true;
}

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

function handle_update_item($order_name)
{
    //if($_POST['UpdateItem'] != "" && check_item_data($_SESSION[$order_name]))
    
    if(!check_item_data($_SESSION[$order_name])){
        $_POST['Edit'.get_post('LineNo')] = 1;
        return;
    }
 

    $inv_adj = &$_SESSION[$order_name];
    $id = $_POST['LineNo'];
    $convertion_factor = $inv_adj->line_items[$id]->convertion_factor;
    $inv_adj->update_cart_item($id, input_num('tran_qty')*$convertion_factor, 
        input_num('std_cost'), null, null, null, null, null, input_num('tran_qty'));

    $lot_details = get_selected_lot_serial_info('guid', $inv_adj->line_items[$id]); 

    $inv_adj->line_items[$id]->lot_details = $lot_details;

    $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'];
    }
    $inv_adj->line_items[$id]->task_id = $task_id;
    $inv_adj->line_items[$id]->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'];
    }
    $inv_adj->line_items[$id]->project_site_id = $project_site_id;
    $inv_adj->line_items[$id]->project_site_description = $project_site_description;
    
    
	line_start_focus();
}

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

function handle_delete_item($order_name,$id)
{
	$_SESSION[$order_name]->remove_from_cart($id);
	line_start_focus();
}

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

function handle_new_item($order_name)
{
    if (!check_item_data($_SESSION[$order_name])){
		return;
    }
        
    $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_to_order($_SESSION[$order_name], $_POST['stock_id'], input_num('qty'), input_num('std_cost'), 
                     $_POST['tran_unit'], input_num('tran_qty'), $convertion_factor);
    
    $adj = &$_SESSION[$order_name];
        
    $current_element = (count($adj->line_items)-1);
//    $adj->line_items[$current_element]->requested_qty = $_POST['qty'];
    $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"];
    $adj->line_items[$current_element]->stock_control_method = $item_info["stock_control_method"];
    $adj->line_items[$current_element]->stock_control_method = $item_info["stock_control_method"];
    
    //$adj->line_items[$current_element]->line_ref = 
    set_line_ref($adj, $current_element);
    $lot_details = get_selected_lot_serial_info('guid', $adj->line_items[$current_element]); 
    
    if(isset($lot_details) && $lot_details != ""){
        $adj->line_items[$current_element]->lot_details = $lot_details;    
    }
    
    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();
    
}

function display_inventory_adjustment_request_cost_update_message($adjustment_type, $project_id)
{
    if(!($project_id > 0)){
        return;
    }
    
    $m = '';
    
    $project = get_project_record($project_id);
    if($adjustment_type == ST_INVENTORY_RECEIPT_REQUEST){
        $m = "This is a positive adjustment request and it will increase stock quantities. \r\n";
        if($project['purchase_to_stock']){ 
            $m .= "Selected project is a stock project (Purchase To Stock = Yes). \r\n";
            $m .= "<font color='red'>Costs will be <b>added</b> to the project budgets</font> as it is adding stock to a stock project. \r\n";
        }
        else{
            $m .= "Selected project is a consumption project (Purchase To Stock = No). \r\n";
            $m .= "Increase in the stock quantities means returning the already consumed items from the project back to stock. \r\n";
            $m .= "So the <font color='red'>costs will be <b>deducted</b> in the project budgets</font>. \r\n";
        }
    }
    elseif($adjustment_type == ST_INVENTORY_ISSUE_REQUEST){
        $m = "This is a negative adjustment request and it will decrease stock quantities. \r\n";
        if($project['purchase_to_stock']){ 
            $m .= "Selected project is a stock project (Purchase To Stock = Yes). \r\n";
            $m .= "<font color='red'>Costs will be <b>deducted</b> from the project budgets</font> as it is decreasing stock in a stock project. \r\n";
        }
        else{
            $m .= "Selected project is a consumption project (Purchase To Stock = No). \r\n";
            $m .= "Decrease in the stock quantities means issuing items to the project for consumption. \r\n";
            $m .= "So the <font color='red'>costs will be <b>added</b> to the project budgets</font>. \r\n";
        }
    }
    
    start_outer_table(TABLESTYLE_NOBORDER, "width=45%");
    echo nl2br($m);
    end_table();
}           
            
?>