<?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, $msgss=null){
    global $Refs, $Ajax, $approval_statuses;
    
    div_start('header_tbl');
    display_heading($msgss);
    br();
    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);
        
        if(!(isset($_POST['StockLocation']) && strlen($_POST['StockLocation']) > 0)){
            $_POST['StockLocation'] = $order->location_name;
        }
        locations_list_row(_("Location:"), 'StockLocation', null, "Select a location");

        if(is_date($order->tran_date)){
            $_POST['AdjDate'] = $order->tran_date;
        }
        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{
            if (! isset($_POST['project_id']) && $order->project_id > 0) {
                $_POST['project_id'] = $order->project_id;
            }
            project_list_row(_("Project:"), 'project_id', null, 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');
            }
            hidden("sample_items", $order->sample_items);
        }else{
            $Ajax->activate('header_tbl');
            yesno_list_row(_("Sample Items:"), 'sample_items');
        }
        
        
    
    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(_("Movement Type:"), 'movement_type', $movement_trans_type, $order->movement_type , '', true);
        
        if(!isset($_POST['linked_field_id'])){
            $_POST['linked_field_id'] = $order->linked_field_id;
        }
        
        $movement_type = get_movement_type($_POST['movement_type']);
        
        if (list_updated('movement_type')) {
            unset($_POST['linked_field_id']);
        }
            
        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;
            case IMLF_VEHICLE:
                vehicles_list_row('Vehicle:', 'linked_field_id', null, '', true);
                break;
            case IMLF_ASSET:
                label_row(_("Asset:"), asset_list('linked_field_id', null, ''));
                break;
            default:
                hidden('linked_field_id', 0);
                break;
        }

        if($order->trans_no > 0){
            $s = get_project_trans_view_str(98, $order->trans_no."&source_type_id=".$order->trans_type, "Approval Status");
                 label_row($s, $approval_statuses[$order->approval_status]);
        }
            
        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){
    
    $id = find_submit('Edit');
    if(list_updated("tran_unit")){
        if(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] !== $id){
            if(!($id > 0)){
                hidden("Edit".$_POST['previous_selected_id'], $_POST['previous_selected_id']);
                $id = $_POST['previous_selected_id'];
                hidden("Edit$id", $id);
                $_POST["Edit$id"] = $line_no = $id;
            }
        }
    }
        
    global $path_to_root;

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

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

            $id = find_submit('Edit');
            
            if (is_array($order->line_items)) {
                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);
                            label_cell($stock_item->row_id, "align=center");
                            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));
                            qty_cell($stock_item->standard_cost, false, 2);
                            label_cell($stock_item->task_description);
                            label_cell($stock_item->project_site_description);
                            qty_cell($stock_item->standard_cost * ($stock_item->tran_qty * $stock_item->convertion_factor), false, 2);

                            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=8", "align=right", 2);

        end_table();
    div_end();
}

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

function inventory_adjustment_request_edit_item_controls(&$order, $line_no=-1){
    global $Ajax;
    start_row();
    
        $id = find_submit('Edit');
        
        if(list_updated("tran_unit")){
            if(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] !== $id){
                if(!($id > 0)){
                    hidden("Edit".$_POST['previous_selected_id'], $_POST['previous_selected_id']);
                    $id = $_POST['previous_selected_id'];
                    hidden("Edit$id", $id);
                    $_POST["Edit$id"] = $line_no = $id;
                }
            }
        }
	$dec2 = 0;
	
	if($line_no != -1 && $line_no == $id){
            label_cell($order->line_items[$id]->row_id , "align=center");
            $_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);
            
            if(!list_updated("tran_unit")){
                $_POST['units'] = $order->line_items[$id]->units;
            }
            $_POST['task_id'] = $order->line_items[$id]->task_id;
            $_POST['project_site_id'] = $order->line_items[$id]->project_site_id;
            $_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{
            label_cell("");
            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){
            $original_unit = $order->line_items[$id]->tran_unit;
            if(isset($_POST['previous_selected_id']) && $_POST['previous_selected_id'] != $id){
                $_POST['tran_unit'] = $original_unit;
            }
            units_list_cells(null, 'tran_unit', $_POST['stock_id'], null, false, true);
        }else{
            units_list_cells(null, 'tran_unit', $_POST['stock_id'], null, false, true);
            $original_unit = $_POST['tran_unit'];
        }
        

        hidden("previous_selected_id", $id);
        
        

        $tran_unit = $_POST['tran_unit'];
        $convesion_factor = 1;
        get_convertion_factor2($_POST['stock_id'], $tran_unit, $convesion_factor);
        $_POST['tran_unit'] = $tran_unit;
        hidden("convesion_factor", $convesion_factor);

        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, 
                               $original_unit, $dec = 2, "items_table");

        $tran_unit_std_cost = input_num('std_cost') * $convesion_factor;
//        amount_cell($tran_unit_std_cost, "", null, 2);
        amount_cell($tran_unit_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_header(&$adj, $save_header_only=false){
    global $Refs;
    
    if($adj->trans_no > 0){
        $sah = get_stock_adjustment_request_header($adj->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'], $adj->trans_no);
        if($ced_msg['success'] !== true){
            return array("success" => false, "focus_to" => '', "message" => $ced_msg['message']);
        }
    }

//    if($_SESSION[$order_name]->trans_no > 0){
//        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(!$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(!(strlen($_POST['StockLocation']) > 0 || $_POST['StockLocation'] != "")){
        $input_error = 1;
        $message = ( _('Select a location.'));
        $focus = ('StockLocation');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    if(!($_POST['project_id'] > 0)){
        $input_error = 1;
        $message = ( _('Select a project.'));
        $focus = ('project_id');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
//    $project = get_project_record($_POST['project_id']);
//    if($project['purchase_to_stock'] == false){
//        $input_error = 1;
//        $message = ( _('Selected project has to be a stock project [Purchase to Stock = Yes].'));
//        $focus = ('project_id');
//        return array("success" => false, "focus_to" => $focus, "message" => $message);
//    }
    
    if (! ($_POST['movement_type'] > 0)) {
        $message =  _('Select a movement type.');
                    
        return array("success" => false, "focus_to" => 'movement_type', "message" => $message);
    } 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) {
                            $message = _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.');                    
                            return array("success" => false, "focus_to" => 'linked_field_id', "message" => $message);
                        }   
                        break;                     
                    case IMLF_ASSET:
                        if (! ($_POST['linked_field_id'] > 0)) {
                            $message = _('Select an '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.');                    
                            return array("success" => false, "focus_to" => 'linked_field_id', "message" => $message);
                        }   
                        break;   
                    default:
                        if (! ($_POST['linked_field_id'] > 0)) {
                            $message =  _('Select a '.$inventory_movement_type_linked_fields[$mv_tp['linked_field']].'.');                    
                            return array("success" => false, "focus_to" => 'linked_field_id', "message" => $message);
                        }   
                        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.';
                            return array("success" => false, "focus_to" => 'linked_field_id', "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);
        }
    }

    if (count($adj->line_items) == 0 && $save_header_only === true) {
        $message = _("You must enter at least one non empty item line.");
        return array("success" => false, "focus_to" => 'stock_id', "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_header($location, $date_, $increase, $reference, $memo, $movement_type, $project_id, $sample_item, $tran_type, 
                                           $linked_field_type = 0, $linked_field_id = '', $trans_no=0, $row_state=0)
{
    
    global $Refs;
       
    if($trans_no > 0){
        $msg = 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, $row_state);
        return $msg;

    }else{
        $msg = add_inventory_adjustment_request_header($date_, $reference, $location, $project_id, $increase, $tran_type, $memo, $movement_type, $sample_item, 
                                                       $linked_field_type, $linked_field_id);
        if($msg['success'] !== true){
            return $msg;
        }else{
            $adj_no = $msg['trans_no'];
        }

        $Refs->save($tran_type, $adj_no, $reference);
        return array("success" => true, "message" => "", "trans_no" => $msg['trans_no']);
    }
  
}








//        $tasks_summary = 0;  
//        foreach ($items as $line_item){
//            $tasks_summary += $line_item->standard_cost * $line_item->quantity;
//        }
//        $info = approve_document($tran_type, $adj_no, $project_id, $tasks_summary, $next_approval_group_id, $current_user_id, db_new_row_state($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($adj_req, $curr_id){
    
    $reference = $_POST['ref'];
    $date_ = $_POST['AdjDate'];
    $location = $_POST['StockLocation'];
    
    $item = $adj_req->line_items[$curr_id];    
    $mb_flag = get_mb_flag($item->stock_id);
    if(is_service($mb_flag)){
        return array("success" => false, "trans_no"=> $adj_req->trans_no, "message" => "Cannot do inventory adjustment for Service item : $item->stock_id");
    }
    
    $asa_msg = save_inventory_adjustment_request_header($location, $date_, $_POST['Increase'], $reference, 
                                                 $_POST['memo_'], $_POST['movement_type'], $_POST['project_id'], $adj_req->sample_items, 
                                                 $adj_req->trans_type, $_POST['linked_field_type'], $_POST['linked_field_id'], $adj_req->trans_no, 
                                                 $adj_req->row_state,  false);
        
    if($asa_msg['success'] !== true){
        cancel_transaction();
        return $asa_msg; 
    }
    
    $adj_no = $asa_msg['trans_no'];
    
    $standard_cost = $item->standard_cost;

    $ssard_msg = save_stock_adjustment_request_detail($item->row_id, $adj_no, $item->stock_id, $location, $date_, $reference, $item->quantity, 
                                                        $standard_cost, $item->tran_unit, $item->tran_qty, $item->convertion_factor, $adj_req->trans_type, 
                                                        $item->task_id, $item->project_site_id, $item->created_by, $item->created_on); 

    if($ssard_msg['success'] !== true){
        cancel_transaction();
        return $ssard_msg;
    }
    

    return $ssard_msg;
    
}

function save_stock_adjustment_request_detail($row_id, $adj_no, $stock_id, $location, $date_, $reference, $quantity, $standard_cost, $tran_unit, $tran_qty, 
                                              $conversion_factor, $tran_type, $task_id, $project_site_id){
    

    if(isset($row_id) && $row_id > 0){
        return update_existing_stock_adjustment_request_details($row_id, $tran_type, $adj_no, $location, $date_, $reference, $quantity, $standard_cost, 
                                                                null, null, null, null, $tran_unit, $tran_qty, $conversion_factor, $task_id, $project_site_id);
    }else{
        return 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, $conversion_factor, $task_id, $project_site_id);
    }
    
}

function release_inventory_adjustment_request_for_approval($adj_req){
    
    $reference = $_POST['ref'];
    $date_ = $_POST['AdjDate'];
    $location = $_POST['StockLocation'];
    
    $asa_msg = save_inventory_adjustment_request_header($location, $date_, $_POST['Increase'], $reference, 
                                                 $_POST['memo_'], $_POST['movement_type'], $_POST['project_id'], $adj_req->sample_items, 
                                                 $adj_req->trans_type, $_POST['linked_field_type'], $_POST['linked_field_id'], $adj_req->trans_no, 
                                                 $adj_req->row_state,  false);

    if($asa_msg['success'] !== true){
        return $asa_msg;
    }
   
    $tasks_summary = 0;  
    foreach ($adj_req->line_items as $line_item){
        $tasks_summary += $line_item->standard_cost * $line_item->quantity;
    }
        
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $row_state = db_new_row_state($adj_req->row_state);

    $info = approve_document($adj_req->trans_type, $adj_req->trans_no, $_POST['project_id'], $tasks_summary, 
                             $adj_req->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();
    
    $trans_no = $adj_req->trans_no;
            
    return array("success" => true, "trans_no" => $trans_no, "message" => $info['message']);

}

function send_inventory_adjustment_request_back_to_originator($order_name){  
    
    $adj_req = &$_SESSION[$order_name];
    
    $reth = can_commit_inventory_adjustment_request_header($adj_req);
    if($reth["success"] !== true){
        display_error($reth["message"]);
        return false;
    }
    
    $trans_no = $adj_req->trans_no;
     
    $sarh = get_stock_adjustment_request_header($trans_no);
    $current_user_id = $_SESSION['wa_current_user']->user;

    begin_transaction();
    $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){
        cancel_transaction();
        display_error_cancel($sbdo_msg['message']);
        return;
    }

    commit_transaction();
    new_doc_date($_POST['AdjDate']);

    $adj_req->clear_items();
    unset($_SESSION[$order_name]);

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

function reject_inventory_adjustment_request($order_name){
    
    $adj_req = &$_SESSION[$order_name];
    
    $reth = can_commit_inventory_adjustment_request_header($adj_req);
    if($reth["success"] !== true){
        display_error($reth["message"]);
        return false;
    }
    
    $trans_no = $adj_req->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();
    new_doc_date($_POST['AdjDate']);

    $adj_req->clear_items();
    unset($_SESSION[$order_name]);
    
    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');
  
//    $id = $_POST['LineNo'];
//    unset($_POST['Edit'.$id]);
}

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

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(($_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 can_commit_inventory_adjustment_request_detail(&$order, $selected_id=-1){
    
    if(!(strlen($_POST['stock_id']) > 0 || $_POST['stock_id'] != "")){
        $message = ( _('Please select an item.'));
        $focus = ('stock_id');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    if($order->sample_items == true){
        $item = get_item($_POST['stock_id']);
        if($item['sample_item'] != 1){
            $message = (_("Selected item is not a sample item. This request can have sample items only."));
            $focus = ('stock_id');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
        }    
    }
    else{
        $item = get_item($_POST['stock_id']);
        if($item['sample_item'] != 0){
            $message = (_("Selected item is a sample item.. This request can not have any sample items."));
            $focus = ('stock_id');
            return array("success" => false, "focus_to" => $focus, "message" => $message);
        }    
    }
             

    if(!check_num('tran_qty',0.00001)){
        $message = (_("The quantity entered is negative or invalid."));
        $focus = ('tran_qty');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }

    if($_POST['task_id'] <= 0 ){
        $message = (_("Please select a budget."));
        $focus = ('task_id');
        return array("success" => false, "focus_to" => $focus, "message" => $message);
    }
    
    return array("success" => true, "focus_to" => '', "message" => '');
}

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

function handle_update_inventory_adjustment_request_header($order_name, $save_header_only=false){  
    
    $adj_req = &$_SESSION[$order_name];
    
    $reth = can_commit_inventory_adjustment_request_header($adj_req, $save_header_only);
    if($reth["success"] !== true){
        display_error($reth["message"]);
        return false;
    }
    
    copy_header_to_inventory_adjustment_request_cart_for_saving($adj_req);

    $reference = $_POST['ref'];
    $date_ = $_POST['AdjDate'];
    $location = $_POST['StockLocation'];
    
    $asa_msg = save_inventory_adjustment_request_header($location, $date_, $_POST['Increase'], $reference, 
                                                 $_POST['memo_'], $_POST['movement_type'], $_POST['project_id'], $adj_req->sample_items, 
                                                 $adj_req->trans_type, $_POST['linked_field_type'], $_POST['linked_field_id'], $adj_req->trans_no, 
                                                 $adj_req->row_state,  false);
    
    $order_no = $asa_msg["trans_no"];

    if($asa_msg['success'] !== true){
        display_error($asa_msg["message"]);
        return $order_no;
    }

    $msg = "Inventory Adjustment request ".$order_no." has been updated.";
    display_notification($msg);
    return $order_no;    
}

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

function handle_update_inventory_adjustment_request_item($order_name){  
    
    global $systypes_array;
    
    $inv_adj = &$_SESSION[$order_name];
    
    $reth = can_commit_inventory_adjustment_request_header($inv_adj);
    if($reth["success"] !== true){
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        display_error($reth["message"]);
        return false;
    }
    
    copy_header_to_inventory_adjustment_request_cart_for_saving($inv_adj);
    
    $id = $_POST['LineNo'];
    $retd = can_commit_inventory_adjustment_request_detail($inv_adj, $id);
    if($retd["success"] !== true){        
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        display_error($retd["message"]);
        return false;
    }
 
//    $id = $_POST['previous_selected_id'];
    $conversion_factor = input_num("convesion_factor");
    $standard_cost = get_standard_cost($_POST['stock_id']);
    $tran_unit_qty = input_num('tran_qty');
    $base_unit_qty = $tran_unit_qty*$conversion_factor;
    
    $inv_adj->update_cart_item($id, $base_unit_qty, $standard_cost, null, null, null, null, null, $tran_unit_qty, 
                               $_POST['tran_unit'], $conversion_factor);

    $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;

    $row_id = $inv_adj->line_items[$id]->row_id;
    
    begin_transaction();
    $csar_msg = commit_stock_adjustment_request($inv_adj, $id); 
    $order_no = $csar_msg["trans_no"];
    if($csar_msg["success"] !== true){
        cancel_transaction();
        display_error($csar_msg["message"]);
        return $order_no;
    }
    
    commit_transaction();
    
    $msg = "Line No $row_id has been updated in the ".$systypes_array[$inv_adj->trans_type]." ".$order_no;
    display_notification($msg);
    return $order_no;    
}

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

function handle_delete_inventory_adjustment_request_item($order_name, $id, $mv_type){
    
    $adj = &$_SESSION[$order_name];
    
    $row_id = $adj->line_items[$id]->row_id;
    
    $reth = can_commit_inventory_adjustment_request_header($adj);
    if($reth["success"] !== true){
        $id = find_submit('Delete');
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        return $reth;
    }
    
    $dsar_msg = delete_stock_adjustment_request_details_record($row_id, $mv_type);    
    if($dsar_msg['success'] !== true){
        display_error($dsar_msg['message']);
    }else{
        display_notification($dsar_msg['message']);
    }
}

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

function handle_new_inventory_adjustment_request_item($order_name){
    
    global $systypes_array;
    
    $adj = &$_SESSION[$order_name];
    
    $reth = can_commit_inventory_adjustment_request_header($adj);
    if($reth["success"] !== true){
        display_error($reth["message"]);
        return false;
    }
    
    copy_header_to_inventory_adjustment_request_cart_for_saving($adj);
    
    $id = find_submit('Edit');
    $retd = can_commit_inventory_adjustment_request_detail($adj, $id);
    if($retd["success"] !== true){        
        $_POST['Edit'.$id] = 1; // Stay in the editing line
        display_error($retd["message"]);
        return false;
    }
        
    $item_info = get_stock_item_edit_info($_POST['stock_id']);
    $alternate_unit = get_convertion_factor($_POST['tran_unit'], $_POST['stock_id']);
    $conversion_factor = $alternate_unit['convertion_factor'];    
        
    add_to_order($adj, $_POST['stock_id'], input_num('qty'), input_num('std_cost'), $_POST['tran_unit'], input_num('tran_qty'), $conversion_factor);
    
    $current_element = (count($adj->line_items)-1);
    $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"];

    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;

    begin_transaction();
    
    $csar_msg = commit_stock_adjustment_request($adj, $current_element); 
    $order_no = $csar_msg["trans_no"];
    if($csar_msg["success"] !== true){
        cancel_transaction();
        display_error($csar_msg["message"]);
        return $order_no;
    }
    
    commit_transaction();              
    
    $msg = "A new line has been added to ".$systypes_array[$adj->trans_type]." ".$order_no;
    display_notification($msg);
    return $order_no;   
}

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();
}

function add_to_order(&$order, $new_item, $new_item_qty, $standard_cost, $tran_unit, $tran_qty, $convertion_factor){
    $order->add_to_cart(count($order->line_items), $new_item, $new_item_qty, $standard_cost, null, null,null, 
                        null, 0, 0, 0, 0, 0, null, 0,null, null,null, null, null,$tran_unit, $tran_qty, $convertion_factor);
}

function copy_header_to_inventory_adjustment_request_cart_for_saving(&$cart){
    $cart->reference = $_POST['ref'];
    $cart->StockLocation =  $_POST['StockLocation'];
    $cart->AdjDate =  $_POST['AdjDate'];
    $cart->project_id =  $_POST['project_id'];
    $cart->sample_items =  $_POST['sample_items'];
    $cart->movement_type =  $_POST['movement_type'];
    $cart->linked_field_id =  $_POST['linked_field_id'];
    $cart->linked_field_type =  $_POST['linked_field_type'];
}


function handle_release_inventory_adjustment_request($order_name){
    
    $adj_req = &$_SESSION[$order_name];
    
    $reth = can_commit_inventory_adjustment_request_header($adj_req);
    if($reth["success"] !== true){
        display_error($reth["message"]);
        return false;
    }
    
    copy_header_to_inventory_adjustment_request_cart_for_saving($adj_req);

    begin_transaction();
    
    $riar_msg = release_inventory_adjustment_request_for_approval($adj_req);
    if($riar_msg["success"] !== true){
        cancel_transaction();
        display_error($riar_msg["message"]);
        return false;
    }
    
    commit_transaction();
    new_doc_date($_POST['AdjDate']);
    $trans_no = $riar_msg["trans_no"];
    $adj_req->clear_items();
    unset($_SESSION[$order_name]);

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



function handle_send_back_to_originator_inventory_adjustment_request($order_name){
    
    
    
    copy_header_to_inventory_adjustment_request_cart_for_saving($adj_req);

   
    $riar_msg = release_inventory_adjustment_request_for_approval($adj_req);
    if($riar_msg["success"] !== true){
        display_error($riar_msg["message"]);
        return false;
    }
    
    new_doc_date($_POST['AdjDate']);
    $trans_no = $riar_msg["trans_no"];
    $adj_req->clear_items();
    unset($_SESSION[$order_name]);

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


            
?>