<?php

function display_job_material_requisition_header_details_for_jm_issue_req($jmr_no, $jmi_no) {
    global $approval_statuses, $systypes_array;
    
    $req_hd_row = get_job_material_requisition_header($jmr_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_JOB_MATERIAL_REQ]." Header");
    
        $jm_req_trans_no = $req_hd_row['trans_no'];
        if (! isset($_POST['location']) && ! ($jmi_no > 0)) {
            $_POST['location'] = $req_hd_row['loc_code'];
        }
    
    start_outer_table(TABLESTYLE2, "width=65%"); // outer table
        start_table(TABLESTYLE2);  
            table_section(1, "27%");
                $jo_id = $req_hd_row['jo_id'];
                label_row("Job Card #:", get_service_trans_view_str(ST_JOB_ORDER, $jo_id));
                label_row("Req. Trans #:", get_inventory_trans_view_str($req_hd_row['type'], $req_hd_row['trans_no']));  
                $iss_row = get_job_material_requisition_header_record($jmi_no);
                    if (is_array($iss_row)) {
                        label_row("Issue Trans #:", $iss_row['trans_no']);  
                    }

            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("Location:", $req_hd_row['location_name']);  
                label_row("Requestor:", $req_hd_row['requestor_name']);  
                $s = get_project_trans_view_str(ST_APPROVAL_LOG, $jm_req_trans_no."&source_type_id=".ST_JOB_MATERIAL_REQ, "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_job_material_issue_requisition_header($jmi_no, $req_hd_row) {
    global $Refs, $systypes_array;
    
    display_heading($systypes_array[ST_JOB_MATERIAL_ISSUE_REQ]." Header");
    
        $type = ST_JOB_MATERIAL_ISSUE_REQ;
        $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_job_material_requisition_header($jmi_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'];
            }

        } 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");
                        if (is_array($header)) {
                            label_row("Issuing Location:", $header['location_name']); 
                            hidden('location', $_POST['location']);
                        } else {
                            locations_list_row("Issuing Location:", 'location', null, '', false); 
                        }

                    table_section(2, "50%");
                        
                        textarea_row("Comment:", 'comments', null, 35, 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_material_issue_requisition_details($jmr_no, $jmi_no) { 
    global $Ajax, $daily_item_types_array, $systypes_array;
    
    display_heading($systypes_array[ST_JOB_MATERIAL_ISSUE_REQ]." Details");
    
    $req_trans_no = $issue_req_trans_no = 0;
    $req_header = get_job_material_requisition_header_record($jmr_no);
        if (is_array($req_header)) {
            $req_trans_no = $req_header['trans_no'];
        } 
        
    $issue_hd_row = get_job_material_requisition_header_record($jmi_no);
        if (is_array($issue_hd_row)) {
            $issue_req_trans_no = $issue_hd_row['trans_no'];
        } 
        
    $units_array = build_all_item_units_array();
    
    $Ajax->activate('jmi_req_details');
    div_start('jmi_req_details');
    
        start_table(TABLESTYLE, "width=100%");

            $th = array(_("Req. Line"), _("Iss.Req Line"), _("Item Type"), _("Item"), _("Req. Unit"), _("Req. Qty"), _('Issue Req. Qty'), _('Issue Req. Alloc Qty'), 
                        _('Issued Qty'), _('Issued Alloc'), _('DPR Qty'), _('Total Qty'), _('Issue Unit'), _('Issue Qty'), _('Site'), _('Line Comment'), _(""));  
                
            table_header($th);

            $k = 0; //row colour counter
                $result = get_job_material_req_with_job_material_issue_req_details($req_trans_no, $issue_req_trans_no);      
                    while ($row = db_fetch($result)) {
                        $id = $row['trans_id'];
                        $issue_req_line_id = $row['issue_req_line_id'];
                        $req_conversion_factor = $row['conversion_factor'];
                        
                        alt_table_row_color($k);

                            label_cell(text_bold($id), 'align=center');
                            label_cell($issue_req_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($row["unit_name"]);
                            
                            $dec = 4; // get_qty_dec($row["stock_id"]);
                            qty_cell($row["tran_qty"], true, $dec);
                            qty_cell($row["issue_req_qty"] / $req_conversion_factor, false, $dec);
                            qty_cell($row["issue_req_alloc_qty"] / $req_conversion_factor, false, $dec);
                            $actual_issued = $row["issued_quantity"] - $row["returned_quantity"];
                            qty_cell(($actual_issued) / $req_conversion_factor, false, $dec);
                            qty_cell($row["issued_alloc"] / $req_conversion_factor, false, $dec);
                            qty_cell($row["dpr_quantity"] / $req_conversion_factor, false, $dec);
                            qty_cell(($actual_issued + $row["issued_alloc"] + $row["dpr_quantity"]) / $req_conversion_factor, true, $dec);
                            
                            if (! isset($_POST["issue_req_tran_unit_$id"])) {
                                if ($issue_req_line_id > 0) {
                                    $_POST["issue_req_tran_unit_$id"] = $row["issue_req_tran_unit"];
                                } else {
                                    $_POST["issue_req_tran_unit_$id"] = $row["tran_unit"];
                                }
                            }
                            
                            if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                                units_list_cells('', "issue_req_tran_unit_$id", $row['stock_id'], null, '', true);
                            } else {
                                custom_values_list_cells('', "issue_req_tran_unit_$id", $units_array, null, '', true);   
                            }
                            
                            if (! isset($_POST["issue_req_tran_qty_$id"])) {
                                if ($issue_req_line_id > 0) {
                                    $_POST["issue_req_tran_qty_$id"] = $row["issue_req_tran_qty"];
                                } else {
                                    set_job_material_issue_requisition_remain_issuable_qty($id, $row, $dec);
                                }
                            } else {
                                if (list_updated("issue_req_tran_unit_$id")) {
                                    set_job_material_issue_requisition_remain_issuable_qty($id, $row, $dec);
                                }
                            }
                            amount_cells("", "issue_req_tran_qty_$id", null, null, null, $dec);
                            
                            label_cell($row["site_description"]);          
                            label_cell(nl2br($row["line_comment"])); 
                            
                            if (! isset($_POST["checked_$id"]) && $issue_req_line_id > 0) {
                                $_POST["checked_$id"] = 1;
                            } 
                            check_cells(null, "checked_$id", null, false, false, 'align=center');

                        end_row();        
                    }

        end_table(3);
    
    div_end();
}

function set_job_material_issue_requisition_remain_issuable_qty($id, $row, $dec=2) {
    $convesion_factor = 1;
    get_convertion_factor2($row['stock_id'], $_POST["issue_req_tran_unit_$id"], $convesion_factor);

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

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

function can_save_job_material_issue_requisition_header($jmr_no, $jmi_no) {
    global $Refs, $systypes_array;
    
    $req_hd = get_job_material_requisition_header_record($jmr_no);
        if (is_array($req_hd)) {
            if ($req_hd['type'] != ST_JOB_MATERIAL_REQ) {
                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_JOB_MATERIAL_REQ]." #$jmr_no is not approved.");
            }
        } else {
            return array("success" => false, "message" => $systypes_array[ST_JOB_MATERIAL_REQ]." #$jmr_no has been deleted by another user.");
        }
    
    $trans_no = $issue_row_state = 0;
    $req_row_state = $req_hd['row_state'];
    $header = get_job_material_requisition_header_record($jmi_no);
    
    if (($jmi_no > 0) && ! is_array($header)) {
        return array("success" => false, "message" => $systypes_array[ST_JOB_MATERIAL_ISSUE_REQ]." #$jmi_no has been deleted by another user.");
    }
      
    if ($jmi_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_JOB_MATERIAL_ISSUE_REQ, $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']; $issue_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'], ST_JOB_MATERIAL_ISSUE_REQ, $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" => "Issuing location cannot empty.");
    }
    
    return array("success" => true, 'req_row_state' => $req_row_state, 'issue_row_state' => $issue_row_state, "message" => "");    
}

function can_save_job_material_issue_requisition_lines($req_trans_no, $issue_req_trans_no) {
    global $systypes_array;
    
    $result = get_job_material_req_with_job_material_issue_req_details($req_trans_no, $issue_req_trans_no);  
        if (! (db_num_rows($result) > 0)) {
            return array('success' => false, 'message' => "No source ".$systypes_array[ST_JOB_MATERIAL_REQ]." found.");
        }
        
        while ($row = db_fetch($result)) {
            $id = $row['trans_id'];
            $issue_req_line_id = $row['issue_req_line_id'];
            $stock_id = $row['stock_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                $item_type = $row['item_type'];
                
                $issue_req_tran_unit = $_POST["issue_req_tran_unit_$id"];
                $issue_req_tran_qty = input_num("issue_req_tran_qty_$id");
                
                $convesion_factor = 1;
                
                // can save job material issue line
                $cn_sv_ln = can_save_job_material_issue_requisition_line($stock_id, $item_type, $issue_req_tran_unit, $issue_req_tran_qty, $convesion_factor, 
                                                                         $issue_req_line_id, $id, $row);
                    if ($cn_sv_ln['success'] !== true) {
                        return array("success" => false, "message" => $cn_sv_ln['message']);
                    }
            } 
        }
        
        return array("success" => true, "message" => "");
}

function can_save_job_material_issue_requisition_line($stock_id, $item_type, $issue_req_tran_unit, $issue_req_tran_qty, $convesion_factor, $issue_req_line_id, $id, $row) {
    $type = ST_JOB_MATERIAL_ISSUE_REQ;
    
        if ($item_type == NSIT_NON_STOCK_ITEM || $item_type == NSIT_STOCK_ITEM) {
            if ($issue_req_tran_unit == -1) {
                return array("success" => false, "focus_to" => "issue_req_tran_unit_$id", "message" => "Req. Line #$id Please select a tran unit.");  
            }
        } elseif ($item_type == NSIT_COMMENT) {
            if ($issue_req_tran_unit == '0') {
                return array("success" => false, "focus_to" => "issue_req_tran_unit_$id", "message" => "Req. Line #$id  Please select an unit.");  
            }
        }

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

        get_convertion_factor2($stock_id, $issue_req_tran_unit, $convesion_factor);
        
        // check whether total requested qty is exceeded
        $rem_trn_qty_ary = get_job_material_requisition_line_remain_qty_array($type, $row['type'], $row['trans_no'], $row['qty'], $id, $issue_req_tran_qty, $convesion_factor, 
                                                                              $issue_req_line_id);
        $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) {
                $exceeded_trn_qty = abs($new_rem_trn_qty_);
                return array('success' => false, "focus_to" => "issue_req_tran_qty_$id", 
                             'message' => "Req. Line #$id remain issuable tran qty $old_rem_trn_qty is exceeded by $exceeded_trn_qty in tran unit.");
            }
                
        return array("success" => true, "focus_to" => "", "message" => ""); 
}

function save_job_material_issue_requisition_lines($req_trans_no, $issue_req_trans_no) {
    global $systypes_array;
    $type = ST_JOB_MATERIAL_ISSUE_REQ;
    
    $no_selected_recs = 0;
    $result = get_job_material_req_with_job_material_issue_req_details($req_trans_no, $issue_req_trans_no);  
    
    $issue_lines_count = get_job_material_requisition_details_lines_count($issue_req_trans_no, $type);
        if ($issue_lines_count > 0) {
            $del_af_rows = delete_job_material_requisition_detail_lines($type, $issue_req_trans_no);
                if ($del_af_rows != $issue_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'];
            $issue_req_line_id = $row['issue_req_line_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                
                $issue_req_tran_unit = $_POST["issue_req_tran_unit_$id"];
                $issue_req_tran_qty = input_num("issue_req_tran_qty_$id");
                
                $convesion_factor = 1;
                get_convertion_factor2($row['stock_id'], $issue_req_tran_unit, $convesion_factor);
                $qty = $issue_req_tran_qty * $convesion_factor;
                
                $standard_cost = $row['standard_cost'];
                if ($row['item_type'] == NSIT_STOCK_ITEM) {
                    $standard_cost = get_standard_cost($row['stock_id']);
                }
                
                // save job material issue requisition line
                $in_id = insert_job_material_requisition_line($issue_req_trans_no, $type, $row['stock_id'], $row['item_type'], $row['item_description'], $issue_req_tran_unit, 
                                                              $issue_req_tran_qty, $qty, $convesion_factor, $standard_cost, $row['project_site_id'], $row['line_comment'], 
                                                              $row['task_id'], $row['type'], $row['trans_no'], $id, $issue_req_line_id);
                
                    if (! ($in_id > 0)) {
                        cancel_transaction();
                        return array("success" => false, "message" => "Could not insert ".$systypes_array[$type]." line.");
                    }
                    
                $no_selected_recs++;
            } 
        }
        
        if (! ($no_selected_recs > 0)) {
            cancel_transaction();
            return array("success" => false, "message" => "Please select at least one record before saving.");  
        }
        
        return array("success" => true, "message" => "");  
}

function save_job_material_issue_requisition_header(&$jmi_no, &$issue_req_trans_no, $type, $project_id, $loc_code, $tran_date_, &$issue_row_state, $jo_id, $source_type, 
                                                    $source_trans_no) {
    global $systypes_array;
    
    $af_no = write_job_material_requisition_header($type, $issue_req_trans_no, $jmi_no, $_POST['reference'], $project_id, $loc_code, $_POST['comments'], $tran_date_, $jo_id, 
                                                   $source_type, $source_trans_no, $issue_row_state);
    
        if ($af_no > 0) {
            return array("success" => true, "message" => $systypes_array[$type]." header record #$jmi_no has been saved.");
        } else {
            return array("success" => false, "message" => "Could not be saved ".$systypes_array[$type].' header.');
        }
}

function save_job_material_issue_requisitions(&$jmr_no, &$jmi_no, $process=false) {
    global $systypes_array;
    
    $req_type = ST_JOB_MATERIAL_REQ; $type = ST_JOB_MATERIAL_ISSUE_REQ;
    
    $cn_sv_hd = can_save_job_material_issue_requisition_header($jmr_no, $jmi_no);   
        if ($cn_sv_hd["success"] !== true) {          
            return $cn_sv_hd;
        }
        
        $req_row_state = $cn_sv_hd['req_row_state']; $issue_row_state = $cn_sv_hd['issue_row_state'];
        
    $req_header = get_job_material_requisition_header_record($jmr_no);
        $req_trans_no = $req_header['trans_no']; $project_id = $req_header['project_id']; $jo_id = $req_header['jo_id'];
        
    $issue_req_trans_no = 0; 
    $issue_hd_row = get_job_material_requisition_header_record($jmi_no);
        if (is_array($issue_hd_row)) {
            $issue_req_trans_no = $issue_hd_row['trans_no']; 
        }
        
    $cn_sv_line = can_save_job_material_issue_requisition_lines($req_trans_no, $issue_req_trans_no);   
        if ($cn_sv_line["success"] !== true) {          
            return $cn_sv_line;
        }
        
        begin_transaction();

            $hd_msg = save_job_material_issue_requisition_header($jmi_no, $issue_req_trans_no, $type, $project_id, $_POST['location'], $_POST['tran_date'], $issue_row_state, 
                                                                 $jo_id, $req_type, $req_trans_no);
                if ($hd_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $hd_msg['message']);
                }
                
            $sv_ln_msg = save_job_material_issue_requisition_lines($req_trans_no, $issue_req_trans_no);
                if ($sv_ln_msg['success'] !== true) {
                    cancel_transaction();
                    return $sv_ln_msg;       
                }
                
            if ($process === true) {
                $ap_msg = approve_job_material_issue_requisition($jmi_no);     
                    if ($ap_msg['success'] === false ) {
                        cancel_transaction();
                        return $ap_msg;
                    }
            }
            
            // save job material_req issue_req_qty and issue_req_alloc_qty => this shold be called after lines saving becouse it checks with approval status
            $sv_is_rt_qty = save_job_material_requisition_lines_issue_req_qty_total($req_type, $req_trans_no, $type);
                if ($sv_is_rt_qty['success'] !== true) {
                    cancel_transaction();
                    return $sv_is_rt_qty;
                }
                
            $fully_issue_requested = check_all_job_material_requisition_lines_fully_issue_requested($req_type, $req_trans_no);
                if ($fully_issue_requested === true) {
                    $ds_msg = direct_update_document_status($req_type, $req_trans_no, AS_COMPLETED, $req_row_state);     
                        if ($ds_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." approval status.");
                        }

                        $req_row_state = db_new_row_state($req_row_state);
                } else {
                    if ($req_header['approval_status'] == AS_COMPLETED) {
                        $ds_msg = direct_update_document_status($req_type, $req_trans_no, AS_APPROVED, $req_row_state);     
                            if ($ds_msg['success'] === false ) {
                                cancel_transaction();
                                return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." approval status.");
                            }

                            $req_row_state = db_new_row_state($req_row_state);
                    }
                }

            $req_af = update_job_material_requisition_row_state($jmr_no, $req_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." record #$jmr_no row state.");
                }
                
        commit_transaction();
            
            if ($process === true) {
                set_session_variable('jmir_messages', $ap_msg['message']);
                meta_forward($_SERVER['PHP_SELF'], "type=$type&ProcessedID=$issue_req_trans_no"); 
            } else {
                return array("success" => true, "message" => $systypes_array[$type]." Trans #$issue_req_trans_no has been saved.");
            }
}

function approve_job_material_issue_requisition($jmi_no) {
    $current_user_id = $_SESSION['wa_current_user']->user;
    $task_costs = 0;
    
    $header = get_job_material_requisition_header_record($jmi_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_job_material_issue_requisition($jmr_no, $jmi_no, $trans_tp_name, $reject) {
    global $systypes_array;
    
    $req_hd = get_job_material_requisition_header_record($jmr_no);
        if (is_array($req_hd)) {
            if ($req_hd['type'] != ST_JOB_MATERIAL_REQ) {
                return array("success" => false, "message" => "Invalid transaction type.");
            }
        } else {
            return array("success" => false, "message" => $systypes_array[ST_JOB_MATERIAL_REQ]." #$jmr_no has been deleted by another user.");
        }
    
    $hd_row = get_job_material_requisition_header_record($jmi_no);
    
        if (! is_array($hd_row)) {
            return array("success" => false, "message" => "Could not find $trans_tp_name #$jmi_no.");
        }

        if (! isset($hd_row['type']) || $hd_row['type'] != ST_JOB_MATERIAL_ISSUE_REQ) {
            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_MATERIAL_ISSUE_REQ, $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_job_material_issue_requisition($jmr_no, $jmi_no) {
    global $systypes_array;
    
    $req_type = ST_JOB_MATERIAL_REQ;
    $type = ST_JOB_MATERIAL_ISSUE_REQ;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_job_material_issue_requisition($jmr_no, $jmi_no, $trans_tp_name, true);
        if ($cn_rej["success"] !== true) { 
            return $cn_rej;
        } 
        
        $req_hd_row = $cn_rej["req_hd_row"];
            $req_row_state = $req_hd_row['row_state'];
            $req_trans_no = $req_hd_row["trans_no"];
            $jm_req_ap = $req_hd_row["approval_status"];
        
        $hd_row = $cn_rej["hd_row"];
            $trans_no = $hd_row["trans_no"];
        
        begin_transaction();
        
            $rj_msg = reject_document($type, $trans_no, $hd_row['project_id'], $hd_row['next_approval_group_id'], $_SESSION['wa_current_user']->user, $hd_row['row_state']);
                if ($rj_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $rj_msg['message']);
                }
                
            // save job material_req issue_req_qty and issue_req_alloc_qty => this shold be called after lines saving becouse it checks with approval status
            $sv_is_rt_qty = save_job_material_requisition_lines_issue_req_qty_total($req_type, $req_trans_no, $type);
                if ($sv_is_rt_qty['success'] !== true) {
                    cancel_transaction();
                    return $sv_is_rt_qty;
                }
                
            $fully_issue_requested = check_all_job_material_requisition_lines_fully_issue_requested($req_type, $req_trans_no);
                if ($fully_issue_requested === true) {
                    $ds_msg = direct_update_document_status($req_type, $req_trans_no, AS_COMPLETED, $req_row_state);     
                        if ($ds_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." approval status.");
                        }

                        $req_row_state = db_new_row_state($req_row_state);
                } else {
                    if ($jm_req_ap == AS_COMPLETED) {
                        $ds_msg = direct_update_document_status($req_type, $req_trans_no, AS_APPROVED, $req_row_state);     
                            if ($ds_msg['success'] === false ) {
                                cancel_transaction();
                                return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." approval status.");
                            }

                            $req_row_state = db_new_row_state($req_row_state);
                    }
                }

            $req_af = update_job_material_requisition_row_state($jmr_no, $req_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." record #$jmr_no row state.");
                }
            
        commit_transaction();

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

function back_to_originator_job_material_issue_requisition($jmr_no, $jmi_no) {
    global $systypes_array;
    
    $type = ST_JOB_MATERIAL_ISSUE_REQ;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_job_material_issue_requisition($jmr_no, $jmi_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('jmir_bo_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&BackedOrgID=$trans_no"); 
}

function view_job_material_issue_requisition_header($type, $trans_no) {
    global $approval_statuses;
    
    $row = get_job_material_requisition_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=70%");

            table_section(1, "50%");
                $jo_id = $row['jo_id'];
                label_row("Req. Trans #:", get_inventory_trans_view_str($row['source_type'], $row['source_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'");

            table_section(2, "50%");
                label_row(_("Reference:"), $row['reference'], "class='tableheader2'");
                label_row(_("Date:"), sql2date($row['tran_date']), "class='tableheader2'");
                label_row(_("Location:"), $row['location_name'], "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);
        }
        
        return $row['id'];
}

function view_job_material_isuue_requisition_details($type, $trans_no) {
    global $daily_item_types_array;
    
    $hd_row = get_job_material_requisition_header_record_type_trans_no($type, $trans_no);
    
    $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=99%");

        $th = array(_("ID"), _("JM Req.Ln"), _("Item Type"), _("Description"), _("Tran Unit"), _("Tran Qty"), _("Issued"), _("Issue.Alloc"), _("Returned"), _("Return.Alloc"), 
                    _("Exact Issued<br>(Issued-Returned)"), _("Remain Qty-<br>(Issued+Issue.Alloc-Returned)"), _('Budget'), _('Project Site'), _('Comment'));  
        table_header($th);

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

                        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 (in_array($row['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                            label_cell($row["stock_id"]." - ".$row["item_description"]);  
                        } else {
                            label_cell($row["item_description"]);
                        }
                        label_cell($row["unit_name"]);
                        qty_cell($row["tran_qty"], false, 4);
                        
                        $conversion_factor = $row['conversion_factor'];
                        $issued_quantity = $row["issued_quantity"];
                        qty_cell($issued_quantity / $conversion_factor, false, 4);
                        qty_cell($row["issued_alloc"] / $conversion_factor, false, 4);
                        
                        qty_cell($row["returned_quantity"] / $conversion_factor, false, 4);
                        qty_cell($row["returned_alloc"] / $conversion_factor, false, 4);
                        
                        $exact_issued = $issued_quantity - $row["returned_quantity"];
                        qty_cell($exact_issued / $conversion_factor, false, 4);
                        
                        $total_issued_issued_alloc = $exact_issued + $row["issued_alloc"];
                        
                        $remain = $row["tran_qty"] - ($total_issued_issued_alloc / $conversion_factor);
                        qty_cell($remain / $conversion_factor, false, 4);
                        
                        if ($row['item_type'] == NSIT_COMMENT) {
                            label_cell('No budget required');
                        } else {
                            label_cell($row["task_description"]);
                        }
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(2);
}

function view_job_material_issue_requisition_headers_by_source($source_trans_no, $source_type) {
    $result = get_job_material_requisition_headers_by_sources($source_type, $source_trans_no);
        if (! (db_num_rows($result) > 0)) {
            return;
        }
        
    $req_hd = get_job_material_requisition_header_record_type_trans_no($source_type, $source_trans_no);
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($req_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[ST_JOB_MATERIAL_ISSUE_REQ]." headers");
    
        start_table(TABLESTYLE, "width=50%");

            $th = array(_("Trans #"), _("Trans Date"), _("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['location_name']);
                        label_cell($approval_statuses[$row['approval_status']], 'align=center');
                    end_row();        
                }

        end_table(2);
}

function view_job_material_issue_requisition_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"), _("Location"), _("Approval Status"));  
        table_header($th);

        $k = 0; //row colour counter
            $result = get_job_material_requisition_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['location_name']);
                        label_cell($approval_statuses[$row['approval_status']], 'align=center');

                    end_row();        
                }

    end_table(2);
}

?>