<?php

function display_job_manual_cost_header_details($jmc_no, $jmcr_no) {
    global $approval_statuses, $systypes_array;
    
    $iss_hd_row = get_job_material_issue_header($jmc_no);
    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($iss_hd_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    display_heading($systypes_array[ST_JOB_MANUAL_COST]." Header");
    
        $jm_issue_trans_no = $iss_hd_row['trans_no'];
        if (! isset($_POST['location']) && ! ($jmcr_no > 0)) {
            $_POST['location'] = $iss_hd_row['loc_code'];
        }
    
    start_outer_table(TABLESTYLE2, "width=65%"); // outer table
        start_table(TABLESTYLE2);  
            table_section(1, "27%");
                $jo_id = $iss_hd_row['jo_id'];
                label_row("JMC. Trans #:", get_inventory_trans_view_str($iss_hd_row['type'], $iss_hd_row['trans_no']));  
                label_row("Job Card #:", get_service_trans_view_str(ST_JOB_ORDER, $jo_id));
                $iss_row = get_job_material_issue_header_record($jmcr_no);
                    if (is_array($iss_row)) {
                        label_row("Return Trans #:", $iss_row['trans_no']);  
                    }
                label_row("Reference:", $iss_hd_row['reference']);  

            table_section(2, "45%");
                label_row("Project:", get_project_formatted_name($iss_hd_row['project_id']));  
                label_row("Date:", sql2date($iss_hd_row['tran_date']));  
                label_row("Location:", $iss_hd_row['location_name']);  
                
            table_section(3, "27%");
                label_row("Requestor:", $iss_hd_row['requestor_name']);  
                label_row(_("Total:"), $iss_hd_row['total']);
                $s = get_project_trans_view_str(ST_APPROVAL_LOG, $jm_issue_trans_no."&source_type_id=".ST_JOB_MANUAL_COST, "Approval Status");
                label_row($s, $approval_statuses[$iss_hd_row['approval_status']]);
    end_outer_table(2); // outer table
    
    if (strlen($iss_hd_row['comments']) > 0) {
        start_table(TABLESTYLE);
            label_row("Comment:", nl2br($iss_hd_row['comments']));  
        end_table(2);
    }
    
    return $iss_hd_row;
}

function display_job_manual_cost_return_header($jmcr_no, $iss_hd_row) {
    global $Refs, $systypes_array;
    
    $type = ST_JOB_MANUAL_COST_RETURN;
    $trans_no = 0;
    
    display_heading($systypes_array[$type]." Header");
    
        $_POST['project_id'] = $iss_hd_row['project_id'];
        hidden('project_id', $iss_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_job_material_issue_header($jmcr_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['location'])) {
                    $_POST['location'] = $header['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'];
                }
                $_POST['total'] = $header['total'];
            } else {
                $_POST['reference'] = $Refs->get_next($type);            
                $_POST['total'] = $_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");
                        if (is_array($header)) {
                            label_row("Returning Location:", $header['location_name']);  
                            hidden('location', $_POST['location']);
                        } else {
                            locations_list_row("Returning Location:", 'location', null, '', false); 
                        }

                    table_section(2, "50%");
                    
                        textarea_row("Comment:", 'comments', null, 35, 2); 
                        label_row('Return Total:', number_format($_POST['total'], 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_job_manual_cost_return_details($jmc_no, $jmcr_no) { 
    global $Ajax, $daily_item_types_array, $systypes_array;
    
    $issue_type = ST_JOB_MANUAL_COST;
    $return_type = ST_JOB_MANUAL_COST_RETURN;
    
    display_heading($systypes_array[$return_type]." Details");
    
    $issue_trans_no = $return_trans_no = 0;
    $req_header = get_job_material_issue_header_record($jmc_no);
        if (is_array($req_header)) {
            $issue_trans_no = $req_header['trans_no'];
        } 
        
    $return_hd_row = get_job_material_issue_header_record($jmcr_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(_("JMC Line"), _("JMC Ret.<br> line"), _("Item Type"), _("Item"), _("JMC Unit"), _("JMC Qty"), _('Qty<br> Returned'), _('Qty.<br> Rtn Alloc'), 
                        _('Returned<br> + Alloc'), _('Return Unit'), _('Return.Qty'), _('Budget'), _('Base.U<br> Cost'), _('Site'), _('Line<br> Comment'), 
                        _(""), _(""), _(""));  
                
            table_header($th);

            $k = 0; //row colour counter
                $result = get_job_material_issue_and_return_details($issue_type, $issue_trans_no, $return_type, $return_trans_no);      
                    while ($row = db_fetch($result)) {
                        $id = $row['issue_line_id'];
                        $return_line_id = $row['return_line_id']; 
                        $issue_conversion_factor = $row['conversion_factor'];
                        
                        alt_table_row_color($k);

                            label_cell(get_inventory_trans_view_str($issue_type, $row['issue_trans_no'], $row['issue_line_id']), 'align=center');
                            label_cell($return_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"]);  
                            } else {
                                label_cell($row["item_description"]);
                            }
                            label_cell(text_bold($row["unit_name"]));
                            
                            $dec = get_qty_dec($row["stock_id"]);
                            qty_cell($row["tran_qty"], true, $dec);
                            qty_cell($row["returned_quantity"] / $issue_conversion_factor, false, $dec);
                            qty_cell($row["returned_alloc"] / $issue_conversion_factor, false, $dec);
                            qty_cell($row["returned_quantity"] + $row["returned_alloc"] / $issue_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_job_manual_cost_remain_returnable_qty($id, $row, $dec);
                                }
                            } else {
                                if (list_updated("return_tran_unit_$id")) {
                                    set_job_manual_cost_remain_returnable_qty($id, $row, $dec);
                                }
                            }
                            amount_cells("", "return_tran_qty_$id", null, null, null, $dec);
                            label_cell($row['task_description']);
                            qty_cell($row["standard_cost"], false, 2);
                            
                            if (! isset($_POST["site_id_$id"])) {
                                if ($return_line_id > 0) {
                                    $_POST["site_id_$id"] = $row["return_site_id"];
                                } else {
                                    $_POST["site_id_$id"] = $row["project_site_id"];
                                }
                            }
                            all_project_sites_list_cells("", "site_id_$id", GLOBAL_VOTES, null, '', false); 
                            
                            if (! isset($_POST["line_comment_$id"])) {
                                $_POST["line_comment_$id"] = $row["line_comment"];
                            }
                            text_cells_ex('', "line_comment_$id", 20, 400, null, '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'], $return_type, $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=2');

                        end_row();        
                    }

        end_table(2);
    
    div_end();
}

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

    $remain_tran_qty = ($issued_qty - ($returned_quantity + $returned_alloc)) / $convesion_factor;

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

function can_save_job_manual_cost_return_header($jmc_no, $jmcr_no) {
    global $Refs, $systypes_array;
    
    $issue_type = ST_JOB_MANUAL_COST;
    $return_type = ST_JOB_MANUAL_COST_RETURN;
    
    $jmc_tp_name = $systypes_array[$issue_type];
    $rtn_tp_name = $systypes_array[$return_type];
    
    $iss_hd = get_job_material_issue_header_record($jmc_no);
        if (is_array($iss_hd)) {
            if (! in_array($iss_hd['approval_status'], array(AS_APPROVED)) && ! ($jmcr_no > 0)) {
                return array("success" => false, "message" => "$jmc_tp_name trans #".$iss_hd['trans_no']." is closed not allow to create new $rtn_tp_name.");
            }
        } else {
            return array("success" => false, "message" => "$jmc_tp_name record #$jmc_no is deleted by another user.");
        }
    
    $iss_row_state = $iss_hd['row_state'];
    $trans_no = $return_row_state = 0;
    $header = get_job_material_issue_header_record($jmcr_no);
    
    if (($jmcr_no > 0) && ! is_array($header)) {
        return array("success" => false, "message" => "$rtn_tp_name record #$jmcr_no is deleted by another user.");
    }
      
    if (is_array($header)) {
        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($return_type, $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'];
    } 
    
    if (! $Refs->is_valid($_POST['reference'])) {
        return array("success" => false, "focus_to" => 'reference', "message" => "Please enter a reference.");      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], $return_type, $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 ($_POST['location'] == '') {
        return array("success" => false, "focus_to" => 'location', "message" => "Returning location cannot empty.");
    }
    
    return array("success" => true, 'iss_row_state' => $iss_row_state, 'return_row_state' => $return_row_state, "message" => "", 'iss_hd' => $iss_hd);   
}

function can_save_job_manual_cost_return_lines($issue_type, $issue_trans_no, $type, $return_trans_no, $loc_code, $process=false) {
    global $systypes_array;
    
    $result = get_job_material_issue_and_return_details($issue_type, $issue_trans_no, $type, $return_trans_no); 
        if (! (db_num_rows($result) > 0)) {
            return array('success' => false, 'message' => "No any line found against ".$systypes_array[ST_JOB_MANUAL_COST]." for Trans #$issue_trans_no.");
        }
        
        $check_exceeded_only = $process === false ? true : false;
    
    $no_selected_recs = 0;
        while ($row = db_fetch($result)) {
            $id = $row['issue_line_id'];
            $return_line_id = $row['return_line_id'];
            $stock_id = $row['stock_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                $item_type = $row['item_type'];
                
                $return_tran_unit = $_POST["return_tran_unit_$id"];
                $return_tran_qty = input_num("return_tran_qty_$id");
                
                // can save job manual cost return line
                $cn_sl_ln = can_save_job_manual_cost_return_line($return_trans_no, $stock_id, $loc_code, $item_type, $return_tran_unit, $return_tran_qty, $return_line_id, 
                                                                 $id, $row, $check_exceeded_only);
                    if ($cn_sl_ln['success'] !== true) {
                        return $cn_sl_ln;
                    }

                $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_JOB_LOT_SELECTION]." in JMC line #$id before deleting ".
                                                       $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.");  
        }
        
        if ($process === true) {
            $result = get_job_material_issue_detail_records_with_no_source(ST_JOB_MANUAL_COST_RETURN, $return_trans_no);      
                while ($row = db_fetch($result)) {
                    if (! ($row['task_id'] > 0)) {
                        $line_id = $row['trans_id'];
                        return array("success" => false, "message" => "JMC Ret. line #$line_id please select a budget.");  
                    }
                }
        }
        
        return array("success" => true, "message" => "");  
}

function can_save_job_manual_cost_return_line($trans_no, $stock_id, $loc_code, $item_type, $return_tran_unit, $return_tran_qty, $return_line_id, $id, $row, 
                                              $check_exceeded_only=true) {
    $type = ST_JOB_MANUAL_COST_RETURN;
    $dec = 4; 
    
    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" => "JMC 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" => "JMC line #$id Please select an unit.");  
        }
    }

    if (! ($return_tran_qty > 0)) {
        return array("success" => false, "focus_to" => "return_tran_qty_$id", "message" => "JMC line #$id Qty should be greater than zero.");  
    }
    
    $convesion_factor = 1;
    get_convertion_factor2($stock_id, $return_tran_unit, $convesion_factor);

    $base_returned_qty = (float) get_job_material_issue_lines_total_by_source_line($type, $id, $return_line_id, approval_status_not_array: array(AS_REJECTED));
    $tran_returned_qty = $base_returned_qty / $convesion_factor;

    $total_tran_returned_qty = $tran_returned_qty + $return_tran_qty;

    $issued_tran_qty = ($row["qty"] / $convesion_factor);

    if ($total_tran_returned_qty > $issued_tran_qty) {
        $total_returnable_tran_qty = round($issued_tran_qty - $tran_returned_qty, $dec);
        $exceeded_qty = round($total_tran_returned_qty - $issued_tran_qty, $dec);

        return array("success" => false, "focus_to" => "return_tran_qty_$id", 
                     "message" => "JMC line #$id exceeded the maximum returnable qty of $total_returnable_tran_qty by $exceeded_qty qty in tran unit.");  
    }

    // check lot allocation exceeded
    if ($row['stock_control_method'] == SKCM_LOTS && $return_line_id > 0) {
        $data_array = array('type' => $type, 'trans_no' => $trans_no, 'line_id' => $return_line_id, 'stock_id' => $stock_id, 'loc_code' => $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_array, $check_exceeded_only);
                if ($lot_ex_msg['success'] === false) {
                    if ($lot_ex_msg['exceeded'] === true) {
                        return array("success" => false, "message" => "Return line #$return_line_id Return Qty cannot smaller than total lot allcations."); 
                    } else {
                        return array("success" => false, "message" => "Return line #$return_line_id Return Qty cannot greater than total lot allcations."); 
                    }
                }
    }
    
        return array("success" => true, "focus_to" => "", "message" => "");  
}

function save_job_manual_cost_return_lines($issue_type, $issue_trans_no, $type, $return_trans_no, $loc_code, $tran_date, $process=false) {
    global $systypes_array;

    $result = get_job_material_issue_and_return_details($issue_type, $issue_trans_no, $type, $return_trans_no); 
        if (! (db_num_rows($result) > 0)) {
            return array('success' => false, 'message' => "No any ".$systypes_array[ST_JOB_MANUAL_COST]." lines found for Trans #$issue_trans_no.");
        }
    
    $return_lines_count = get_job_material_issue_details_lines_count($return_trans_no, $type, true);
        if ($return_lines_count > 0) {
            $del_af_rows = delete_job_material_issue_detail_lines($type, $return_trans_no, true);
                if ($del_af_rows != $return_lines_count) {
                    return array('success' => false, 'message' => "Could not delete ".$systypes_array[$type]." lines.");
                }
        }
        
        while ($row = db_fetch($result)) {
            $id = $row['issue_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");
                $site_id = $_POST["site_id_$id"];
                $line_comment = $_POST["line_comment_$id"];
                
                $convesion_factor = 1;
                
                // save job manual cost return line
                $sv_ln_msg = save_job_manual_cost_return_line($type, $return_trans_no, $loc_code, $tran_date, $return_tran_unit, $return_tran_qty, $convesion_factor, $site_id, 
                                                              $line_comment, $row);
                    if ($sv_ln_msg['success'] !== true) {
                        cancel_transaction();
                        return array("success" => false, "message" => $sv_ln_msg['message']);
                    }
            } 
        }
        
        $save_process = $process === true ? 'Processed' : 'Saved'; 
        return array("success" => true, "message" => $systypes_array[$type]." has been $save_process.");  
}

function save_job_manual_cost_return_header(&$jmc_no, &$jmcr_no, &$return_trans_no, $type, $project_id, $loc_code, $tran_date, $return_row_state, $jo_id) {
    global $systypes_array;
    
    $af_no = write_job_material_issue_header($type, $jmc_no, $jmcr_no, $return_trans_no, $_POST['reference'], $project_id, $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 #$jmcr_no has been saved.");
        } else {
            return array("success" => false, "message" => "Could not be saved ".$systypes_array[$type].' header.');
        }
}

function save_job_manual_cost_return_line($type, $return_trans_no, $loc_code, $tran_date, $tran_unit, $tran_qty, $conversion_factor, $project_site_id, $line_comment, $row) {    
    global $systypes_array;
    
        $id = $row['issue_line_id'];
        $return_line_id = $row['return_line_id'];

        $stock_id = $row['stock_id'];
        $item_type = $row['item_type'];
        $item_description = $row['item_description'];
        $standard_cost = $row['standard_cost'];
        $task_id = $row['task_id'];

            get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);

            $base_qty = $tran_qty * $conversion_factor;

            $ln_id = insert_job_material_issue_line($return_trans_no, $type, $loc_code, $tran_date, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, 
                                                    $base_qty, $conversion_factor, $standard_cost, $project_site_id, $line_comment, $task_id, $id, $return_line_id);

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

function save_job_manual_cost_returns(&$jmc_no, &$jmcr_no, $process=false) {
    global $systypes_array;
    
    $issue_type = ST_JOB_MANUAL_COST; $type = ST_JOB_MANUAL_COST_RETURN;
    
    $hd_msg = can_save_job_manual_cost_return_header($jmc_no, $jmcr_no);   
        if ($hd_msg["success"] !== true) {          
            return $hd_msg;
        }
        
        $iss_row_state = $hd_msg['iss_row_state']; $return_row_state = $hd_msg['return_row_state'];
        
        $iss_hd = $hd_msg['iss_hd'];
        $issue_trans_no = $iss_hd['trans_no']; $project_id = $iss_hd['project_id']; $jo_id = $iss_hd['jo_id'];
        
    $return_trans_no = $approval_status = $increment_row_state = 0;
    $ret_hd = get_job_material_issue_header_record($jmcr_no);
        if (is_array($ret_hd)) {
            $return_trans_no = $ret_hd['trans_no']; 
            $increment_row_state = 1;
        }
        
    $cn_sv_line = can_save_job_manual_cost_return_lines($issue_type, $issue_trans_no, $type, $return_trans_no, $_POST['location'], $process);   
        if ($cn_sv_line["success"] !== true) {          
            return $cn_sv_line;
        }
        
    $tran_date = date2sql($_POST["tran_date"]);
        
        begin_transaction();

            $header_msg = save_job_manual_cost_return_header($jmc_no, $jmcr_no, $return_trans_no, $type, $project_id, $_POST['location'], $tran_date, $return_row_state, 
                                                             $jo_id);
                if ($header_msg["success"] !== true) {
                    cancel_transaction();
                    
                    return array("success" => false, "message" => $header_msg['message']);
                }
                
                if ($increment_row_state == 1) {
                    $return_row_state = db_new_row_state($return_row_state);
                }
                
            $ln_msg = save_job_manual_cost_return_lines($issue_type, $issue_trans_no, $type, $return_trans_no, $_POST['location'], $tran_date, $process);
                if ($ln_msg['success'] !== true) {
                    cancel_transaction();
                    
                    return $ln_msg;       
                }
                
            if ($process === true) {
                $task_costs = 0;
                $current_user_id = $_SESSION['wa_current_user']->user;
                
                $ap_msg = approve_document($type, $return_trans_no, $project_id, $task_costs, $ret_hd['next_approval_group_id'], $current_user_id, $return_row_state, 
                                           $ret_hd['created_by']);
                    if ($ap_msg['success'] === false) {
                        cancel_transaction();
                        
                        return $ap_msg;
                    }
                    
                    $approval_status = $ap_msg['approval_status']; // this approval status is used by below functions.
                    $return_row_state = db_new_row_state($return_row_state);
            }
            
            $num_af_row = update_job_material_issue_header_totals($type, $return_trans_no, $return_row_state);
                if (! ($num_af_row == 1)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$type]." header total.");
                }
             
            if ($process === true && $approval_status == AS_APPROVED) {
                // process job material issue line 
                $prs_msg = process_job_manual_cost_return($ret_hd['trans_no'], $ret_hd['type'], $ret_hd['tran_date'], $ret_hd['project_id']);
                    if ($prs_msg['success'] !== true) {
                        cancel_transaction();

                        return array("success" => false, "message" => $prs_msg['message']);
                    }
            }
            
            // save job manual cost returned alloc and returned qty
            $sv_is_rt_qty = update_job_material_issue_all_lines_returned_alloc_returned($issue_type, $issue_trans_no, $type);
                if ($sv_is_rt_qty['success'] !== true) {
                    cancel_transaction();
                    
                    return $sv_is_rt_qty;
                }
                
            // job manual cost header update
            $partially = get_job_material_issue_partially_returned_lines($issue_type, $issue_trans_no);
                if ($iss_hd['approval_status'] == AS_CLOSED && db_num_rows($partially) > 0) {
                    $ap_msg_2 = direct_update_document_status($issue_type, $issue_trans_no, AS_APPROVED, $iss_row_state);     
                        if ($ap_msg_2['success'] === false ) {
                            cancel_transaction();
                            
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$issue_type]." trans #$issue_trans_no approval status.");
                        }
                        
                    $iss_row_state = db_new_row_state($iss_row_state);
                } elseif ($iss_hd['approval_status'] == AS_APPROVED && db_num_rows($partially) == 0) {
                    $ap_msg_2 = direct_update_document_status($issue_type, $issue_trans_no, AS_CLOSED, $iss_row_state);     
                        if ($ap_msg_2['success'] === false) {
                            cancel_transaction();
                            
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$issue_type]." trans #$issue_trans_no approval status.");
                        }
                        
                    $iss_row_state = db_new_row_state($iss_row_state);
                }
                
            $req_af = update_job_material_issue_row_state($issue_type, $issue_trans_no, $iss_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$issue_type]." record #$jmc_no row state.");
                }
                
        commit_transaction();
                
            if ($process === true) {
                set_session_variable('jmc_return_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 can_reject_back_to_originator_job_manual_cost_return($jmc_no, $jmcr_no, $trans_tp_name, $reject) {
    global $systypes_array;
    
    $iss_hd = get_job_material_issue_header_record($jmc_no);
        if (is_array($iss_hd)) {
            if ($iss_hd['type'] != ST_JOB_MANUAL_COST) {
                return array("success" => false, "message" => "Invalid transaction type.");
            }
        } else {
            return array("success" => false, "message" => $systypes_array[ST_JOB_MANUAL_COST]." #$jmc_no has been deleted by another user.");
        }
    
    $hd_row = get_job_material_issue_header_record($jmcr_no);
        if (! is_array($hd_row)) {
            return array("success" => false, "message" => "Could not find $trans_tp_name #$jmc_no.");
        }

        if (! isset($hd_row['type']) || $hd_row['type'] != ST_JOB_MANUAL_COST_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_JOB_MANUAL_COST_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" => "", "iss_hd_row" => $iss_hd, "hd_row" => $hd_row);
}

function reject_job_manual_cost_return($jmc_no, $jmcr_no) {
    global $systypes_array;
    
    $issue_type = ST_JOB_MANUAL_COST;
    $type = ST_JOB_MANUAL_COST_RETURN;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_job_manual_cost_return($jmc_no, $jmcr_no, $trans_tp_name, true);
        if ($cn_rej["success"] !== true) { 
            return $cn_rej;
        } 
        
        $iss_hd_row = $cn_rej["iss_hd_row"];
            $iss_row_state = $iss_hd_row['row_state'];
            $issue_trans_no = $iss_hd_row["trans_no"];
        
        $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 job manual cost returned alloc and returned qty
            $sv_is_rt_qty = update_job_material_issue_all_lines_returned_alloc_returned($issue_type, $issue_trans_no, $return_trans_no);
                if ($sv_is_rt_qty['success'] !== true) {
                    cancel_transaction();
                    return $sv_is_rt_qty;
                }
                
            // job manual cost header update
            $partially = get_job_material_issue_partially_returned_lines($issue_type, $issue_trans_no);
                if ($iss_hd_row['approval_status'] == AS_CLOSED && db_num_rows($partially) > 0) {
                    $ap_msg_2 = direct_update_document_status($issue_type, $issue_trans_no, AS_APPROVED, $iss_row_state);     
                        if ($ap_msg_2['success'] === false ) {
                            cancel_transaction();
                            
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$issue_type]." trans #$issue_trans_no approval status.");
                        }
                        
                    $iss_row_state = db_new_row_state($iss_row_state);
                } 
                
            $req_af = update_job_material_issue_row_state($issue_type, $issue_trans_no, $iss_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$issue_type]." record #$jmc_no row state.");
                }
            
        commit_transaction();

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

function back_to_originator_job_manual_cost_return($jmc_no, $jmcr_no) {
    global $systypes_array;
    
    $type = ST_JOB_MANUAL_COST_RETURN;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_job_manual_cost_return($jmc_no, $jmcr_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('jmcr_bo_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&BackedOrgID=$trans_no"); 
}

function clear_job_manual_cost_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_job_manual_cost_return($trans_no, $type, $tran_date_, $project_id) {
    // stock move and lot move
    $result = get_job_material_issue_details($trans_no, $type);
        while ($row = db_fetch($result)) {
            $stock_control_method = $row['stock_control_method'];

            // stock move
            $stk_mv_msg = process_job_manual_cost_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, $row['trans_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;
                    }
            }
        }

        // budgets update 
        $jmc_details_array = $b = array();
        $result_2 = get_job_material_issue_details($trans_no, $type);
            while ($row = db_fetch($result_2)) {
                $qty = $row['qty'];
                $b['row_id'] = $row['trans_id'];
                $b['stock_id'] = $row['stock_id'];
                $b['task_id'] = $row['task_id'];
                $b['requested_qty'] = $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;

                $jmc_details_array[] = $b;
            }

            $jmc_tasks_summary = calculate_task_remaining_totals($jmc_details_array);
            $created_by = $_SESSION['wa_current_user']->user;

            $mtrec_msg = remove_costs_from_tasks($type, $trans_no, $jmc_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_job_manual_cost_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"]);
    $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["loc_code"], $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["loc_code"], $tran_date_, $row["reference"], $qty, $standard_cost, 0, $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 stock movement record for rec id : ".$row["trans_id"]);
        }
        
        return array("success" => true, 'trans_no' => $trans_no, "message" => "");            
}

function view_job_manual_cost_return_header($type, $trans_no) {
    global $approval_statuses;
    
    $row = get_job_material_issue_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=80%");

            table_section(1, "50%");
                $jo_id = $row['jo_id'];
                $re_hd = get_job_material_issue_header_record($row['jmr_no']);
                label_row("JMC. Trans #:", get_inventory_trans_view_str($re_hd['type'], $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(_("Location:"), $row['location_name'], "class='tableheader2'");
                label_row(_("Total:"), $row['total'], "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_job_manual_cost_return_details($type, $trans_no) {
    global $daily_item_types_array;
    
    $view_tp = ST_LOT_ALLOCATION;
    $hd_row = get_job_material_issue_header_record_type_trans_no($type, $trans_no);
        if (in_array($hd_row['approval_status'], array(AS_APPROVED, 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=98%");

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

        $k = $total_cost = 0; 
            $result = get_job_material_issue_details($trans_no, $type);      
                while ($row = db_fetch($result)) {
                    $dec = 2;
                    
                    alt_table_row_color($k);

                        $trans_id = $row['trans_id'];
                        
                        if ($row['stock_control_method'] == SKCM_LOTS) {
                            $params = "type=".ST_JOB_MANUAL_COST_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($row['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(get_stock_item_formatted_name($row["stock_id"]));  
                            
                            $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_JOB_MANUAL_COST_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=center');
                        } else {
                            qty_cell($row["tran_qty"], false, $dec);
                        }
                        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('');
                            }
                        $line_cost = $tran_unit_cost * $row["tran_qty"];
                            if ($line_cost > 0) {
                                qty_cell($line_cost, false, $dec);
                            } else {
                                label_cell('');
                            }
                            
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();    
                    
                    $total_cost += $line_cost;
                }
                
                start_row();
                    label_cell(text_bold('Total'), 'align=right colspan=8');
                    if ($total_cost > 0) {
                        qty_cell($total_cost, true, 2);
                    } else {
                        label_cell('');
                    }
                    label_cell('', 'colspan=2');
                end_row();

    end_table(2);
}

?>