<?php

function display_material_list_header($ml_no) {
    global $Refs;
    
    $trans_no = 0;
    if (isset($_POST['jo_id']) || isset($_POST['ModifyML_No'])) {
        $type = ST_MATERIAL_LIST;
    }
    
        if ($ml_no > 0) {

            $header = get_material_list_header($ml_no);
            $_POST['project_id'] = $header['project_id'];
            hidden('project_id', $header['project_id']);

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

            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['project_description'])) {
                $_POST['project_description'] = $header['project_description'];
            }

            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 (isset($_POST['jo_id']) && $_POST['jo_id'] > 0) {
                            $jo_id = $_POST['jo_id'];
                            label_row("Job Card:", get_service_trans_view_str(ST_JOB_ORDER, $jo_id));
                        }
                        
                        if ($ml_no > 0) {
                            $pd_request = get_material_list_header($ml_no);
                            label_row("Trans #:", get_inventory_trans_view_str($pd_request['type'], $pd_request['trans_no']));  
                            
                            $reference = $pd_request['reference'];            
                            text_row("Reference:", 'reference', $reference, null, null);            
                        } else {            
                            text_row("Reference:", 'reference', $Refs->get_next($type), null, null);   
                        }

                        if ($ml_no > 0) {
                            label_row("Project:", get_project_formatted_name($_POST['project_id']));   
                        } elseif (isset($_POST['jo_id']) && $_POST['jo_id'] > 0) {
                            $jo_pro = get_job_order_department_approval_project($_POST['jo_id']);
                            $_POST['project_id'] = $jo_pro['project_id'];
                            hidden('project_id', $jo_pro['project_id']);
                            label_row("Project:", get_project_formatted_name($jo_pro['project_id']));   
                        } else {
                            $_POST['project_id'] = 0;
                            hidden('project_id', 0);
                        }

                    table_section(2, "50%");
                        
                        date_row("Date:", "tran_date");
                        
                        locations_list_row("Location:", 'location', null, '', false);  
                        
                        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_material_list_details($ml_no, $selected_id, &$Mode) { 
    global $Ajax, $daily_item_types_array, $systypes_array;
    
    display_heading($systypes_array[ST_MATERIAL_LIST]." Lines");
    
    $trans_no = $type = $approval_status = -1;
    $header = get_material_list_header_record($ml_no);
        if (is_array($header)) {
            $trans_no = $header['trans_no'];
            $type = $header['type'];
            $approval_status = $header['approval_status'];
        } 
    
    $Ajax->activate('nsit_details');
    div_start('nsit_details');
    
        start_table(TABLESTYLE, "width=98%");

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

            $k = 0; //row colour counter
                $result = get_material_list_details($trans_no, $type);      
                    while ($row = db_fetch($result)) {
                        
                        if ($selected_id != $row['trans_id'] || $Mode == 'Delete') {
                            
                            alt_table_row_color($k);

                                label_cell($row['trans_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 = get_qty_dec($row["stock_id"]);
                                qty_cell($row["tran_qty"], false, $dec);

                                $tran_unit_cost = $row["standard_cost"] * $row["conversion_factor"];
                                    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"]));          

                                if (! in_array($approval_status, array(AS_APPROVED, AS_COMPLETED))) {
                                    edit_button_cell("Edit".$row["trans_id"], _("Edit"));    
                                    delete_button_cell("Delete".$row["trans_id"], _("Delete"));  
                                } else {
                                    label_cell(''); label_cell('');
                                }

                            end_row();  
                            
                        } else {
                            display_material_list_details_edit_controls($selected_id, $Mode);
                        }
                    }

                    if (! ($selected_id > 0) || $Mode == 'Delete') {
                        display_material_list_details_edit_controls($selected_id, $Mode);
                    }

        end_table(2);
    
    div_end();
}

function display_material_list_details_edit_controls($selected_id, &$Mode) {
    global $Ajax, $daily_item_types_array;
    $dec = 2;

    if ($selected_id > 0 && $Mode != 'Delete') {   
        $row = get_material_list_details_record($selected_id); 
            if ($Mode == 'Edit') {
                $_POST['item_type'] = $row["item_type"];
                $_POST['stock_id'] = $row["stock_id"];
                $_POST['item_description'] = $row["item_description"];
                $_POST['tran_unit'] = $row["tran_unit"];
                $_POST['tran_qty'] = $row["tran_qty"];
                $_POST['site_id'] = $row["project_site_id"];
                $_POST['item_cost'] = $row["standard_cost"] * $row["conversion_factor"];
                $_POST['line_comment'] = $row["line_comment"];
            }
            
            if (! (strlen($_POST['stock_id']) > 0)) {
                $_POST['stock_id'] = $row["stock_id"];
            }
            if ($_POST['tran_unit'] == -1) {
                $_POST['tran_unit'] = $row["tran_unit"];
            }
            if (! ($_POST['tran_qty'] > 0)) {
                $_POST['tran_qty'] = $row["tran_qty"];
            }
            if (! ($_POST['item_cost'] > 0)) {
                $_POST['item_cost'] = $row["standard_cost"] * $row["conversion_factor"];
            }
            
            if (! (strlen($_POST['line_comment']) > 0)) {
                $_POST['line_comment'] = $row["line_comment"];
            }
    }
  
    echo "<td colspan=8>";
        $Ajax->activate("control_items");    
        div_start('control_items');
            start_outer_table(TABLESTYLE2);
            
                table_section(1);

                    if ($selected_id > 0 && $Mode != 'Delete') {  
                        label_row('Rec Id:', $selected_id);
                        label_row('Item Type:', $daily_item_types_array[$row['item_type']]);
                        $_POST['item_type'] = $row['item_type'];
                        hidden('item_type', $row['item_type']);
                    } else {
                        custom_values_list_row('Item Type:', 'item_type', $daily_item_types_array, null, '', true);
                    }

                    if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM) {

                        if ($selected_id > 0 && $Mode != 'Delete') {  
                            label_row('Item:', $_POST['stock_id']);
                            hidden('stock_id', $_POST['stock_id']);
                            text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                        } else {
                            label_row('Stock Item:', non_stock_items_list('stock_id', null, false, true));
                            $itm = get_item($_POST['stock_id']);
                                if (is_array($itm)) {
                                    hidden('item_description', $itm['description']);
                                } else {
                                    hidden('item_description', '');
                                }
                        }

                        units_list_row('Unit:', 'tran_unit', $_POST['stock_id'], null, '');
                        $dec = get_qty_dec($_POST["stock_id"]);

                    } elseif ($_POST['item_type'] == NSIT_STOCK_ITEM) {

                        if ($selected_id > 0 && $Mode != 'Delete') {  
                            label_row('Stock Item:', $_POST['stock_id']);
                            hidden('stock_id', $_POST['stock_id']);
                            text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                        } else {
                            label_row('Stock Item:', stock_and_manufacture_items_list('stock_id', null, false, true));
                            $itm = get_item($_POST['stock_id']);
                                if (is_array($itm)) {
                                    hidden('item_description', $itm['description']);
                                } else {
                                    hidden('item_description', '');
                                }
                        }

                        units_list_row('Unit:', 'tran_unit', $_POST['stock_id'], null, '');
                        $dec = get_qty_dec($_POST["stock_id"]);

                    } elseif ($_POST['item_type'] == NSIT_COMMENT) {
                        text_row_ex('Item Description:', 'item_description', 50, 250, 'Item Description');
                        hidden('stock_id', '');

                        $units_array = build_all_item_units_array();
                        custom_values_list_row('Unit:', 'tran_unit', $units_array, null, '');
                    } else {
                        hidden('stock_id', '');
                        hidden('tran_unit', '');
                        hidden('item_description', '');
                    }

                table_section(2);
                
                    amount_row("Quantity:", 'tran_qty', null, null, null, $dec);

                    if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM) {
                        amount_row("Item Cost:", 'item_cost', null, null, null, 0);
                    } else {
                        $_POST['item_cost'] = 0;
                        hidden('item_cost', 0);
                    }
                    
                    project_sites_list_row("Site:", 'site_id', GLOBAL_VOTES, null, '', false); 
                    text_row_ex('Line Comment:', 'line_comment', 50, 400, 'Line Comment');

        end_outer_table();
    div_end();
    
        if ($selected_id > 0 && $Mode != 'Delete') {
            button_cell('Update_ML', _("Update"),  _('Confirm changes'), ICON_UPDATE);
            button_cell('cancel', _("Cancel"), _("Cancel changes"), ICON_CANCEL);
            hidden('selected_id', $selected_id);

        } else {        
            button_cell('Add_ML', _("ADD"),  _('Confirm changes'), ICON_ADD);
            button_cell('cancel', _("Cancel"), _("Cancel changes"), ICON_CANCEL);
        }
}

function can_process_material_list_header($ml_no) {
    global $Refs;
    
    $jo_row = get_job_order_record($_POST['jo_id']);
        if (! is_array($jo_row)) {
            $set_focus = '';
            $message = ("Could not find Job Card #".$_POST['jo_id'].".");
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
    
    if (isset($_POST['jo_id']) || isset($_POST['ModifyML_No'])) {
        $type = ST_MATERIAL_LIST;
    } 
    
    $trans_no = 0;
    $header = get_material_list_header_record($ml_no);
    
    if ($ml_no > 0 && ! is_array($header)) {
        $message = ("Another user has been deleted Header Record #$ml_no.");
        return array("success" => false, "focus_to" => '', "message" => $message);
    }
      
    if (is_array($header)) {
        if (! in_array($header['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))) {
            $set_focus = '';
            $message = ("This document status does not allow further updating.");
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $ced_msg = can_edit_document($header['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'];
        
        $lines_count = get_material_list_details_lines_count($trans_no, $header['type']);
            if (! ($lines_count > 0)) {
                $message = "No any saved detail lines found.";
                $set_focus = '';
                return array("success" => false, "focus_to" => $set_focus, "message" => $message);
            }
    } 
    
    if (! $Refs->is_valid($_POST['reference'])) {
        $message = ("Please enter a reference.");
        $set_focus = 'reference';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], $type, $trans_no);
        if ($ref_msg) {
            $message = $ref_msg;
            $set_focus = 'reference';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);       
        }
      
    if (! ($ml_no > 0)) {
        if (! ($_POST['project_id'] > 0)) {
            if (isset($_POST['jo_id'])) {
                $jo_pro = get_job_order_department_approval_project($_POST['jo_id']);
                    if ($jo_pro['success'] === false) {
                        return array("success" => false, "focus_to" => '', "message" => $jo_pro['message']);
                    }
            }
            
            return array("success" => false, "focus_to" => 'project_id', "message" => "Please select a Project.");
        }
    }
    
    if (! is_date($_POST['tran_date'])) {
        $message = "Date entered is not a valid date.";
        $set_focus = 'tran_date';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);        
    }
              
    if ($_POST['location'] == '') {
        $message = "Please select a location.";
        $set_focus = 'location';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);
    }
        
    $row_state = 0;
    if ($ml_no > 0) {
        $row_state = $header['row_state'];
    }
    
    return array("success" => true, 'row_state' => $row_state, "message" => "");    
}

function can_process_material_list_line() {
    if (! ($_POST['item_type'] > 0)) {
        $message = "Please select an item type.";
        $set_focus = 'item_type';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM || $_POST['item_type'] == NSIT_STOCK_ITEM) {
        if (! (strlen($_POST['stock_id']) > 0)) {
            $message = "Please select an item.";
            $set_focus = 'stock_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }

        if ($_POST['tran_unit'] == -1) {
            $message = "Please select a tran unit.";
            $set_focus = 'tran_unit';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    } elseif ($_POST['item_type'] == NSIT_COMMENT) {
        if (! (strlen($_POST['item_description']) > 0)) {
            $message = "Item description cannot be empty.";
            $set_focus = 'item_description';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
        
        if ($_POST['tran_unit'] == '0') {
            $message = "Please select a unit.";
            $set_focus = 'tran_unit';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }
    
    $item = get_stock_item_edit_info($_POST['stock_id']);
    if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM){
        if (!($item['mb_flag'] == "D")) {
            $message = "Selected item is a stock item, Please select a non-stock item.";
            $set_focus = 'stock_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        } 
    }
    if ($_POST['item_type'] == NSIT_STOCK_ITEM){
        if (!($item['mb_flag'] == "B" || $item['mb_flag'] == "M")) {
            $message = "Selected item is not a stock item, Please select a stock item.";
            $set_focus = 'stock_id';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        } 
    }
        
    if (! (input_num('tran_qty') > 0)) {
        $message = "Quantity should be greater than zero.";
        $set_focus = 'tran_qty';
        return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
    }
    
    if ($_POST['item_type'] == NSIT_NON_STOCK_ITEM) {
        if (! ($_POST['item_cost'] > 0)) {
            $message = "Item cost should be greater than zero.";
            $set_focus = 'item_cost';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);  
        }
    }

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

function can_delete_material_list_line($ml_no) {
    global $systypes_array;
    
   $header = get_material_list_header_record($ml_no);
   
    if (is_array($header)) {
        if (! in_array($header['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))) {
            $message = ("This document status does not allow further updating.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }
        
        $ced_msg = can_edit_document(ST_MATERIAL_LIST, $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']);
            }
    } else {
        return array("success" => false, "message" => "Could not find ".$systypes_array[ST_MATERIAL_LIST]." #$ml_no.");
    }  
    
    $lines_count = get_material_list_details_lines_count($header['trans_no'], $header['type']);
        if (! ($lines_count > 1)) {
            $message = ("This is the last line. Can not delete this line.");
            $set_focus = '';
            return array("success" => false, "focus_to" => $set_focus, "message" => $message);
        }  
    
    return array("success" => true, "focus_to" => '', "message" => "");       
}

function save_material_list_header(&$ml_no, $type, $row_state) {
    global $systypes_array;

    $ml_no = write_material_list_header($type, $ml_no, $_POST['reference'], $_POST['project_id'], $_POST['location'], $_POST['comments'], $_POST['tran_date'], 0, 
                                        $_POST['jo_id'], $row_state); 
    
        if ($ml_no > 0) {
            return array("success" => true, 'ml_no' => $ml_no, "message" => $systypes_array[$type]." header #$ml_no has been saved.");
        } else {
            return array("success" => false, 'ml_no' => '', "message" => "Could not be saved ".$systypes_array[$type].' header.');
        }
}

function save_material_list_line(&$ml_no, $selected_id, $type, $trans_no) {    
    global $systypes_array;
    
    $standard_cost = 0; $conversion_factor = 1;
    
    $tran_unit = $_POST['tran_unit'];
    
    if ($_POST['item_type'] == NSIT_STOCK_ITEM) {
        $standard_cost = get_standard_cost($_POST['stock_id']);
        get_convertion_factor2($_POST['stock_id'], $tran_unit, $conversion_factor);

    } elseif ($_POST['item_type'] == NSIT_NON_STOCK_ITEM) {
        $tran_unit_cost = input_num('item_cost');
        get_convertion_factor2($_POST['stock_id'], $tran_unit, $conversion_factor);
        $standard_cost = $tran_unit_cost/$conversion_factor;
    }
    
    $qty = input_num('tran_qty') * $conversion_factor;
    
    $af_no = write_material_list_line($trans_no, $selected_id, $type, $_POST['stock_id'], $_POST['item_type'], $_POST['item_description'], $_POST['tran_unit'], 
                                      input_num('tran_qty'), $qty, $conversion_factor, $standard_cost, get_post('site_id'), $_POST['line_comment']); 
    
        if ($af_no > 0) {
            return array("success" => true, 'trans_no' => $trans_no, "message" => $systypes_array[$type]." line saved.");
        } else {
            if ($selected_id > 0) {
                $ln_ms = $systypes_array[$type]." #$selected_id line could not be updated.";
            } else {
                $ln_ms = $systypes_array[$type]." line could not be saved.";
            }

                return array("success" => false, 'ml_no' => $ml_no, "message" => $ln_ms);
        }
}

function save_material_list(&$ml_no, $selected_id) {
    global $systypes_array;
    
    if (isset($_POST['jo_id']) || isset($_POST['ModifyML_No'])) {
        $type = ST_MATERIAL_LIST;
    } 
    
    $row_state = 0;
    $hd_msg = can_process_material_list_header($ml_no);   
        if ($hd_msg["success"] !== true) {          
            if (isset($hd_msg["focus_to"])) {
                set_focus($hd_msg["focus_to"]);            
            }
            
            return array("success" => false, "message" => $hd_msg["message"]);
        } else {
            $row_state = $hd_msg['row_state'];
        }
    
    $ln_msg = can_process_material_list_line();
        if ($ln_msg['success'] !== true) {
            if (isset($ln_msg["focus_to"])) {
                set_focus($ln_msg["focus_to"]);            
            }
            
            return array("success" => false, 'ml_no' => $ml_no, "message" => $ln_msg['message']);        
        }
       
        begin_transaction();

            $header_msg = save_material_list_header($ml_no, $type, $row_state);
                if ($header_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, 'ml_no' => $ml_no, "message" => $header_msg['message']);
                }
                
            $header = get_material_list_header_record($ml_no);
                $trans_no = $header['trans_no'];
                $type = $header['type'];
                $row_state = $header['row_state'];

            $line_msg = save_material_list_line($ml_no, $selected_id, $type, $trans_no);
                if ($line_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, 'ml_no' => $ml_no, "message" => $line_msg['message']);
                }
                
            $num_af_row = update_material_list_header_totals($type, $trans_no, $row_state);
                if (! ($num_af_row == 1)) {
                    cancel_transaction();
                    return array("success" => false, 'ml_no' => $ml_no, "message" => "Could not update ".$systypes_array[ST_MATERIAL_LIST]." header total.");
                }

        commit_transaction();

    return array("success" => true, 'ml_no' => $ml_no, "message" => $systypes_array[$type]." #$ml_no has been saved.");
}

function delete_material_list_line($ml_no, $selected_id) {
    $cd_msg = can_delete_material_list_line($ml_no, $selected_id);
        if ($cd_msg['success'] !== true) {
            return $cd_msg;
        }
        
        begin_transaction();
            delete_material_list_details_record($selected_id);
        commit_transaction();

    return array("success" => true, 'ml_no' => $ml_no, "message" => "Line record #$selected_id has been deleted.");
}

function save_material_list_header_only(&$ml_no, $approve=false) {
    $row_state = 0;
    
    $hd_msg = can_process_material_list_header($ml_no);   
        if ($hd_msg["success"] !== true) {          
            if (isset($hd_msg["focus_to"])) {
                set_focus($hd_msg["focus_to"]);            
            }
            
            return array("success" => false, "message" => $hd_msg["message"]);
        } else {
            $row_state = $hd_msg['row_state'];
        }
        
        $type = ST_MATERIAL_LIST;
    
        begin_transaction();
        
            $msg = save_material_list_header($ml_no, $type, $row_state);
                if ($msg["success"] !== true) {          
                    cancel_transaction();

                    return $msg;
                } 

                if ($approve === false) {
                    commit_transaction();

                    return $msg;
                } 

            $header = get_material_list_header_record($ml_no);
            $ap_msg = approve_material_list($header);
                if ($ap_msg["success"] !== true) {          
                    cancel_transaction();

                    return $ap_msg;
                } 

            commit_transaction();
            
        return array('success' => true, 'message' => $ap_msg['message']);
}

function approve_material_list($header) {
    $current_user_id = $_SESSION['wa_current_user']->user;
    $task_costs = 0;
    
    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_material_list($ml_no, $trans_tp_name, $reject) {
    $hd_row = get_material_list_header_record($ml_no);
    
        if (! is_array($hd_row)) {
            return array("success" => false, "message" => "Could not find $trans_tp_name #$ml_no.");
        }

        if (! isset($hd_row['type']) || $hd_row['type'] != ST_MATERIAL_LIST) {
            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_MATERIAL_LIST, $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" => "", "trans_no" => $hd_row["trans_no"], "row_state" => $hd_row["row_state"], "hd_row" => $hd_row);
}

function reject_material_list($ml_no) {
    global $systypes_array;
    
    $type = ST_MATERIAL_LIST;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_material_list($ml_no, $trans_tp_name, true);
        if ($cn_rej["success"] !== true) { 
            return $cn_rej;
        } 
        
        $hd_row = $cn_rej["hd_row"];
        $trans_no = $cn_rej["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']);
                }
            
        commit_transaction();

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

function back_to_originator_material_list($ml_no) {
    global $systypes_array;
    
    $type = ST_MATERIAL_LIST;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_material_list($ml_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('ml_bo_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&BackedOrgID=$trans_no"); 
}

function clear_material_list_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 view_material_list_header($type, $trans_no) {
    global $approval_statuses;
    
    $row = get_material_list_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'];
                label_row("Job Card:", get_service_trans_view_str(ST_JOB_ORDER, $jo_id), "class='tableheader2'");
                label_row(_("Trans #:"), get_inventory_trans_view_str($type, $trans_no), "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);
        }
}

function view_material_list_details($type, $trans_no) {
    global $daily_item_types_array;
    
    $header_row = get_material_list_header_type_trans_no($type, $trans_no);
    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($header_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    start_table(TABLESTYLE, "width=95%");

        $th = array(_("ID"), _("Item Type"), _("Description"), _("Unit"), _("Requested Qty"), _("JMR Trn.Qty"), _("DPR Trn.Qty"), _('Cost'), _('Project Site'), _('Comment'));  
        table_header($th);

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

                        label_cell($row['trans_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"]);
                        qty_cell($row["tran_qty"],false,  2);
                        qty_cell($row["jmr_quantity"] / $row["conversion_factor"], false, 2);
                        qty_cell($row["dpr_quantity"] / $row["conversion_factor"], false, 2);
                        
                        $tran_unit_cost = $row["conversion_factor"] * $row["standard_cost"];
                            if ($tran_unit_cost > 0) {
                                qty_cell($tran_unit_cost, false, 2);
                            } else {
                                label_cell('');
                            }
                            
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(2);
}

function view_material_list_headers_by_jo_id($jo_id, $type, $width=70, $edit_link=false) {
    global $approval_statuses, $systypes_array, $path_to_root;
    
    $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;
        }
    
    if ($edit_link === false) {
        display_heading2($systypes_array[$type].'s');    br();
    } else {
        display_heading($systypes_array[$type].'s');   
    }
    
    start_table(TABLESTYLE, "width=$width%");

        $th = array(_("Trans #"), _("Reference"), _("Description"), _("Date"), _("Location"), _("Approval Status"));  
            if ($edit_link === true) {
                array_push($th, 'DPR'); array_push($th, 'JMR');
            }
        table_header($th);

        $k = 0; //row colour counter
            $result = get_material_list_headers_by_filters($jo_id, 0, $type);      
                while ($row = db_fetch($result)) {
                    $id = $row['id'];
                    
                    alt_table_row_color($k);
                        
                        label_cell(get_inventory_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');
                        
                        if ($edit_link === true) {
                            if (in_array($row['approval_status'], array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR))) {
                                $link = "<a target='_blank' href='$path_to_root/inventory/material_lists.php?ModifyML_No=$id' >Edit</a>";
                                label_cell('');
                                label_cell($link, 'align=center');
                            } elseif (in_array($row['approval_status'], array(AS_APPROVED))) {
                                $par = "ml_no=$id&type=".ST_DIRECT_PURCHASE_REQ;
                                $link = pager_link($systypes_array[ST_DIRECT_PURCHASE_REQ], "/inventory/material_list_jmr_dpr.php?$par", ICON_RECEIVE);
                                label_cell($link, 'align=center');

                                $par2= "ml_no=$id&type=".ST_JOB_MATERIAL_REQ;
                                $link2 = pager_link($systypes_array[ST_JOB_MATERIAL_REQ], "/inventory/material_list_jmr_dpr.php?$par2", ICON_DOC);
                                label_cell($link2, 'align=center');
                            } else {
                                label_cell(''); label_cell('');
                            }
                        }

                    end_row();        
                }

    end_table(2);
}

function job_material_lists(&$jo_id) {
    global $path_to_root, $Ajax;
    
    $Ajax->activate('job_material_lists');
    div_start('job_material_lists');
        if (! ($jo_id > 0)) {
            return;
        }
        
        $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;
            }
        
        view_material_list_headers_by_jo_id($jo_id, ST_MATERIAL_LIST, edit_link: true);

        start_table();
            hyperlink_params_separate($path_to_root . "/inventory/material_lists.php", 'Create a New Material List/ Estimate', "jo_id=$jo_id"); 
        end_table();
    div_end();
}

?>