<?php

function display_direct_purchase_requisition_header_details($dpr_no, $qck_no) {
    global $approval_statuses, $systypes_array;
    
    $req_hd_row = get_direct_purchase_requisition_header($dpr_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_DIRECT_PURCHASE_REQ]." Header");
    
        $jm_req_trans_no = $req_hd_row['trans_no'];
        if (! isset($_POST['location']) && ! ($qck_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'];
                if ($jo_id > 0) {
                    label_row(_("Job Card #:"), get_service_trans_view_str(ST_JOB_ORDER, $jo_id));
                } else {
                    label_row("Job Card #:", 'Purchase to Stock'); 
                }
                label_row("Req. Trans #:", get_supplier_trans_view_str($req_hd_row['type'], $req_hd_row['trans_no']));  
                $iss_row = get_quality_check_header_record($qck_no);
                    if (is_array($iss_row)) {
                        label_row("Check Trans #:", get_supplier_trans_view_str($iss_row['type'], $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_DIRECT_PURCHASE_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("Comments:", nl2br($req_hd_row['comments']));  
        end_table(2);
    }
    
    return $req_hd_row;
}

function display_quality_check_header($qck_no, $req_hd_row) {
    global $Refs, $systypes_array;
    
    display_heading($systypes_array[ST_QUALITY_CHECK]." Header");
    
        $type = ST_QUALITY_CHECK;
        $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_quality_check_header($qck_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_supplier_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("Receiving Location:", $header['location_name']); 
                            hidden('location', $_POST['location']);
                        } else {
                            locations_list_row("Receiving 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_quality_check_details($dpr_no, $qck_no, &$selected_id, &$Mode) { 
    global $Ajax, $daily_item_types_array, $systypes_array;
    
    display_heading($systypes_array[ST_QUALITY_CHECK]." Details");
    
    $req_trans_no = $check_trans_no = 0;
    $req_header = get_direct_purchase_requisition_header_record($dpr_no);
        if (is_array($req_header)) {
            $req_trans_no = $req_header['trans_no'];
        } 
        
    $check_hd_row = get_quality_check_header_record($qck_no);
        if (is_array($check_hd_row)) {
            $check_trans_no = $check_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(_("DP.Req. Line"), _("QC. Line"), _("Item Type"), _("Item"), _("Req. Unit"), _("Req. Qty"), _('Checked Qty'), _('Returned'), _('Exactly Checked'), 
                        _('Return Alloc'), _('Remain'), _('Check Unit'), _('Check Qty'), _('Budget'), _('Site'), _('Line Comment'), _(""), _(""));  
                
            table_header($th);

            $k = 0; //row colour counter
                $result = get_direct_purchase_requisition_with_quality_check_details($req_trans_no, $check_trans_no);      
                    while ($row = db_fetch($result)) {
                        $id = $row['trans_id'];
                        $check_line_id = $row['check_line_id'];
                        
                        $dp_req_array = display_direct_purchase_req_line_from_quality_check($id);
                        
                        if ($check_line_id > 0 && $row['stock_id'] != $row['check_stock_id']) {
                            start_row("style=background-color:#f3cbf7");
                        } else {
                            alt_table_row_color($k);
                        }

                            label_cell('', 'align=center');
                            label_cell($check_line_id, 'align=center');
                            
                            if (! isset($_POST["item_type_$id"]) && ! ($check_line_id > 0) && is_array($dp_req_array)) {
                                $_POST["item_type_$id"] = $dp_req_array['item_type'];
                            } elseif (! isset($_POST["item_type_$id"]) && $check_line_id > 0) {
                                $_POST["item_type_$id"] = $row['check_item_type'];
                            }
                            custom_values_list_cells('', "item_type_$id", $daily_item_types_array, null, '', true);
                            
                            if (! isset($_POST["stock_id_$id"]) && ! ($check_line_id > 0) && is_array($dp_req_array)) {
                                $_POST["stock_id_$id"] = $dp_req_array['stock_id'];
                            } elseif (! isset($_POST["stock_id_$id"]) && $check_line_id > 0) {
                                $_POST["stock_id_$id"] = $row['check_stock_id'];
                            }
                            if (! isset($_POST["item_description_$id"]) && ! ($check_line_id > 0) && is_array($dp_req_array)) {
                                $_POST["item_description_$id"] = $dp_req_array['item_description'];
                            } elseif (! isset($_POST["item_description_$id"]) && $check_line_id > 0) {
                                $_POST["item_description_$id"] = $row['check_item_description'];
                            }

                            if ($_POST["item_type_$id"] == NSIT_NON_STOCK_ITEM) {
                                label_cell(non_stock_items_list("stock_id_$id", null, false, true));
                                $itm = get_item($_POST["stock_id_$id"]);
                                    if (is_array($itm)) {
                                        hidden("item_description_$id", $itm['description']);
                                    } else {
                                        hidden("item_description_$id", '');
                                    }
                            } elseif ($_POST["item_type_$id"] == NSIT_STOCK_ITEM) {
                                label_cell(stock_and_manufacture_items_list("stock_id_$id", null, false, true));
                                $itm = get_item($_POST["stock_id_$id"]);
                                    if (is_array($itm)) {
                                        hidden("item_description_$id", $itm['description']);
                                    } else {
                                        hidden("item_description_$id", '');
                                    }
                            } elseif ($_POST["item_type_$id"] == NSIT_COMMENT) {
                                text_cells('', "item_description_$id", null, 20, 1000, 'Item Description');
                                hidden("stock_id_$id", '');
                            } else {
                                label_cell(''); 
                                hidden("stock_id_$id", '');
                                hidden("item_description_$id", '');
                            }
                            
                            label_cell('', 'colspan=7');  
                            $dec = 4; //get_qty_dec($row["stock_id"]);
                            
                            if (! isset($_POST["check_tran_unit_$id"])) {
                                if ($check_line_id > 0) {
                                    $_POST["check_tran_unit_$id"] = $row["check_tran_unit"];
                                } else {
                                    $_POST["check_tran_unit_$id"] = $row["tran_unit"];
                                }
                            }
                            
                            if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                                units_list_cells('', "check_tran_unit_$id", $_POST["stock_id_$id"], null, '', true);
                            } else {
                                custom_values_list_cells('', "check_tran_unit_$id", $units_array, null, '', true);   
                            }
                            
                            if (! isset($_POST["check_tran_qty_$id"])) {
                                if ($check_line_id > 0) {
                                    $_POST["check_tran_qty_$id"] = $row["check_tran_qty"];
                                } else {
                                    set_quality_check_remain_checkable_qty($id, $row, $dec);
                                }
                            } else {
                                if (list_updated("check_tran_unit_$id")) {
                                    set_quality_check_remain_checkable_qty($id, $row, $dec);
                                }
                            }
                            amount_cells("", "check_tran_qty_$id", null, null, null, $dec);
                            
                            label_cell($row['task_description']);          
                            if (! isset($_POST["site_id_$id"]) && ! ($check_line_id > 0)) {
                                $_POST["site_id_$id"] = $row['project_site_id'];
                            } elseif (! isset($_POST["site_id_$id"]) && $check_line_id > 0) {
                                $_POST["site_id_$id"] = $row['check_site_id'];
                            }
                            
                            all_project_sites_list_cells("", "site_id_$id", GLOBAL_VOTES, null, '', false); 
                            
                            if (! isset($_POST["line_comment_$id"]) && $check_line_id > 0) {
                                $_POST["line_comment_$id"] = $row['check_line_comment'];
                            }
                            text_cells('', "line_comment_$id", null, 20, 200, 'Line Comment'); 
                            
                            if (! isset($_POST["checked_$id"]) && $check_line_id > 0) {
                                $_POST["checked_$id"] = 1;
                            } 
                            check_cells(null, "checked_$id", null, false, false, 'align=center colspan=2');

                        end_row();  
                        
                        vertical_space('height=18px colspan=18');
                    }
                    
                    display_quality_check_new_lines_details($check_trans_no, $selected_id, $Mode, $k);

        end_table(2);
    
    div_end();
}

function display_direct_purchase_req_line_from_quality_check($dp_req_line_id) {
    global $daily_item_types_array;
    
    if (! ($dp_req_line_id > 0)) {
        return;
    }
    
    $dec = 4;
    $row = get_direct_purchase_requisition_detail_line_details($dp_req_line_id);
        start_row('style=background-color:#abdbda');
            label_cell(text_bold($dp_req_line_id), 'colspan=1 align=center');
            label_cell('');
            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"], true, $dec);
            qty_cell($row["checked_quantity"] / $row['conversion_factor'], false, $dec);
            qty_cell($row["returned_quantity"] / $row['conversion_factor'], false, $dec);
            qty_cell(($row["checked_quantity"] - $row["returned_quantity"]) / $row['conversion_factor'], true, $dec);
            qty_cell($row["returned_alloc"] / $row['conversion_factor'], false, $dec);
            qty_cell($row["tran_qty"] - ($row["checked_quantity"] - $row["returned_quantity"]) / $row['conversion_factor'], false, $dec);
            label_cell('', 'colspan=2');  
            label_cell($row["task_description"]);     
            label_cell($row["site_description"]);          
            label_cell(nl2br($row["line_comment"]), 'colspan=3'); 
        end_row();
        
        return array('item_type' => $row['item_type'], 'stock_id' => $row['stock_id'], 'item_description' => $row['item_description']); 
}

function display_quality_check_new_lines_details($check_trans_no, $selected_id, $Mode, &$k) {
    global $daily_item_types_array, $systypes_array;
    
    start_row('style=background-color:#afedab');
        label_cell(text_bold($systypes_array[ST_QUALITY_CHECK].' Records Without '.$systypes_array[ST_DIRECT_PURCHASE_REQ]), 'align=center colspan=18');
    end_row();
    
    $dec = 4;
    $result = get_quality_checks_without_dp_req_details($check_trans_no);
        while ($row = db_fetch($result)) {
            $qc_line_id = $row['trans_id'];
            
            if ($selected_id != $qc_line_id || $Mode == 'Delete') {
                alt_table_row_color($k);
                    label_cell('No DP Req');
                    label_cell(text_bold($qc_line_id), 'colspan=1 align=center');
                    label_cell($daily_item_types_array[$row['item_type']]);
                    if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                        label_cell($row["stock_id"]." - ".$row["item_description"]);  
                    } else {
                        label_cell($row["item_description"]);
                    }
                    label_cell('', 'colspan=7');          
                    label_cell($row["unit_name"]);
                    qty_cell($row["tran_qty"], false, $dec);
                    label_cell($row["task_description"]);          
                    label_cell($row["site_description"]);          
                    label_cell(nl2br($row["line_comment"]), 'colspan=0'); 
                    
                    edit_button_cell("Edit$qc_line_id", _("Edit"));    
                    delete_button_cell("Delete$qc_line_id", _("Delete"));  
                end_row();
            } else {
                display_quality_check_details_edit_controls($selected_id, $Mode);
            }
        }
        
        if (! ($selected_id > 0) || $Mode == 'Delete') {
            display_quality_check_details_edit_controls($selected_id, $Mode);
        }
}

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

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

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

function display_quality_check_details_edit_controls($selected_id, &$Mode) {
    global $Ajax, $daily_item_types_array;
    $dec = 2;
    
    if ($selected_id > 0 && $Mode != 'Delete') {   
        $row = get_quality_check_detail_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['task_id'] = $row["task_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['task_id'] > 0)) {
                $_POST['task_id'] = $row["task_id"];
            }
            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=16>";
        $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 (in_array($_POST['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                        all_budgets_list_row('Budget:', 'task_id', GLOBAL_VOTES, null, _(''));
                    } else {
                        $_POST['task_id'] = 0;
                        hidden('task_id', 0);
                    }

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

                table_section(3);
                
                    all_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();
    
    echo "</td>";
    
        if ($selected_id > 0 && $Mode != 'Delete') {
            button_cell('Update_DPR', _("Update"),  _('Confirm changes'), ICON_UPDATE);
            button_cell('cancel', _("Cancel"), _("Cancel changes"), ICON_CANCEL);
            hidden('selected_id', $selected_id);

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

function can_save_quality_check_header($dpr_no, $qck_no) {
    global $Refs, $systypes_array;
    
    $req_hd = get_direct_purchase_requisition_header_record($dpr_no);
        if (is_array($req_hd)) {
            if (! in_array($req_hd['approval_status'], array(AS_APPROVED, AS_COMPLETED))) {
                return array("success" => false, "message" => $systypes_array[ST_DIRECT_PURCHASE_REQ]." #$dpr_no is not approved.");
            }
        } else {
            return array("success" => false, "message" => $systypes_array[ST_DIRECT_PURCHASE_REQ]." #$dpr_no has been deleted by another user.");
        }
    
    $trans_no = $check_row_state = 0;
    $req_row_state = $req_hd['row_state'];
    $header = get_quality_check_header_record($qck_no);
    
    if (($qck_no > 0) && ! is_array($header)) {
        return array("success" => false, "message" => $systypes_array[ST_QUALITY_CHECK]." #$qck_no has been deleted by another user.");
    }
      
    if ($qck_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($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']; $check_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_QUALITY_CHECK, $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, 'check_row_state' => $check_row_state, "message" => "", 'dp_req_hd' => $req_hd);    
}

function can_save_quality_check_lines($req_trans_no, $check_trans_no, $approve=false) {
    global $systypes_array;
    
    $result = get_direct_purchase_requisition_with_quality_check_details($req_trans_no, $check_trans_no);  
        if (! (db_num_rows($result) > 0)) {
            return array('success' => false, 'message' => "No source ".$systypes_array[ST_DIRECT_PURCHASE_REQ]." found.");
        }
        
        $no_selected_recs = 0;
        
        while ($row = db_fetch($result)) {
            $id = $row['trans_id'];
            $check_line_id = $row['check_line_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                $item_type = $_POST["item_type_$id"];
                $stock_id = $_POST["stock_id_$id"];
                $item_description = $_POST["item_description_$id"];
                
                $check_tran_unit = $_POST["check_tran_unit_$id"];
                $check_tran_qty = input_num("check_tran_qty_$id");
                
                $convesion_factor = 1;
                
                // can save quality check line
                $cn_sv_ln = can_save_quality_check_line($stock_id, $item_type, $item_description, $check_tran_unit, $check_tran_qty, $convesion_factor, $check_line_id, $id, 
                                                        $row);
                    if ($cn_sv_ln['success'] !== true) {
                        return array("success" => false, "message" => $cn_sv_ln['message']);
                    }
                    
                $no_selected_recs++;
            } 
        }
        
        $recs_without_dp_req = get_quality_check_details_lines_count($check_trans_no, ST_QUALITY_CHECK, false);
        
        if (! ($no_selected_recs > 0) && ! ($recs_without_dp_req > 0)) {
            return array("success" => false, "message" => "Please select at least one record before saving.");  
        }
        
        if ($approve === true) {
            $result = get_quality_check_detail_records_with_no_source(ST_QUALITY_CHECK, $check_trans_no);      
                while ($row = db_fetch($result)) {
                    if (in_array($row['item_type'], array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
                        if (! ($row['task_id'] > 0)) {
                            $line_id = $row['trans_id'];
                            return array("success" => false, "message" => "Check line #$line_id please select a budget.");  
                        }
                    }
                }
        }
        
        return array("success" => true, "message" => "");
}

function can_save_quality_check_line($stock_id, $item_type, $item_description, $check_tran_unit, $check_tran_qty, $convesion_factor, $check_line_id, 
                                     $id, $row) {
    $type = ST_QUALITY_CHECK;
    $dec = 4; // get_qty_dec($stock_id);
    
    if (! ($item_type > 0)) {
        return array("success" => false, "focus_to" => "item_type_$id", "message" => "Req. Line #$id Please select an item type.");  
    }
    
    if (in_array($item_type, array(NSIT_NON_STOCK_ITEM, NSIT_STOCK_ITEM))) {
        if (! (strlen($stock_id) > 0)) {
            return array("success" => false, "focus_to" => "stock_id_$id", "message" => "Req. Line #$id Please select an item.");  
        }

        if ($check_tran_unit == -1) {
            return array("success" => false, "focus_to" => "check_tran_unit_$id", "message" => "Req. Line #$id Please select a tran unit.");  
        }
    } elseif ($item_type == NSIT_COMMENT) {
        if (! (strlen($item_description) > 0)) {
            return array("success" => false, "focus_to" => "item_description_$id", "message" => "Req. Line #$id Item description cannot be empty.");  
        }
        
        if ($check_tran_unit == '0') {
            return array("success" => false, "focus_to" => "check_tran_unit_$id", "message" => "Req. Line #$id Please select a tran unit.");  
        }
    }

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

        get_convertion_factor2($stock_id, $check_tran_unit, $convesion_factor);
        
        $req_base_qty = (float) $row['qty'];
        $returned_quantity = (float) $row['returned_quantity'];

        $base_checked_qty = (float) get_quality_check_lines_total_by_source_line($type, $id, $check_line_id); // get without rejected qty
        $tran_checked_qty = ($base_checked_qty - $returned_quantity ) / $convesion_factor;

        $req_this_tran_qty = round($req_base_qty / $convesion_factor, $dec);
        
        $remain_qty = $req_this_tran_qty - $tran_checked_qty;

        if ($check_tran_qty > $remain_qty) {
            $exceeded = round($check_tran_qty - $remain_qty, $dec);

            return array("success" => false, "focus_to" => "check_tran_qty_$id", 
                         "message" => "Req. Line #$id remain quality $remain_qty is exceeded by $exceeded in selected unit.");  
        }

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

function save_quality_check_lines($req_trans_no, $check_trans_no) {
    global $systypes_array;
    $type = ST_QUALITY_CHECK;
    
    $result = get_direct_purchase_requisition_with_quality_check_details($req_trans_no, $check_trans_no);  
    
    $check_lines_count = get_quality_check_details_lines_count($check_trans_no, $type, true);
        if ($check_lines_count > 0) {
            $del_af_rows = delete_quality_check_detail_lines($type, $check_trans_no, true);
                if ($del_af_rows != $check_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'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                
                $item_type = $_POST["item_type_$id"];
                $stock_id = $_POST["stock_id_$id"];
                $item_description = $_POST["item_description_$id"];
                $check_tran_unit = $_POST["check_tran_unit_$id"];
                $check_tran_qty = input_num("check_tran_qty_$id");
                
                $convesion_factor = 1;
                
                // save job material check line
                $sv_ln_msg = save_quality_check_line($type, $check_trans_no, $item_type, $stock_id, $item_description, $check_tran_unit, $check_tran_qty, $convesion_factor, 
                                                     $row);
                    if ($sv_ln_msg['success'] !== true) {
                        cancel_transaction();
                        return array("success" => false, "message" => $sv_ln_msg['message']);
                    }
            } 
            
            $upaf_row = update_direct_purchase_requisition_line_total_checked_qty($id, $type, $row['row_state']);
                if ($upaf_row != 1) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Req. Line #$id could not update total checked quantity.");  
                }
        }
        
        return array("success" => true, "message" => "");  
}

function save_quality_check_header(&$dpr_no, &$qck_no, &$check_trans_no, $type, $project_id, $loc_code, $tran_date, $check_row_state) {
    global $systypes_array;
    
    $req_hd_row = get_direct_purchase_requisition_header($dpr_no);
        $jo_id = $req_hd_row['jo_id'];
    $af_no = write_quality_check_header($jo_id, $type, $dpr_no, $qck_no, $check_trans_no, $_POST['reference'], $project_id, $loc_code, $_POST['comments'], $tran_date, 
                                        $check_row_state); 
    
        if ($af_no > 0) {
            return array("success" => true, "message" => $systypes_array[$type]." header record #$qck_no has been saved.");
        } else {
            return array("success" => false, "message" => "Could not be saved ".$systypes_array[$type].' header.');
        }
}

function save_quality_check_line($type, $check_trans_no, $item_type, $stock_id, $item_description, $tran_unit, $tran_qty, $conversion_factor, $row) {    
    global $systypes_array;
    
        $id = $row['trans_id'];
        $check_line_id = $row['check_line_id'];

        $standard_cost = $row['standard_cost'];
        $site_id = $_POST["site_id_$id"];
        $line_comment = $_POST["line_comment_$id"];
        $task_id = $row['task_id'];
                
            if ($item_type == NSIT_STOCK_ITEM) {
                $standard_cost = get_standard_cost($stock_id);
            } 
            
            get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);

            $base_qty = $tran_qty * $conversion_factor;

            $ln_id = insert_quality_check_line($check_trans_no, $type, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, $base_qty, $conversion_factor, 
                                               $standard_cost, $site_id, $line_comment, $task_id, $id, $check_line_id);

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

function save_quality_check(&$dpr_no, &$qck_no, $approve=false) {
    global $systypes_array;
    
    $req_type = ST_DIRECT_PURCHASE_REQ; $type = ST_QUALITY_CHECK;
    
    $cn_sv_hd = can_save_quality_check_header($dpr_no, $qck_no);   
        if ($cn_sv_hd["success"] !== true) {          
            return $cn_sv_hd;
        }
        
        $req_row_state = $cn_sv_hd['req_row_state']; 
        $new_check_row_state = $check_row_state = $cn_sv_hd['check_row_state'];
        
        $dp_req_hd = $cn_sv_hd['dp_req_hd']; 
        $req_trans_no = $dp_req_hd['trans_no']; $project_id = $dp_req_hd['project_id'];
        
    $check_trans_no = 0; 
    $check_hd_row = get_quality_check_header_record($qck_no);
        if (is_array($check_hd_row)) {
            $check_trans_no = $check_hd_row['trans_no']; 
        }
        
    $cn_sv_line = can_save_quality_check_lines($req_trans_no, $check_trans_no, $approve);   
        if ($cn_sv_line["success"] !== true) {          
            return $cn_sv_line;
        }
        
    $tran_date = date2sql($_POST['tran_date']);
       
        begin_transaction();
        
            if ($qck_no > 0) {
                $new_check_row_state = db_new_row_state($check_row_state);
            } 

            $hd_msg = save_quality_check_header($dpr_no, $qck_no, $check_trans_no, $type, $project_id, $_POST['location'], $tran_date, $check_row_state);
                if ($hd_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $hd_msg['message']);
                }
                
            $sv_ln_msg = save_quality_check_lines($req_trans_no, $check_trans_no);
                if ($sv_ln_msg['success'] !== true) {
                    cancel_transaction();
                    return $sv_ln_msg;       
                }
                
            $all_checked = check_all_direct_purchase_requisition_lines_fully_checked($req_type, $req_trans_no);
                if ($all_checked === true && $dp_req_hd['approval_status'] == AS_APPROVED) {
                    $ap_msg = direct_update_document_status($req_type, $req_trans_no, AS_COMPLETED, $req_row_state);     
                        if ($ap_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);
                } elseif ($all_checked === false && $dp_req_hd['approval_status'] == AS_COMPLETED) {
                    $ap_msg = direct_update_document_status($req_type, $req_trans_no, AS_APPROVED, $req_row_state);     
                        if ($ap_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);
                }
                
            $qc_af = update_quality_check_row_state($type, $check_trans_no, $new_check_row_state);
                if (! ($qc_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$type]." trans #$check_trans_no row state.");
                }
                
            $req_af = update_direct_purchase_requisition_row_state($dpr_no, $req_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." trans #$req_row_state row state.");
                }
             
            $approval_status = 0;
            if ($approve === true) {
                $ap_msg = approve_quality_check($check_hd_row, db_new_row_state($new_check_row_state));
                    if ($ap_msg["success"] !== true) {          
                        cancel_transaction();
                        return $ap_msg;
                    } 

                $approval_status = $ap_msg['approval_status'];
            }
                
            if ($approve === true && $approval_status == AS_APPROVED) {
                // newly added lines budgets update
                $bu_msg = quality_check_details_budget_update($type, $check_trans_no);
                    if ($bu_msg['success'] === false) {
                        cancel_transaction();
                        return $bu_msg;
                    }
            }
                
        commit_transaction();
            
            if ($approve === true) {
                set_session_variable('qck_messages', $ap_msg['message']);
                meta_forward($_SERVER['PHP_SELF'], "type=$type&ApprovedID=$check_trans_no"); 
            } else {
                return array("success" => true, "message" => $systypes_array[$type]." Trans #$check_trans_no has been saved.");
            }
}

function approve_quality_check($header, $row_state) {
    $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, $row_state, 
                            $header['created_by']);
}

function quality_check_details_budget_update($type, $trans_no) {
    global $systypes_array;
    
    // budget update 
        $details_array = $b = array();

        $result = get_quality_check_detail_records_with_no_source($type, $trans_no);      
            while ($row = db_fetch($result)) {
                if ($row['item_type'] != NSIT_COMMENT) {
                    $qty = $row['qty'];
                    $b['row_id'] = $row['trans_id'];
                    $b['stock_id'] = $row['stock_id'];
                    $b['task_id'] = $row['task_id'];
                    $b['requested_qty'] = $row['qty'];
                    $b['high_value_item'] = 0;

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

                    $details_array[] = $b;
                }
            }

        $qc_tasks_summary = calculate_task_remaining_totals($details_array);
        $created_by = $_SESSION['wa_current_user']->user;

        $msg = charge_cost_to_tasks($type, $trans_no, $qc_tasks_summary, $created_by);
            if ($msg['success'] !== true) {
                cancel_transaction();
                return array("success" => $msg['success'], "tran_no" => $trans_no, "message" => $msg['message']);
            }
            
        return array("success" => true, "message" => $systypes_array[$type].' budgets have been updated.');
}

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

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

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

function handle_save_quality_check_line(&$dpr_no, &$qck_no, $selected_id) {
    global $systypes_array;
    
    $req_type = ST_DIRECT_PURCHASE_REQ; $type = ST_QUALITY_CHECK;
    
    $cn_sv_hd = can_save_quality_check_header($dpr_no, $qck_no);   
        if ($cn_sv_hd["success"] !== true) {          
            return $cn_sv_hd;
        }
        
        $req_row_state = $cn_sv_hd['req_row_state']; 
        $new_check_row_state = $check_row_state = $cn_sv_hd['check_row_state'];
        
        $dp_req_hd = $cn_sv_hd['dp_req_hd']; 
        $project_id = $dp_req_hd['project_id'];
        
   $cn_sv_ln = can_save_new_quality_check_line(); 
        if ($cn_sv_ln["success"] !== true) {          
            return $cn_sv_ln;
        }    
        
    $check_trans_no = $conversion_factor = $standard_cost = 0; 
    $check_hd_row = get_quality_check_header_record($qck_no);
        if (is_array($check_hd_row)) {
            $check_trans_no = $check_hd_row['trans_no']; 
        }
        
        $tran_date = date2sql($_POST['tran_date']);
       
        begin_transaction();
        
            if ($selected_id > 0) {
                $dl_row = delete_quality_check_detail_line_by_id($selected_id);
                    if ($dl_row != 1) {
                        cancel_transaction();
                        return array("success" => false, "message" => "Check line #$selected_id could not delete.");
                    }
            }
            
            if ($qck_no > 0) {
                $new_check_row_state = db_new_row_state($check_row_state);
            } 

            $hd_msg = save_quality_check_header($dpr_no, $qck_no, $check_trans_no, $type, $project_id, $_POST['location'], $tran_date, $check_row_state);
                if ($hd_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $hd_msg['message']);
                }
                
            // save quality check new line
            if ($_POST["item_type"] == NSIT_STOCK_ITEM) {
                $standard_cost = get_standard_cost($_POST["stock_id"]);
            } elseif ($_POST['item_type'] == NSIT_NON_STOCK_ITEM) {
                get_convertion_factor2($_POST['stock_id'], $_POST["tran_unit"], $conversion_factor);
                $standard_cost = input_num('item_cost') / $conversion_factor;
            }
            
            get_convertion_factor2($_POST["stock_id"], $_POST["tran_unit"], $conversion_factor);

            $base_qty = input_num("tran_qty") * $conversion_factor;

            $nid = insert_quality_check_line($check_trans_no, $type, $_POST["stock_id"], $_POST["item_type"], $_POST["item_description"], $_POST["tran_unit"], 
                                             input_num("tran_qty"), $base_qty, $conversion_factor, $standard_cost, $_POST['site_id'], $_POST['line_comment'], 
                                             $_POST['task_id'], 0, $selected_id);

                if (! ($nid > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not save ".$systypes_array[$type]." line details.");
                } 
                    
            $qc_af = update_quality_check_row_state($type, $check_trans_no, $new_check_row_state);
                if (! ($qc_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$type]." trans #$check_trans_no row state.");
                }
                    
            $req_af = update_direct_purchase_requisition_row_state($dpr_no, $req_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." record #$dpr_no row state.");
                }
                    
        commit_transaction();
            
        return array("success" => true, "message" => $systypes_array[$type]." #$check_trans_no has been saved.");
}

function can_delete_quality_check_line($qck_no, $selected_id) {
    global $systypes_array;
    
    $header = get_quality_check_header_record($qck_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))) {
                return array("success" => false, "message" => "This document status does not allow further updating.");
            }
            
            $ced_msg = can_edit_document(ST_QUALITY_CHECK, $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_QUALITY_CHECK]." #$qck_no.");
        } 
    
    $dpr_line = get_quality_check_detail_record($selected_id);
        if (! is_array($dpr_line)) {
            return array("success" => false, "message" => "Check line #$selected_id is already deleted by another user.");
        } 
    
    $lines_count = get_quality_check_details_lines_count($header['trans_no'], $header['type'], null, $selected_id);
        if (! ($lines_count > 1)) {
            return array("success" => false, "message" => "This is the last line. Can not delete check line #$selected_id.");
        }  
    
    return array("success" => true, "message" => "");       
}

function handle_delete_quality_check_line($qck_no, $selected_id) {
    $cd_msg = can_delete_quality_check_line($qck_no, $selected_id);
        if ($cd_msg['success'] !== true) {
            return $cd_msg;
        }
        
        begin_transaction();
        
            $af_row = delete_quality_check_detail_line_by_id($selected_id);
                if ($af_row != 1) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Check line #$selected_id could not delete.");
                }
                
        commit_transaction();

    return array("success" => true, "message" => "Check line #$selected_id has been deleted.");
}

function can_reject_back_to_originator_quality_check($dpr_no, $qck_no, $trans_tp_name, $reject) {
    global $systypes_array;
    
    $req_hd = get_direct_purchase_requisition_header_record($dpr_no);
        if (is_array($req_hd)) {
            if ($req_hd['type'] != ST_DIRECT_PURCHASE_REQ) {
                return array("success" => false, "message" => "Invalid transaction type.");
            }
        } else {
            return array("success" => false, "message" => $systypes_array[ST_DIRECT_PURCHASE_REQ]." #$dpr_no has been deleted by another user.");
        }
    
    $hd_row = get_quality_check_header_record($qck_no);
    
        if (! is_array($hd_row)) {
            return array("success" => false, "message" => "Could not find $trans_tp_name #$qck_no.");
        }

        if (! isset($hd_row['type']) || $hd_row['type'] != ST_QUALITY_CHECK) {
            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_QUALITY_CHECK, $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_quality_check($dpr_no, $qck_no) {
    global $systypes_array;
    
    $req_type = ST_DIRECT_PURCHASE_REQ;
    $type = ST_QUALITY_CHECK;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_quality_check($dpr_no, $qck_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"];
            $dp_req_ap = $req_hd_row["approval_status"];
        
        $hd_row = $cn_rej["hd_row"];
            $check_trans_no = $hd_row["trans_no"];
            $row_state = $hd_row["row_state"];
        
        begin_transaction();
        
            $rj_msg = reject_document($type, $check_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']);
                }
                
            $qcq_up_msg = update_direct_purchase_requisition_lines_total_checked_qty($check_trans_no, $type);
                if ($qcq_up_msg['success'] === false ) {
                    cancel_transaction();
                    return $qcq_up_msg;
                }
                
            $all_checked = check_all_direct_purchase_requisition_lines_fully_checked($req_type, $req_trans_no);
                if ($all_checked === true && $dp_req_ap == AS_APPROVED) {
                    $ap_msg = direct_update_document_status($req_type, $req_trans_no, AS_COMPLETED, $req_row_state);     
                        if ($ap_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);
                } elseif ($all_checked === false && $dp_req_ap == AS_COMPLETED) {
                    $ap_msg = direct_update_document_status($req_type, $req_trans_no, AS_APPROVED, $req_row_state);     
                        if ($ap_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_direct_purchase_requisition_row_state($dpr_no, $req_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." trans #$req_row_state row state.");
                }
            
        commit_transaction();

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

function back_to_originator_quality_check($dpr_no, $qck_no) {
    global $systypes_array;
    
    $type = ST_QUALITY_CHECK;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_quality_check($dpr_no, $qck_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('qck_bo_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&BackedOrgID=$trans_no"); 
}

function clear_quality_check_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_quality_check_header($type, $trans_no) {
    global $approval_statuses;
    
    $row = get_quality_check_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'];
                if ($jo_id > 0) {
                    label_row(_("Job Card #:"), get_service_trans_view_str(ST_JOB_ORDER, $jo_id), "class='tableheader2'");
                } else {
                    label_row("Job Card #:", 'Purchase to Stock', "class='tableheader2'"); 
                }
                $re_hd = get_direct_purchase_requisition_header_record($row['dpr_no']);
                label_row("Req. Trans #:", get_supplier_trans_view_str(ST_DIRECT_PURCHASE_REQ, $re_hd['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);
        }
        
        return $row['id'];
}

function view_quality_check_details($type, $trans_no) {
    global $daily_item_types_array;
    
    $dpr_row = get_quality_check_header_type_trans_no($type, $trans_no);
    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($dpr_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"), _("DP.Req Line"), _("Req. Item"), _("Item Type"), _("Description"), _("Unit"), _("Tran Qty"), _('GRN Qty'), _('GRN Alloc'), _('GRN Total'), 
                    _("Returned Qty"), _("Returned Alloc"), _('Budget'), _('Cost'), _('Project Site'), _('Comment'));  
        table_header($th);

        $k = 0; //row colour counter
            $result = get_quality_check_line_details_with_dpr_line_details($trans_no, $type);      
                while ($row = db_fetch($result)) {
                    $dec = 2;
                    
                    if ($row['req_stock_id'] != $row['stock_id']) {
                        start_row("style=background-color:#f3cbf7");
                    } else {
                        alt_table_row_color($k);
                    }

                        label_cell($row['trans_id'], 'align=center');
                        label_cell($row['source_line_id'] > 0 ? $row['source_line_id'] : 'No DP.Req', 'align=center');
                        label_cell($row['req_stock_id'].' - '.$row['req_item_description']);
                            
                        label_cell($daily_item_types_array[$row['item_type']]);
                        if ($row['item_type'] == NSIT_NON_STOCK_ITEM || $row['item_type'] == NSIT_STOCK_ITEM) {
                            label_cell($row["stock_id"]." - ".$row["item_description"]);  
                            
                            $dec = get_qty_dec($row["stock_id"]);
                        } else {
                            label_cell($row["item_description"]);
                        }
                        label_cell($row["unit_name"]);
                        
                        qty_cell($row["tran_qty"], true, $dec);
                        qty_cell($row["grn_quantity"] / $row["conversion_factor"], false, $dec);
                        qty_cell($row["grn_alloc"] / $row["conversion_factor"], false, $dec);
                        qty_cell(($row["grn_quantity"] + $row["grn_alloc"]) / $row["conversion_factor"], true, $dec);
                        qty_cell($row["returned_quantity"] / $row["conversion_factor"], false, $dec);
                        qty_cell($row["returned_alloc"] / $row["conversion_factor"], false, $dec);
                        
                        if ($row['item_type'] == NSIT_COMMENT) {
                            label_cell('No budget required');
                        } else {
                            label_cell($row["task_description"]);
                        }
                        $tran_unit_cost = $row["conversion_factor"] * $row["standard_cost"];
                            if ($tran_unit_cost > 0) {
                                qty_cell($tran_unit_cost, false, $dec);
                            } else {
                                label_cell('');
                            }
                            
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(2);
}

function view_quality_check_headers_by_dpr_no($dpr_no, $type) {
    $dpr_row = get_direct_purchase_requisition_header($dpr_no);
    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($dpr_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    $result = get_quality_check_headers_by_dpr_no_type($dpr_no, $type); 
        if (! (db_num_rows($result) > 0)) {
            return;
        }
    
    global $systypes_array, $approval_statuses;
    
    display_heading($systypes_array[$type]." 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_supplier_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_quality_check_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_quality_check_headers_by_filters($jo_id, 0, $type);      
                while ($row = db_fetch($result)) {
                    alt_table_row_color($k);
                        
                        label_cell(get_supplier_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);
}

?>