<?php

function display_outside_material_receipt_header_details($omrc_no, $omrt_no) {
    global $approval_statuses, $systypes_array;
    
    $req_hd_row = get_outside_material_receipt_header($omrc_no);
    
        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($req_hd_row['project_id'], $user_id);
            if ($cap['success'] !== true) {
                display_error($cap["message"]);
                display_footer_exit();
                exit;
            }
    
    display_heading($systypes_array[ST_OUTSIDE_MATERIAL_RECEIPT]." Header");
    
        $receipt_trans_no = $req_hd_row['trans_no'];
        if (! isset($_POST['to_loc_code']) && ! ($omrt_no > 0)) {
            $_POST['to_loc_code'] = $req_hd_row['from_location'];
        }
        $_POST['from_location'] = $req_hd_row['to_loc_code'];
        hidden('from_location', $req_hd_row['to_loc_code']);
        $_POST['to_location_name'] = $req_hd_row['to_location_name'];
    
    start_outer_table(TABLESTYLE2, "width=65%"); // outer table
        start_table(TABLESTYLE2);  
            table_section(1, "27%");
                $jo_id = $req_hd_row['jo_id'];
                label_row("Receipt Trans #:", get_inventory_trans_view_str($req_hd_row['type'], $req_hd_row['trans_no']));  
                label_row("Job Card #:", get_service_trans_view_str(ST_JOB_ORDER, $jo_id));
                label_row("Requestor:", $req_hd_row['requestor_name']);  

            table_section(2, "45%");
                label_row("Reference:", $req_hd_row['reference']);  
                label_row("Project:", get_project_formatted_name($req_hd_row['project_id']));  
                label_row("Date:", sql2date($req_hd_row['tran_date']));  
                
            table_section(3, "27%");
                label_row("From Location:", $req_hd_row['from_location']);  
                label_row("To Location:", $req_hd_row['to_location_name']);  
                $s = get_project_trans_view_str(ST_APPROVAL_LOG, $receipt_trans_no."&source_type_id=".ST_OUTSIDE_MATERIAL_RECEIPT, "Approval Status");
                label_row($s, $approval_statuses[$req_hd_row['approval_status']]);

    end_outer_table(2); // outer table
    
    if (strlen($req_hd_row['comments']) > 0) {
        start_table(TABLESTYLE);
            label_row("Comment:", nl2br($req_hd_row['comments']));  
        end_table(2);
    }
    
    return $req_hd_row;
}

function display_outside_material_return_header($omrt_no, $req_hd_row) {
    global $Refs, $systypes_array;
    
    display_heading($systypes_array[ST_OUTSIDE_MATERIAL_RETURN]." Header");
    
        $type = ST_OUTSIDE_MATERIAL_RETURN;
        $trans_no = 0;
    
        $_POST['project_id'] = $req_hd_row['project_id'];
        hidden('project_id', $req_hd_row['project_id']);

        $user_id = $_SESSION['wa_current_user']->user;
        $cap = can_access_project($_POST['project_id'], $user_id);
            if ($cap['success'] !== true) {
                display_error($cap["message"]);
                set_focus('project_id');
                display_footer_exit();
                exit;
            }  
            
        $header = get_outside_material_receipt_header($omrt_no);

        if (is_array($header)) {
            
            $trans_no = $header['trans_no'];

            if (! isset($_POST['reference'])) {
                $_POST['reference'] = $header['reference'];
            }

            if (! isset($_POST['comments'])){
                $_POST['comments'] = $header['comments'];
            }        

            if (! isset($_POST['to_loc_code'])) {
                $_POST['to_loc_code'] = $header['to_loc_code'];
            }

            if (! isset($_POST['tran_date'])) {
                $_POST['tran_date'] = sql2date($header['tran_date']);
            }

            if (! isset($_POST['approval_status'])) {
                $_POST['approval_status'] = $header['approval_status'];
            }

        } else {
            $_POST['reference'] = $Refs->get_next($type);            
            $_POST['approval_status'] = 0;
        }
        
        div_start('nsit_header');
  
            start_outer_table(TABLESTYLE2, "width=65%"); // outer table
                start_table(TABLESTYLE2);  
                    table_section(1, "50%");

                        if (is_array($header)) {
                            label_row("Trans #:", get_inventory_trans_view_str($header['type'], $header['trans_no']));  
                            
                            $reference = $header['reference'];            
                            text_row("Reference:", 'reference', $reference, null, null);            
                        } else {            
                            text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   
                        }
                        
                        date_row("Date:", "tran_date");
                        label_row("From Location:", $_POST['to_location_name']); 

                    table_section(2, "50%");
                    
                        text_row("To Location:", "to_loc_code", null, 50, 500);
                        textarea_row("Comment:", 'comments', null, 50, 2); 

                        global $approval_statuses;
                        $s = get_project_trans_view_str(ST_APPROVAL_LOG, $trans_no."&source_type_id=".$type, "Approval Status");
                        label_row($s, $approval_statuses[$_POST['approval_status']]);

            end_outer_table(2); // outer table
    
        div_end();
}

function display_outside_material_return_details($omrc_no, $omrt_no) { 
    global $Ajax, $daily_item_types_array, $systypes_array;
    
    display_heading($systypes_array[ST_OUTSIDE_MATERIAL_RETURN]." Details");
    
    $receipt_trans_no = $return_trans_no = 0;
    $receipt_header = get_outside_material_receipt_header_record($omrc_no);
        if (is_array($receipt_header)) {
            $receipt_trans_no = $receipt_header['trans_no'];
        } 
        
    $return_hd_row = get_outside_material_receipt_header_record($omrt_no);
        if (is_array($return_hd_row)) {
            $return_trans_no = $return_hd_row['trans_no'];
        } 
        
    $units_array = build_all_item_units_array();
    
    $Ajax->activate('nsit_details');
    div_start('nsit_details');
    
        start_table(TABLESTYLE, "width=99%");

            $th = array(_("Receipt Line"), _("Return Line"), _("Item Type"), _("Item"), _("Receipt Unit"), _('Receipt'), _('Returned'), _('Retur.Alloc'), _('Remain'), 
                        _('Return Unit'), _('Return Qty'), _('Budget'), _('Site'), _('Line Comment'), _(""), _(""));  
                
            table_header($th);

            $k = 0; $dec = 4;
                $result = get_outside_material_receipt_with_outside_material_return_details($receipt_trans_no, $return_trans_no);      
                    while ($row = db_fetch($result)) {
                        $id = $row['trans_id'];
                        $return_line_id = $row['return_line_id'];
                        $conversion_factor = $row['conversion_factor'];
                        
                        alt_table_row_color($k);
                        
                            label_cell(text_bold($id), 'colspan=1 align=center');
                            label_cell($return_line_id, 'colspan=1 align=center');
                            label_cell($daily_item_types_array[$row['item_type']]);
                            if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                                label_cell($row["stock_id"]." - ".$row["item_description"]);  
                            } else {
                                label_cell($row["item_description"]);
                            }
                            label_cell(text_bold($row["unit_name"]));
                            qty_cell($row["tran_qty"], true, $dec);
                            qty_cell($row["returned_quantity"] / $conversion_factor, false, $dec);
                            qty_cell($row["returned_alloc"] / $conversion_factor, false, $dec);
                            $total_return_return_alloc = $row["returned_quantity"] + $row["returned_alloc"];
                            qty_cell(($row["tran_qty"] - $total_return_return_alloc) / $conversion_factor, false, $dec);
            
                            if (! isset($_POST["return_tran_unit_$id"])) {
                                if ($return_line_id > 0) {
                                    $_POST["return_tran_unit_$id"] = $row["return_tran_unit"];
                                } else {
                                    $_POST["return_tran_unit_$id"] = $row["tran_unit"];
                                }
                            }
                            
                            if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                                units_list_cells('', "return_tran_unit_$id", $row["stock_id"], null, '', true);
                            } else {
                                custom_values_list_cells('', "return_tran_unit_$id", $units_array, null, '', true);   
                            }
                            
                            if (! isset($_POST["return_tran_qty_$id"])) {
                                if ($return_line_id > 0) {
                                    $_POST["return_tran_qty_$id"] = $row["return_tran_qty"];
                                } else {
                                    set_outside_material_return_remain_qty($id, $row, $dec);
                                }
                            } else {
                                if (list_updated("return_tran_unit_$id")) {
                                    set_outside_material_return_remain_qty($id, $row, $dec);
                                }
                            }
                            amount_cells("", "return_tran_qty_$id", null, null, null, $dec);
                            
                            if (! isset($_POST["task_id_$id"]) && ! ($return_line_id > 0)) {
                                $_POST["task_id_$id"] = $row['task_id'];
                            } elseif (! isset($_POST["task_id_$id"]) && $return_line_id > 0) {
                                $_POST["task_id_$id"] = $row['return_task_id'];
                            }
                            
                            if (in_array($row["item_type"], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                                all_budgets_list_cells('', "task_id_$id", GLOBAL_VOTES, null, _(''));
                            } else {
                                label_cell('');
                                $_POST["task_id_$id"] = 0;
                                hidden("task_id_$id", 0);
                            }

                            if (! isset($_POST["site_id_$id"]) && ! ($return_line_id > 0)) {
                                $_POST["site_id_$id"] = $row['project_site_id'];
                            } elseif (! isset($_POST["site_id_$id"]) && $return_line_id > 0) {
                                $_POST["site_id_$id"] = $row['return_project_site_id'];
                            }
                            
                            all_project_sites_list_cells("", "site_id_$id", GLOBAL_VOTES, null, '', false); 
                            
                            if (! isset($_POST["line_comment_$id"]) && $return_line_id > 0) {
                                $_POST["line_comment_$id"] = $row['return_line_comment'];
                            }
                            text_cells('', "line_comment_$id", null, 20, 200, 'Line Comment');
                            
                            if ($return_line_id > 0 && $row['stock_control_method'] == SKCM_LOTS) {
                                $return_convesion_factor = 1;
                                get_convertion_factor2($row["stock_id"], $_POST["return_tran_unit_$id"], $return_convesion_factor);
                                
                                display_lot_serial_edit_cells($row['stock_control_method'], ST_OUTSIDE_MATERIAL_RETURN, $return_trans_no, $return_line_id, 
                                                              $return_convesion_factor, $dec);
                            } else {
                                label_cell('');
                            }
                            
                            if (! isset($_POST["checked_$id"]) && $return_line_id > 0) {
                                $_POST["checked_$id"] = 1;
                            } 
                            check_cells(null, "checked_$id", null, false, false, 'align=center colspan=1');

                        end_row();    
                        
                        vertical_space('height=18px colspan=16');
                    }
                    
        end_table(2);
    
    div_end();
}

function set_outside_material_return_remain_qty($id, $row, $dec=4) {
    $convesion_factor = 1;
    get_convertion_factor2($row['stock_id'], $_POST["return_tran_unit_$id"], $convesion_factor);
    $total_return_qty = $row["returned_quantity"] + $row["returned_alloc"];

    $remain_tran_qty = ($row["qty"] - $total_return_qty) / $convesion_factor;

    $_POST["return_tran_qty_$id"] = number_format($remain_tran_qty, $dec);
}

function can_save_outside_material_return_header($omrc_no, $omrt_no) {
    global $Refs, $systypes_array;
    
    $req_hd = get_outside_material_receipt_header_record($omrc_no);
        if (is_array($req_hd)) {
            if ($req_hd['type'] != ST_OUTSIDE_MATERIAL_RECEIPT) {
                return array("success" => false, "message" => "Invalid transaction type.");
            }
            if (! in_array($req_hd['approval_status'], array(AS_APPROVED, AS_COMPLETED))) {
                return array("success" => false, "message" => $systypes_array[ST_OUTSIDE_MATERIAL_RECEIPT]." #$omrc_no is not approved/ completed.");
            } 
        } else {
            return array("success" => false, "message" => $systypes_array[ST_OUTSIDE_MATERIAL_RECEIPT]." #$omrc_no has been deleted by another user.");
        }
        
    $trans_no = $return_row_state = 0; $return_ap_status = AS_NEW;
    $receipt_row_state = $req_hd['row_state'];
    $header = get_outside_material_receipt_header_record($omrt_no);
    
    if (($omrt_no > 0) && ! is_array($header)) {
        return array("success" => false, "message" => $systypes_array[ST_OUTSIDE_MATERIAL_RETURN]." #$omrt_no has been deleted by another user.");
    }
      
    if ($omrt_no > 0) {
        if (! in_array($header['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))) {
            return array("success" => false, "message" => "This document status does not allow further updating.");
        }
        
        $ced_msg = can_edit_document(ST_OUTSIDE_MATERIAL_RETURN, $header['project_id'], $header['next_approval_group_id'], $_SESSION['wa_current_user']->user, 
                                     $header['created_by']);
            if ($ced_msg['success'] !== true){
                return array("success" => false, "message" => $ced_msg['message']);
            }
        
        $trans_no = $header['trans_no']; $return_row_state = $header['row_state']; $return_ap_status = $header['approval_status'];
    }
    
    // check allow to add or update by user role when ap status NEW. SK only can create recs however recs should go through approval path
    $can_access_msg = can_access_outside_material_return($return_ap_status);
        if ($can_access_msg['success'] === false) {
            return $can_access_msg;
        }
    
    if (! $Refs->is_valid($_POST['reference'])) {
        return array("success" => false, "focus_to" => 'reference', "message" => "Please enter a reference.");      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], ST_OUTSIDE_MATERIAL_RETURN, $trans_no);
        if ($ref_msg) {
            return array("success" => false, "focus_to" => 'reference', "message" => $ref_msg);       
        }
      
    if (! is_date($_POST['tran_date'])) {
        return array("success" => false, "focus_to" => 'tran_date', "message" => "Date entered is not a valid date.");        
    }
      
    if (! (strlen($_POST['from_location']) > 2)) {
        return array("success" => false, "focus_to" => 'from_location', "message" => "From location cannot empty.");
    }
      
    if (! (strlen($_POST['to_loc_code']) > 2)) {
        return array("success" => false, "focus_to" => 'to_loc_code', "message" => "To location cannot empty.");
    }
    
    if ($_POST['from_location'] == $_POST['to_loc_code']) {
        return array("success" => false, "focus_to" => 'to_loc_code', "message" => "From and To locations cannot be same.");
    }
    
    return array("success" => true, 'receipt_row_state' => $receipt_row_state, 'return_row_state' => $return_row_state, "message" => "", 'req_hd' => $req_hd);    
}

function can_access_outside_material_return($return_ap_status) {
    global $systypes_array;
    
    $tran_tp_name = $systypes_array[ST_OUTSIDE_MATERIAL_RETURN];
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $can_access = false;
    $correct_role = 'WMS Store Keeper';
    
    $user_recs = get_users(id: $current_user_id);
        $user_row = db_fetch($user_recs);
        $role = $user_row['role'];
        
        if ($role == $correct_role) {
            $can_access = true;
        }
    
        // when creating new/ update outside material return record when approval status is AS_NEW
        if ($can_access === false && $return_ap_status == AS_NEW) {
            return array("success" => false, "message" => "Your role is not allowed to create new ".$tran_tp_name." only $correct_role allow to create new one.");
        } 
        
        return array("success" => true, "message" => "");
}

function can_save_outside_material_return_lines($receipt_trans_no, $return_trans_no, $type, $to_loc_code, $process=false) {
    global $systypes_array;
    
    $result = get_outside_material_receipt_with_outside_material_return_details($receipt_trans_no, $return_trans_no);  
        if (! (db_num_rows($result) > 0)) {
            return array('success' => false, 'message' => "No source ".$systypes_array[ST_OUTSIDE_MATERIAL_RECEIPT]." found.");
        }
        
        $check_exceeded_only = $process === false ? true : false;
        
        $no_selected_recs = 0;
        
        while ($row = db_fetch($result)) {
            $id = $row['trans_id'];
            $return_line_id = $row['return_line_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                $return_tran_unit = $_POST["return_tran_unit_$id"];
                $return_tran_qty = input_num("return_tran_qty_$id");
                $task_id = $_POST["task_id_$id"];
                
                $convesion_factor = 1;
                
                // can save outside material return line
                $cn_sv_ln = can_save_outside_material_return_line($return_trans_no, $row['stock_id'], $to_loc_code, $row['item_type'], $return_tran_unit, $return_tran_qty, 
                                                                  $convesion_factor, $task_id, $return_line_id, $id, $row, $check_exceeded_only);
                    if ($cn_sv_ln['success'] !== true) {
                        return array("success" => false, "message" => $cn_sv_ln['message']);
                    }
                    
                $no_selected_recs++;
                    
            } else {
                
                if ($return_line_id > 0) {
                    $lot_row = get_lot_allocation_records($type, $return_trans_no, $return_line_id, fetch:true);
                        if (is_array($lot_row) > 0) {
                            return array("success" => false, "focus_to" => '', "message" => "Please delete all ".$systypes_array[ST_LOT_ALLOCATION]." details in ".
                                                                                             $systypes_array[$type]." Line #$return_line_id.");
                        }
                }
            }
        }
        
            if (! ($no_selected_recs > 0)) {
                return array("success" => false, "message" => "Please select at least one record before saving.");  
            }

        return array("success" => true, "message" => "");
}

function can_save_outside_material_return_line($trans_no, $stock_id, $to_loc_code, $item_type, $return_tran_unit, $return_tran_qty, $convesion_factor, $task_id, 
                                               $return_line_id, $id, $row, $check_exceeded_only=true) {
    $type = ST_OUTSIDE_MATERIAL_RETURN;
    
        if ($item_type == NSIT_NON_STOCK_ITEM || $item_type == NSIT_STOCK_ITEM) {
            if ($return_tran_unit == -1) {
                return array("success" => false, "focus_to" => "return_tran_unit_$id", "message" => "Receipt Line #$id Please select a tran unit.");  
            }
        } elseif ($item_type == NSIT_COMMENT) {
            if ($return_tran_unit == '0') {
                return array("success" => false, "focus_to" => "return_tran_unit_$id", "message" => "Receipt Line #$id  Please select an unit.");  
            }
        }

        if (! ($return_tran_qty > 0)) {
            return array("success" => false, "focus_to" => "return_tran_qty_$id", "message" => "Receipt Line #$id Qty should be greater than zero.");  
        }

        get_convertion_factor2($stock_id, $return_tran_unit, $convesion_factor);
        
        // check whether total return qty is exceeded
        $rem_trn_qty_ary = get_outside_material_receipt_line_remain_qty_array($row['qty'], $id, $return_tran_qty, $convesion_factor, $return_line_id, 4);
        $old_rem_trn_qty = $rem_trn_qty_ary['old_rem_trn_qty'];
        $new_rem_trn_qty_ = $rem_trn_qty_ary['new_rem_trn_qty'];
            if ($new_rem_trn_qty_ < 0) {
                $new_rem_trn_qty = abs($new_rem_trn_qty_);
                return array('success' => false, "focus_to" => "return_tran_qty_$id", 
                             'message' => "Receipt Line #$id remain tran qty $old_rem_trn_qty is exceeded by $new_rem_trn_qty in tran unit.");
            }

        // check lot allocation exceeded
        if ($row['stock_control_method'] == SKCM_LOTS && $return_line_id > 0) {
            $data_arr = array('type' => $type, 'trans_no' => $trans_no, 'line_id' => $return_line_id, 'stock_id' => $stock_id, 'loc_code' => $to_loc_code, 
                              'conversion_factor' => $convesion_factor, 'tran_qty' => $return_tran_qty, 'tran_unit' => $return_tran_unit);
            $lot_ex_msg = check_total_lot_allocations_item_qty_exceed_allowable_qty($data_arr, $check_exceeded_only);
                if ($lot_ex_msg['success'] === false) {
                    if ($lot_ex_msg['exceeded'] === true) {
                        return array("success" => false, "message" => "Receipt line #$return_line_id Receipt Qty cannot smaller than total lot allcations."); 
                    } else {
                        return array("success" => false, "message" => "Receipt line #$return_line_id Receipt Qty cannot greater than total lot allcations."); 
                    }
                }
        }
        
        if ($item_type == NSIT_NON_STOCK_ITEM || $item_type == NSIT_STOCK_ITEM) {
            if (! ($task_id > 0)) {
                return array("success" => false, "focus_to" => "task_id_$id", "message" => "Receipt Line #$id Please select a budget.");  
            }
        }
                
        return array("success" => true, "focus_to" => "", "message" => ""); 
}

function save_outside_material_return_lines($receipt_trans_no, $return_trans_no, $project_id, $from_location, $to_loc_code, $tran_date, $process=false, $approval_status=0) {
    global $systypes_array;
    $type = ST_OUTSIDE_MATERIAL_RETURN;
    
    $result = get_outside_material_receipt_with_outside_material_return_details($receipt_trans_no, $return_trans_no);  
    
    $return_lines_count = get_outside_material_receipt_details_lines_count($return_trans_no, $type, true);
        if ($return_lines_count > 0) {
            $del_af_rows = delete_outside_material_receipt_detail_lines($type, $return_trans_no, true);
                if ($del_af_rows != $return_lines_count) {
                    cancel_transaction();
                    return array('success' => false, 'message' => "Could not delete ".$systypes_array[$type]." detail lines.");
                }
        }
        
        while ($row = db_fetch($result)) {
            $id = $row['trans_id'];
            $return_line_id = $row['return_line_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                
                $return_tran_unit = $_POST["return_tran_unit_$id"];
                $return_tran_qty = input_num("return_tran_qty_$id");
                $task_id = $_POST["task_id_$id"];
                $site_id = $_POST["site_id_$id"];
                $line_comment = $_POST["line_comment_$id"];
                
                $convesion_factor = 1;
                
                // save outside material return line
                $sv_ln_msg = save_outside_material_return_line($type, $return_trans_no, $return_line_id, $from_location, $to_loc_code, $tran_date, $row["item_type"], 
                                                               $row["stock_id"], $row["item_description"], $return_tran_unit, $return_tran_qty, $convesion_factor, $task_id, 
                                                               $site_id, $line_comment, $row);
                    if ($sv_ln_msg['success'] !== true) {
                        cancel_transaction();
                        return array("success" => false, "message" => $sv_ln_msg['message']);
                    }
                    
                // process outside material return line 
                if ($process === true && $approval_status == AS_APPROVED) {
                    $stock_control_method = $row['stock_control_method'];
                    
                    $prs_msg = process_outside_material_return_line($type, $return_trans_no, $tran_date, $project_id, $return_line_id, $stock_control_method);
                        if ($prs_msg['success'] !== true) {
                            cancel_transaction();
                            return array("success" => false, "message" => $prs_msg['message']);
                        }
                } 
            } 
        }
        
        return array("success" => true, "message" => "");  
}

function save_outside_material_return_header(&$omrc_no, &$omrt_no, &$return_trans_no, $type, $project_id, $from_location, $to_loc_code, $tran_date, $return_row_state, 
                                             $jo_id) {
    global $systypes_array;
    
    $af_no = write_outside_material_receipt_header($type, $omrc_no, $omrt_no, $return_trans_no, $_POST['reference'], $project_id, $from_location, $to_loc_code, 
                                                   $_POST['comments'], $tran_date, $return_row_state, $jo_id, 0); 
    
        if ($af_no > 0) {
            return array("success" => true, "message" => $systypes_array[$type]." header record #$omrt_no has been saved.");
        } else {
            return array("success" => false, "message" => "Could not be saved ".$systypes_array[$type].' header.');
        }
}

function save_outside_material_return_line($type, $return_trans_no, &$return_line_id, $from_location, $to_loc_code, $tran_date, $item_type, $stock_id, $item_description, 
                                           $tran_unit, $tran_qty, $conversion_factor, $task_id, $site_id, $line_comment, $row) {    
    global $systypes_array;
    
        $id = $row['trans_id'];
        $standard_cost = $row['standard_cost'];
                
            if ($item_type == NSIT_STOCK_ITEM) {
                $standard_cost = get_standard_cost($stock_id);
            } 
            
            get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);

            $base_qty = $tran_qty * $conversion_factor;

            $ln_id = insert_outside_material_receipt_line($return_trans_no, $type, $from_location, $to_loc_code, $tran_date, $stock_id, $item_type, $item_description, 
                                                          $tran_unit, $tran_qty, $base_qty, $conversion_factor, $standard_cost, $site_id, $line_comment, $task_id, $id, 
                                                          $return_line_id);

                if (! ($ln_id > 0)) {
                    return array("success" => false, "message" => "Could not save Receipt Line #$id ".$systypes_array[$type]." line details.");
                } 
        
                $return_line_id = $ln_id;
                
        return array("success" => true, "message" => $systypes_array[$type]." details have been saved.");
}

function save_outside_material_returns(&$omrc_no, &$omrt_no, $process=false) {
    global $systypes_array;
    
    $receipt_type = ST_OUTSIDE_MATERIAL_RECEIPT; $type = ST_OUTSIDE_MATERIAL_RETURN;
    
    $cn_sv_hd = can_save_outside_material_return_header($omrc_no, $omrt_no);   
        if ($cn_sv_hd["success"] !== true) {          
            return $cn_sv_hd;
        }
        
        $receipt_row_state = $cn_sv_hd['receipt_row_state']; $return_row_state = $cn_sv_hd['return_row_state'];
        
    $receipt_header = get_outside_material_receipt_header_record($omrc_no);
        $receipt_trans_no = $receipt_header['trans_no']; $project_id = $receipt_header['project_id']; $jo_id = $receipt_header['jo_id']; 
        $omrc_ap_st = $receipt_header['approval_status'];
        
    $return_trans_no = $return_approval_status = 0; 
    $return_hd_row = get_outside_material_receipt_header_record($omrt_no);
        if (is_array($return_hd_row)) {
            $return_trans_no = $return_hd_row['trans_no']; 
        }
        
    $cn_sv_line = can_save_outside_material_return_lines($receipt_trans_no, $return_trans_no, $type, $_POST['to_loc_code'], $process);   
        if ($cn_sv_line["success"] !== true) {          
            return $cn_sv_line;
        }
        
    $tran_date = date2sql($_POST['tran_date']);
       
        begin_transaction();

            $hd_msg = save_outside_material_return_header($omrc_no, $omrt_no, $return_trans_no, $type, $project_id, $_POST['from_location'], $_POST['to_loc_code'], 
                                                          $tran_date, $return_row_state, $jo_id);
                if ($hd_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $hd_msg['message']);
                }
                
            if ($process === true) {
                $ap_msg = approve_outside_material_return($omrt_no);     
                    if ($ap_msg['success'] === false ) {
                        cancel_transaction();
                        return $ap_msg;
                    }
                    
                    $return_approval_status = $ap_msg['approval_status']; // this approval status is used by below functions.
            }
                
            $sv_ln_msg = save_outside_material_return_lines($receipt_trans_no, $return_trans_no, $project_id, $_POST['from_location'], $_POST['to_loc_code'], $tran_date, 
                                                            $process, $return_approval_status);
                if ($sv_ln_msg['success'] !== true) {
                    cancel_transaction();
                    return $sv_ln_msg;       
                }
            
            // save outside material receipt - return alloc, return qty => this shold be called after lines saving becouse it checks with approval status
            $sv_is_rt_qty = save_outside_material_receipt_lines_return_alloc_return_qty_total($receipt_type, $receipt_trans_no);
                if ($sv_is_rt_qty['success'] !== true) {
                    cancel_transaction();
                    return $sv_is_rt_qty;
                }
            
            $req_trans_no = $req_hd_row_state = $req_approval_status = 0;
            // update outside material requisition returned and returned alloc qty 
            $result = get_om_requisition_lines_from_om_receipt_with_om_return($receipt_trans_no, $return_trans_no);
                while ($row = db_fetch($result)) {
                    $req_trans_no = $row['req_trans_no'];  $req_approval_status = $row['approval_status'];  $req_hd_row_state = $row['req_hd_row_state'];
                    $req_af_rw = update_outside_material_requisition_line_retruned_qty($row['trans_id'], $row['row_state']);
                        if ($req_af_rw == 0) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[ST_OUTSIDE_MATERIAL_REQ]." lines returned qty.");
                        }
                }
            
            // update outside material requisition approval status from Completed to Approved 
            if ($process === true && $return_approval_status == AS_APPROVED && $req_approval_status == AS_COMPLETED && $req_trans_no > 0) {
                $ds_msg = direct_update_document_status(ST_OUTSIDE_MATERIAL_REQ, $req_trans_no, AS_APPROVED, $req_hd_row_state);     
                    if ($ds_msg['success'] === false ) {
                        cancel_transaction();
                        return array("success" => false, "message" => "Could not update ".$systypes_array[ST_OUTSIDE_MATERIAL_REQ]." approval status.");
                    }
            } elseif ($req_trans_no > 0) {
                $req_af = update_outside_material_requisition_row_state_by_type_trans_no(ST_OUTSIDE_MATERIAL_REQ, $req_trans_no, $req_hd_row_state);
                    if (! ($req_af > 0)) {
                        cancel_transaction();
                        return array("success" => false, "message" => "Could not update ".$systypes_array[$receipt_type]." trans #$req_trans_no row state.");
                    }
            }

            // return qty + return alloc qty - returned qty
            $fully_return = check_all_outside_material_receipt_lines_fully_processed($receipt_type, $receipt_trans_no);
                if ($fully_return === true && $omrc_ap_st === AS_APPROVED) {
                    $ds_msg = direct_update_document_status($receipt_type, $receipt_trans_no, AS_COMPLETED, $receipt_row_state);     
                        if ($ds_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$receipt_type]." approval status.");
                        }

                        $receipt_row_state = db_new_row_state($receipt_row_state);
                } elseif ($fully_return === false && $omrc_ap_st === AS_COMPLETED) {
                    $ds_msg = direct_update_document_status($receipt_type, $receipt_trans_no, AS_APPROVED, $receipt_row_state);     
                        if ($ds_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$receipt_type]." approval status.");
                        }

                        $receipt_row_state = db_new_row_state($receipt_row_state);
                }
                
            $rcp_af = update_outside_material_receipt_row_state_by_id($omrc_no, $receipt_row_state);
                if (! ($rcp_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$receipt_type]." record #$omrc_no row state.");
                }
                
        commit_transaction();
            
            if ($process === true) {
                set_session_variable('omrt_messages', $ap_msg['message']);
                meta_forward($_SERVER['PHP_SELF'], "type=$type&ProcessedID=$return_trans_no"); ;
            } else {
                return array("success" => true, "message" => $systypes_array[$type]." trans #$return_trans_no has been saved.");
            }
}

function approve_outside_material_return($omrt_no) {
    $current_user_id = $_SESSION['wa_current_user']->user;
    $task_costs = 0;
    
    $header = get_outside_material_receipt_header_record($omrt_no);
    
        return approve_document($header['type'], $header['trans_no'], $header['project_id'], $task_costs, $header['next_approval_group_id'], $current_user_id, 
                                $header['row_state'], $header['created_by']);
}

function can_reject_back_to_originator_outside_material_return($omrc_no, $omrt_no, $trans_tp_name, $reject) {
    global $systypes_array;
    
    $req_hd = get_outside_material_receipt_header_record($omrc_no);
        if (is_array($req_hd)) {
            if ($req_hd['type'] != ST_OUTSIDE_MATERIAL_RECEIPT) {
                return array("success" => false, "message" => "Invalid transaction type.");
            }
        } else {
            return array("success" => false, "message" => $systypes_array[ST_OUTSIDE_MATERIAL_RECEIPT]." #$omrc_no has been deleted by another user.");
        }
    
    $hd_row = get_outside_material_receipt_header_record($omrt_no);
    
        if (! is_array($hd_row)) {
            return array("success" => false, "message" => "Could not find $trans_tp_name #$omrt_no.");
        }

        if (! isset($hd_row['type']) || $hd_row['type'] != ST_OUTSIDE_MATERIAL_RETURN) {
            return array("success" => false, "message" => "Invalid transaction type.");
        }
        
        if ($reject === true) {
            if (! in_array($hd_row['approval_status'], array(AS_NEW, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR, AS_WITH_THE_APPROVER))) {
                return array("success" => false, "message" => "This document status does not allow to reject. Only unapproved records can be rejected.");
            }
        } else {
            if (! in_array($hd_row['approval_status'], array(AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER))) {
                return array("success" => false, "message" => "This document status does not allow to back to originator.");
            }
        }
        
        $ced_msg = can_edit_document(ST_OUTSIDE_MATERIAL_RETURN, $hd_row['project_id'], $hd_row['next_approval_group_id'], $_SESSION['wa_current_user']->user, 
                                     $hd_row['created_by']);
            if ($ced_msg['success'] !== true){
                return array("success" => false, "message" => $ced_msg['message']);
            }
        
        return array("success" => true, "message" => "", "req_hd_row" => $req_hd, "hd_row" => $hd_row);
}

function reject_outside_material_return($omrc_no, $omrt_no) {
    global $systypes_array;
    
    $receipt_type = ST_OUTSIDE_MATERIAL_RECEIPT;
    $type = ST_OUTSIDE_MATERIAL_RETURN;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_outside_material_return($omrc_no, $omrt_no, $trans_tp_name, true);
        if ($cn_rej["success"] !== true) { 
            return $cn_rej;
        } 
        
        $req_hd_row = $cn_rej["req_hd_row"];
            $receipt_row_state = $req_hd_row['row_state'];
            $receipt_trans_no = $req_hd_row["trans_no"];
            $omrc_ap_st = $req_hd_row["approval_status"];
        
        $hd_row = $cn_rej["hd_row"];
            $return_trans_no = $hd_row["trans_no"];
            $row_state = $hd_row["row_state"];
        
        begin_transaction();
        
            $rj_msg = reject_document($type, $return_trans_no, $hd_row['project_id'], $hd_row['next_approval_group_id'], $_SESSION['wa_current_user']->user, $row_state);
                if ($rj_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $rj_msg['message']);
                }
                
            // save outside material receipt - return alloc, return qty => this shold be called after lines saving becouse it checks with approval status
            $sv_is_rt_qty = save_outside_material_receipt_lines_return_alloc_return_qty_total($receipt_type, $receipt_trans_no);
                if ($sv_is_rt_qty['success'] !== true) {
                    cancel_transaction();
                    return $sv_is_rt_qty;
                }
            
            $req_trans_no = $req_hd_row_state = $req_approval_status = 0;
            // update outside material requisition returned and returned alloc qty 
            $result = get_om_requisition_lines_from_om_receipt_with_om_return($receipt_trans_no, $return_trans_no);
                while ($row = db_fetch($result)) {
                    $req_trans_no = $row['req_trans_no'];  $req_approval_status = $row['approval_status'];  $req_hd_row_state = $row['req_hd_row_state'];
                    $req_af_rw = update_outside_material_requisition_line_retruned_qty($row['trans_id'], $row['row_state']);
                        if ($req_af_rw == 0) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[ST_OUTSIDE_MATERIAL_REQ]." lines returned qty.");
                        }
                }
            
            if ($req_trans_no > 0) {
                $req_af = update_outside_material_requisition_row_state_by_type_trans_no(ST_OUTSIDE_MATERIAL_REQ, $req_trans_no, $req_hd_row_state);
                    if (! ($req_af > 0)) {
                        cancel_transaction();
                        return array("success" => false, "message" => "Could not update ".$systypes_array[$receipt_type]." trans #$req_trans_no row state.");
                    }
            }

            // return qty + return alloc qty - returned qty
            $fully_return = check_all_outside_material_receipt_lines_fully_processed($receipt_type, $receipt_trans_no);
                if ($fully_return === true && $omrc_ap_st === AS_APPROVED) {
                    $ds_msg = direct_update_document_status($receipt_type, $receipt_trans_no, AS_COMPLETED, $receipt_row_state);     
                        if ($ds_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$receipt_type]." approval status.");
                        }

                        $receipt_row_state = db_new_row_state($receipt_row_state);
                } elseif ($fully_return === false && $omrc_ap_st === AS_COMPLETED) {
                    $ds_msg = direct_update_document_status($receipt_type, $receipt_trans_no, AS_APPROVED, $receipt_row_state);     
                        if ($ds_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$receipt_type]." approval status.");
                        }

                        $receipt_row_state = db_new_row_state($receipt_row_state);
                }
                
            $rcp_af = update_outside_material_receipt_row_state_by_id($omrc_no, $receipt_row_state);
                if (! ($rcp_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$receipt_type]." record #$omrc_no row state.");
                }
                
        commit_transaction();

            set_session_variable('omrt_rj_messages', $rj_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&RejectedID=$return_trans_no"); 
}

function back_to_originator_outside_material_return($omr_no, $omrc_no) {
    global $systypes_array;
    
    $type = ST_OUTSIDE_MATERIAL_RETURN;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_outside_material_return($omr_no, $omrc_no, $trans_tp_name, false);
        if ($cn_rej["success"] !== true) { 
            return $cn_rej;
        } 
        
        $hd_row = $cn_rej["hd_row"];
        $trans_no = $hd_row["trans_no"];
        
        begin_transaction();
        
            $ap_msg = send_back_to_document_originator($type, $trans_no, $hd_row['project_id'], $hd_row['next_approval_group_id'], $_SESSION['wa_current_user']->user, 
                                                       $hd_row['row_state'], $hd_row['created_by']);
                if ($ap_msg['success'] === false ) {
                    cancel_transaction();
                    return array("success" => false, "message" => $ap_msg['message']);
                }
            
        commit_transaction();

            set_session_variable('omrt_bo_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&BackedOrgID=$trans_no"); 
}

function clear_outside_material_return_details() {
    unset($_POST['item_type']);
    unset($_POST['stock_id']);
    unset($_POST['item_description']);
    unset($_POST['tran_unit']);
    unset($_POST['tran_qty']);
    unset($_POST['site_id']);
    unset($_POST['line_comment']);
}

function process_outside_material_return_line($type, $trans_no, $tran_date, $project_id, $return_line_id, $stock_control_method) {
    $row = get_outside_material_receipt_details_line_by_type_trans_no_line_no($type, $trans_no, $return_line_id);
            
        // stock move
        $stk_mv_msg = process_outside_material_return_item($trans_no, $type, $tran_date, $project_id, $row);
            if ($stk_mv_msg['success'] === false) {
                cancel_transaction();
                return $stk_mv_msg;
            }
            
        // lot move
        if ($stock_control_method == SKCM_LOTS) {
            $lot_mv_msg = lot_allocations_to_lot_moves($type, $trans_no, $return_line_id);
                if ($lot_mv_msg['success'] === false) {
                    cancel_transaction();
                    return $lot_mv_msg;
                }
                
            $lot_loc_array = $lot_mv_msg['lot_loc_array'];
            
            // update lot balances
            $lot_bl_msg = save_lot_balances_from_array($lot_loc_array);
                if ($lot_bl_msg['success'] === false) {
                    cancel_transaction();
                    return $lot_bl_msg;
                }
        }
        
        // budget update 
        if ($row['item_type'] != NSIT_COMMENT) {
            $omrc_details_array = $b = array();
            
            $qty = $row['qty'];
            $b['row_id'] = $row['trans_id'];
            $b['stock_id'] = $row['stock_id'];
            $b['task_id'] = $row['task_id'];
            $b['requested_qty'] = $row['qty'];
            $b['high_value_item'] = 0;

            $standard_cost = $row['standard_cost'];
            $b['reference_cost'] = $standard_cost; 
            $b['standard_cost'] = $standard_cost;
            $b['charging_cost'] = $standard_cost;
            $b['total_issued_qty'] = $qty;
            $b['qty'] = $qty;

            $omrc_details_array[] = $b;
            
            $omrc_tasks_summary = calculate_task_remaining_totals($omrc_details_array);
            $created_by = $_SESSION['wa_current_user']->user;

            $mtrec_msg = remove_costs_from_tasks($type, $trans_no, $omrc_tasks_summary, $created_by);
                if ($mtrec_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => $mtrec_msg['success'], "tran_no" => $trans_no, "message" => $mtrec_msg['message']);
                }
        }

        return array("success" => true, "message" => "");
}

function process_outside_material_return_item($trans_no, $type, $tran_date, $project_id, $row) {
    $tran_date_ = sql2date($tran_date);
    $qty = abs($row["qty"]);
    $tran_qty = abs($row["tran_qty"]);
    
    $qty *= -1;
    $tran_qty *= -1;
    
    $standard_cost = $row["standard_cost"];
    
        if ($row['mb_flag'] == 'B' || $row['mb_flag'] == 'M') {
            $n = add_stock_adjustment_item($trans_no, $row["stock_id"], $row["from_location"], $tran_date_, $row["reference"], $qty, $standard_cost, '', $row["tran_unit"], 
                                           $tran_qty, $row["conversion_factor"], $type, $row["task_id"], $row["project_site_id"], $row["trans_id"], $project_id);
        } else {
            $n = add_non_stock_move($type, $row["stock_id"], $trans_no, $row["from_location"], $tran_date_, $row["reference"], $qty, $standard_cost, '', $row["visible"], 
                                    $row["price"], $row["discount_percent"], $row["tran_unit"], $tran_qty, $row["conversion_factor"], $row["task_id"], $row["project_site_id"], 
                                    $row["trans_id"], $row["item_description"], $project_id);
        }

        if (! ($n > 0)) {
            return array("success" => false, "message" => "Could not create the movement record for rec id : ".$row["trans_id"]);
        }

        return array("success" => true, 'trans_no' => $trans_no, "message" => "");            
}

function view_outside_material_return_header($type, $trans_no) {
    global $approval_statuses;
    
    $row = get_outside_material_receipt_header_type_trans_no($type, $trans_no);
    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
        start_outer_table(TABLESTYLE2, "width=60%");

            table_section(1, "50%");
                $jo_id = $row['jo_id'];
                $re_hd = get_outside_material_receipt_header_record($row['omr_no']);
                label_row("Receipt Trans #:", get_inventory_trans_view_str(ST_OUTSIDE_MATERIAL_RECEIPT, $re_hd['trans_no']), "class='tableheader2'");  
                label_row("Job Card #:", get_service_trans_view_str(ST_JOB_ORDER, $jo_id), "class='tableheader2'");
                label_row(_("Project:"), get_project_formatted_name($row['project_id']), "class='tableheader2'");
                label_row(_("Reference:"), $row['reference'], "class='tableheader2'");

            table_section(2, "50%");
                label_row(_("Date:"), sql2date($row['tran_date']), "class='tableheader2'");
                label_row(_("From Location:"), $row['from_location_name'], "class='tableheader2'");
                label_row(_("To Location:"), $row['to_loc_code'], "class='tableheader2'");
                $s = get_project_trans_view_str(ST_APPROVAL_LOG, $trans_no."&source_type_id=".$type, "Approval Status");
                label_row($s, $approval_statuses[$row['approval_status']], "class='tableheader2'");

        end_outer_table(2);

        if (strlen($row['comments']) > 0) {
            start_table(TABLESTYLE2);
                label_row(_("Comment:"), nl2br($row['comments']), "class='tableheader2'");
            end_table(2);
        }
}

function view_outside_material_return_details($type, $trans_no) {
    global $daily_item_types_array;
    
    $view_tp = ST_LOT_ALLOCATION;
    $hd_row = get_outside_material_receipt_header_record_type_trans_no($type, $trans_no);
        if (in_array($hd_row['approval_status'], array(AS_APPROVED))) {
            $view_tp = ST_LOT_MOVE;
        }
        
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($hd_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    start_table(TABLESTYLE, "width=88%");

        $th = array(_("Line Id"), _("Receipt Line"), _("Item Type"), _("Description"), _("Unit"), _("Tran Qty"), _('Budget'), _('Cost'), _('Project Site'), _('Comment'));  
        table_header($th);

        $k = 0; //row colour counter
            $result = get_outside_material_receipt_details($trans_no, $type);      
                while ($row = db_fetch($result)) {
                    $dec = 4;
                    
                    alt_table_row_color($k);

                        $trans_id = $row['trans_id'];
                        
                        if ($row['stock_control_method'] == SKCM_LOTS) {
                            $params = "type=".ST_OUTSIDE_MATERIAL_RETURN."&trans_no=$trans_no&line_id=$trans_id";
                            label_cell(get_data_view_str($view_tp, $params, $trans_id), 'align=center');
                        } else {
                            label_cell($trans_id, 'align=center');
                        }
                        
                        label_cell($row['source_line_id'], 'align=center');
                        
                        label_cell($daily_item_types_array[$row['item_type']]);
                        if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                            label_cell($row["stock_id"]." - ".$row["item_description"]);  
                            
                            $dec = get_qty_dec($row["stock_id"]);
                        } else {
                            label_cell($row["item_description"]);
                        }
                        label_cell($row["unit_name"]);
                        
                        if ($row['stock_control_method'] == SKCM_LOTS) {
                            $params = "type=".ST_OUTSIDE_MATERIAL_RETURN."&trans_no=$trans_no&line_id=$trans_id";
                            label_cell(get_data_view_str($view_tp, $params, number_format($row["tran_qty"], $dec)), 'align=right');
                        } else {
                            qty_cell($row["tran_qty"], false, $dec);
                        }
                        
                        if ($row['item_type'] == NSIT_COMMENT) {
                            label_cell('No budget required');
                        } else {
                            label_cell($row["task_description"]);
                        }
                        $tran_unit_cost = $row["conversion_factor"] * $row["standard_cost"];
                            if ($tran_unit_cost > 0) {
                                qty_cell($tran_unit_cost, false, $dec);
                            } else {
                                label_cell('');
                            }
                            
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(2);
}

function view_outside_material_return_return_headers_by_omrc_no($omrc_no, $type) {
    $result = get_outside_material_return_headers_by_omrc_no_type($omrc_no, $type); 
        if (! (db_num_rows($result) > 0)) {
            return;
        }
    
    $rcp_hd = get_outside_material_receipt_header_record($omrc_no);
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($rcp_hd['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
        
    global $systypes_array, $approval_statuses;
    
    display_heading($systypes_array[$type]." headers");
    
        start_table(TABLESTYLE, "width=70%");

            $th = array(_("Trans #"), _("Trans Date"), _("From Location"), _("To Location"), _("Approval Status"));  
            table_header($th);

            $k = 0; //row colour counter
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);
                        label_cell(get_inventory_trans_view_str($row['type'], $row['trans_no']), 'align=center');
                        label_cell(sql2date($row["tran_date"]), 'align=center');
                        label_cell($row['from_location_name']);
                        label_cell($row['to_loc_code']);
                        label_cell($approval_statuses[$row['approval_status']], 'align=center');
                    end_row();        
                }

        end_table(2);
}

function view_outside_material_return_headers_by_jo_id($jo_id, $type, $width=70) {
    global $approval_statuses, $systypes_array;
    
    $jo_row = get_job_order_project_id($jo_id);
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($jo_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    display_heading2($systypes_array[$type].'s');    br();
    
    start_table(TABLESTYLE, "width=$width%");

        $th = array(_("Trans #"), _("Reference"), _("Description"), _("Date"), _("From Location"), _("To Location"), _("Approval Status"));  
        table_header($th);

        $k = 0; //row colour counter
            $result = get_outside_material_receipt_headers_by_filters($jo_id, 0, $type);      
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);
                        
                        label_cell(get_trans_view_str($row['type'], $row['trans_no']), 'align=center');
                        label_cell($row["reference"]);
                        label_cell($row["comments"]);
                        label_cell(sql2date($row["tran_date"]), 'align=center');
                        label_cell($row['from_location_name']);
                        label_cell($row['to_loc_code']);
                        label_cell($approval_statuses[$row['approval_status']], 'align=center');

                    end_row();        
                }

    end_table(2);
}

?>