<?php

function display_quality_check_header_details($qck_no, $rcp_no) {
    global $approval_statuses, $systypes_array;
    
    $req_hd_row = get_quality_check_header($qck_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_QUALITY_CHECK]." Header");
    
        $qck_trans_no = $req_hd_row['trans_no'];
        if (! isset($_POST['location']) && ! ($rcp_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("Q.Check Trans #:", get_supplier_trans_view_str($req_hd_row['type'], $req_hd_row['trans_no']));  
                $iss_row = get_quality_check_header_record($rcp_no);
                    if (is_array($iss_row)) {
                        label_row("GRN 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, $qck_trans_no."&source_type_id=".ST_QUALITY_CHECK, "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_direct_purchase_receipt_header($rcp_no, $req_hd_row) {
    global $Refs, $systypes_array;
    
    display_heading($systypes_array[ST_DIRECT_PURCHASE_RECEIPT]." Header");
    
        $type = ST_DIRECT_PURCHASE_RECEIPT;
        $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($rcp_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("GRN Location:", $header['location_name']); 
                            hidden('location', $_POST['location']);
                        } else {
                            locations_list_row("GRN 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_direct_purchase_receipt_details($qck_no, $rcp_no) { 
    global $Ajax, $daily_item_types_array, $systypes_array;
    
    display_heading($systypes_array[ST_DIRECT_PURCHASE_RECEIPT]." Details");
    
    $qck_trans_no = $trans_no = 0;
    $req_header = get_quality_check_header_record($qck_no);
        if (is_array($req_header)) {
            $qck_trans_no = $req_header['trans_no'];
        } 
        
    $rcp_hd_row = get_quality_check_header_record($rcp_no);
        if (is_array($rcp_hd_row)) {
            $trans_no = $rcp_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"),_("Q.Check Line"), _("GRN Line"), _("Req. Item"), _("Item Type"), _("Item"), _("Q.Check Unit"), _("Q.Check Qty"), _('GRN Qty'), 
                        _('GRN Alloc'), _('GRN + Alloc'), _('Returned'), _('Return Alloc'), _('GRN Unit'), _('GRN Qty'), _("Unit Price"), _('Site'), _('Line Comment'), 
                        _(""), _(""));  
                
            table_header($th);

            $dec = 4;
            $k = 0; //row colour counter
                $result = get_quality_check_with_direct_purchase_receipt_details($qck_trans_no, $trans_no);      
                    while ($row = db_fetch($result)) {
                        $id = $row['trans_id'];
                        $rcp_line_id = $row['rcp_line_id'];
                        $req_conversion_factor = $row['conversion_factor'];
                        
                        $qc_array = display_quality_check_line($id, $row);
                        
                        if ($qc_array['item_changed'] === true || ($rcp_line_id > 0 && $row['stock_id'] != $row['rcp_stock_id'])) {
                            start_row("style=background-color:#f3cbf7");
                        } else {
                            alt_table_row_color($k);
                        }

                            label_cell('');
                            label_cell(text_bold($id), 'align=center');
                            label_cell($rcp_line_id, 'align=center');
                            label_cell("");
                            
                            if (! isset($_POST["item_type_$id"]) && ! ($rcp_line_id > 0) && is_array($qc_array)) {
                                $_POST["item_type_$id"] = $qc_array['item_type'];
                            } elseif (! isset($_POST["item_type_$id"]) && $rcp_line_id > 0) {
                                $_POST["item_type_$id"] = $row['rcp_item_type'];
                            }
                            custom_values_list_cells('', "item_type_$id", $daily_item_types_array, null, '', true);
                            
                            if (! isset($_POST["stock_id_$id"]) && ! ($rcp_line_id > 0) && is_array($qc_array)) {
                                $_POST["stock_id_$id"] = $qc_array['stock_id'];
                            } elseif (! isset($_POST["stock_id_$id"]) && $rcp_line_id > 0) {
                                $_POST["stock_id_$id"] = $row['rcp_stock_id'];
                            }
                            if (! isset($_POST["item_description_$id"]) && ! ($rcp_line_id > 0) && is_array($qc_array)) {
                                $_POST["item_description_$id"] = $qc_array['item_description'];
                            } elseif (! isset($_POST["item_description_$id"]) && $rcp_line_id > 0) {
                                $_POST["item_description_$id"] = $row['rcp_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($row["unit_name"]);
                            qty_cell($row["tran_qty"], true, $dec);
                            qty_cell(($row["grn_quantity"] - $row["returned_quantity"]) / $req_conversion_factor, false, $dec);
                            qty_cell($row["grn_alloc"] / $req_conversion_factor, false, $dec);
                            qty_cell(($row["grn_quantity"] + $row["grn_alloc"]) / $req_conversion_factor, true, $dec);
                            qty_cell(($row["returned_quantity"]) / $req_conversion_factor, false, $dec);
                            qty_cell(($row["returned_alloc"]) / $req_conversion_factor, false, $dec);
                            
                            if (! isset($_POST["rcp_tran_unit_$id"])) {
                                if ($rcp_line_id > 0) {
                                    $_POST["rcp_tran_unit_$id"] = $row["rcp_tran_unit"];
                                } else {
                                    $_POST["rcp_tran_unit_$id"] = $row["tran_unit"];
                                }
                            }
                            
                            if ($_POST["item_type_$id"] == NSIT_NON_STOCK_ITEM || $_POST["item_type_$id"] == NSIT_STOCK_ITEM) {
                                units_list_cells('', "rcp_tran_unit_$id", $_POST["stock_id_$id"], null, '', true);
                            } else {
                                custom_values_list_cells('', "rcp_tran_unit_$id", $units_array, null, '', true);   
                            }
                            
                            if (! isset($_POST["rcp_tran_qty_$id"])) {
                                if ($rcp_line_id > 0) {
                                    $_POST["rcp_tran_qty_$id"] = $row["rcp_tran_qty"];
                                } else {
                                    set_direct_purchase_receipt_remain_acceptable_qty($id, $row, $dec);
                                }
                            } else {
                                if (list_updated("rcp_tran_unit_$id")) {
                                    set_direct_purchase_receipt_remain_acceptable_qty($id, $row, $dec);
                                }
                            }
                            amount_cells("", "rcp_tran_qty_$id", null, null, null, $dec);
                            
                            if (! isset($_POST["site_id_$id"]) && ! ($rcp_line_id > 0)) {
                                $_POST["site_id_$id"] = $row['project_site_id'];
                            } elseif (! isset($_POST["site_id_$id"]) && $rcp_line_id > 0) {
                                $_POST["site_id_$id"] = $row['rcp_site_id'];
                            }
                            
                            if (! isset($_POST["unit_price_$id"]) && $row["unit_price"] > 0) {
                                $_POST["unit_price_$id"] = number_format($row["unit_price"], 2);
                            } elseif (! isset($_POST["unit_price_$id"]) && $qc_array["standard_cost"] > 0) {
                                $_POST["unit_price_$id"] = number_format($qc_array["standard_cost"], 2);
                            }
                            amount_cells("", "unit_price_$id", null, null, null, 2);
                            
                            all_project_sites_list_cells("", "site_id_$id", GLOBAL_VOTES, null, '', false); 
                            
                            if (! isset($_POST["line_comment_$id"]) && $rcp_line_id > 0) {
                                $_POST["line_comment_$id"] = $row['rcp_line_comment'];
                            }
                            text_cells('', "line_comment_$id", null, 20, 200, 'Line Comment');
                            
                            if ($rcp_line_id > 0 && $row['rcp_stock_control_method'] == SKCM_LOTS) {
                                $rcp_convesion_factor = 1;
                                get_convertion_factor2($_POST["stock_id_$id"], $_POST["rcp_tran_unit_$id"], $rcp_convesion_factor);
                                
                                display_lot_serial_edit_cells($row['rcp_stock_control_method'], ST_DIRECT_PURCHASE_RECEIPT, $trans_no, $rcp_line_id, $rcp_convesion_factor, 
                                                              $dec);
                            } else {
                                label_cell('');
                            }
                            
                            if (! isset($_POST["checked_$id"]) && $rcp_line_id > 0) {
                                $_POST["checked_$id"] = 1;
                            } 
                            check_cells(null, "checked_$id", null, false, false, 'align=center');

                        end_row();     
                        
                        vertical_space('height=18px colspan=20');
                    }

        end_table(2);
    
    div_end();
}

function display_quality_check_line($qc_line_id) {
    global $daily_item_types_array;
    
    $standard_cost = null;
    $dec = 4;
    $row = get_quality_check_line_with_direct_purchase_requisition_line($qc_line_id);
        start_row('style=background-color:#abdbda');
            if ($row["source_line_id"] > 0) {
                label_cell($row["source_line_id"], "align=center");
            } else {
                label_cell("No Req Line");
            }
            label_cell($qc_line_id, "align=center");
            label_cell('');
            if ($row['req_item_type'] == NSIT_NON_STOCK_ITEM || $row['req_item_type'] == NSIT_STOCK_ITEM) {
                label_cell(text_bold($row["req_stock_id"]." - ".$row["req_item_description"]));  
            } else {
                label_cell(text_bold($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"]);  
                $standard_cost = get_standard_cost($row["stock_id"]);
            } else {
                label_cell($row["item_description"]);
            }
            label_cell($row["unit_name"]);
            qty_cell($row["tran_qty"], false, $dec);
            label_cell('', 'colspan=7');          
            if ($standard_cost > 0) {
                qty_cell($standard_cost, false, 2);
            } else {
                label_cell('');
            }
            label_cell($row["site_description"]);          
            label_cell(nl2br($row["line_comment"]),'colspan=3'); 
        end_row();
        
        $item_changed = $row["req_stock_id"] != $row["stock_id"] ? true : false;
        
        return array('item_type' => $row['item_type'], 'stock_id' => $row['stock_id'], 'item_description' => $row['item_description'], 'item_changed' => $item_changed,
                     'standard_cost' => $standard_cost); 
}

function set_direct_purchase_receipt_remain_acceptable_qty($id, $row, $dec=4) {
    $convesion_factor = 1;
    get_convertion_factor2($_POST["stock_id_$id"], $_POST["rcp_tran_unit_$id"], $convesion_factor);

    $remain_tran_qty = ($row["qty"] - ($row["grn_quantity"] + $row["grn_alloc"])) / $convesion_factor;

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

function can_save_direct_purchase_receipt_header($qck_no, $rcp_no) {
    global $Refs, $systypes_array;
    
    $req_hd = get_quality_check_header_record($qck_no);
        if (is_array($req_hd)) {
            $q_trans_no = $req_hd['trans_no'];
            if (! in_array($req_hd['approval_status'], array(AS_APPROVED, AS_COMPLETED))) {
                return array("success" => false, "message" => $systypes_array[ST_QUALITY_CHECK]." Trans #$q_trans_no is not approved.");
            }
        } else {
            return array("success" => false, "message" => $systypes_array[ST_QUALITY_CHECK]." #$qck_no has been deleted by another user.");
        }
    
    $trans_no = $rcp_row_state = 0; $rcp_approval_status = AS_NEW;
    $qck_row_state = $req_hd['row_state'];
    $header = get_quality_check_header_record($rcp_no);
    
    if (($rcp_no > 0) && ! is_array($header)) {
        return array("success" => false, "message" => $systypes_array[ST_DIRECT_PURCHASE_RECEIPT]." #$rcp_no has been deleted by another user.");
    }
      
    if ($rcp_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']; $rcp_row_state = $header['row_state']; $rcp_approval_status = $header['approval_status'];
    }
    
    // check allow to add or update by user role if any new item not add or not change any item then SK only can create recs
    $can_access_msg = can_access_direct_purchase_receipt($trans_no, $q_trans_no, $rcp_approval_status);
        if ($can_access_msg['success'] === false) {
            return $can_access_msg;
        }
    
    if (! $Refs->is_valid($_POST['reference'])) {
        return array("success" => false, "focus_to" => 'reference', "message" => "Please enter a reference.");      
    }    
 
    $ref_msg = reference_exists($_POST['reference'], ST_DIRECT_PURCHASE_RECEIPT, $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, 'qck_row_state' => $qck_row_state, 'rcp_row_state' => $rcp_row_state, "message" => "", 'qc_hd' => $req_hd);    
}

function can_access_direct_purchase_receipt($trans_no=0, $q_trans_no=0, $rcp_approval_status=AS_NEW) {
    global $systypes_array;
    
    $tran_tp_name = $systypes_array[ST_DIRECT_PURCHASE_RECEIPT];
    $current_user_id = $_SESSION['wa_current_user']->user;
    
    $can_access = false; // only SK is allowed
    $correct_role = 'WMS Store Keeper';
    
    $user_recs = get_users(id: $current_user_id);
        $user_row = db_fetch($user_recs);
        $role = $user_row['role'];
        
        if ($role == $correct_role) {
            $can_access = true;
        }
    
        // when creating new direct_purchase_receipt record: only allow to SK 
        if ($trans_no == 0 && $can_access === false) {
            return array("success" => false, "message" => "Your role is not allowed to create new ".$tran_tp_name." only $correct_role allow to create new one.");
        } elseif ($trans_no > 0 && $rcp_approval_status != AS_AWAITING_APPROVAL) {

            // when awaiting approved direct_purchase_receipt record updating: only allow to SK
            $header = get_quality_check_header_record_type_trans_no(ST_DIRECT_PURCHASE_RECEIPT, $trans_no);
                if ($header['approval_status'] != AS_AWAITING_APPROVAL && $can_access === false) {
                    return array("success" => false, "message" => "Your role is not allowed to update ".$tran_tp_name." only $correct_role allow to update.");
                }

            // when approval status is AS_AWAITING_APPROVAL and quality check records have not changed any item or no new item is added 
            $changed_q_item = check_quality_check_item_edit_or_new_items_added($q_trans_no);
                if ($changed_q_item === false && $can_access === false) {
                    return array("success" => false, "message" => "Your role is not allowed to update ".$tran_tp_name." only $correct_role allow to update.");
                }

            // when approval status is AS_AWAITING_APPROVAL and no any dp receipt item is changed or no new item is added 
            $changed_rcp_item = check_direct_purchase_receipt_item_edit_or_new_items_added($trans_no, $q_trans_no);
                if ($changed_rcp_item === false && $can_access === false) {
                    return array("success" => false, "message" => "Your role is not allowed to update ".$tran_tp_name." only $correct_role allow to update.");
                }
        }
        
        return array("success" => true, "message" => "");
}

function check_quality_check_item_edit_or_new_items_added($q_trans_no) {
    // check new lines were added when quality checking.
    $qc_new_recs = get_quality_check_details_lines_count($q_trans_no, ST_QUALITY_CHECK, false);
        if ($qc_new_recs > 0) {
            return true;
        }
        
    // check quality check items were changed.        
    $old_result = get_quality_check_lines_with_edited_item_codes($q_trans_no);  
        if (db_num_rows($old_result) > 0) {
            return true;
        }
        
        return false;
}

function check_direct_purchase_receipt_item_edit_or_new_items_added($rcp_trans_no, $q_trans_no) {
    // check new lines are added when quality checking.
    $new_recs = get_quality_check_details_lines_count($q_trans_no, ST_DIRECT_PURCHASE_RECEIPT, false);
        if ($new_recs > 0) {
            return true;
        }
        
    // check old direct_purchase_receipt lines' items are edited.        
    $old_result = get_direct_purchase_lines_with_edited_item_codes($q_trans_no, $rcp_trans_no);  
        if (db_num_rows($old_result) > 0) {
            return true;
        }
        
        return false;
}

function can_save_direct_purchase_receipt_lines($qck_trans_no, $trans_no, $type, $loc_code, $process=false) {
    global $systypes_array;
    
    $result = get_quality_check_with_direct_purchase_receipt_details($qck_trans_no, $trans_no);  
        if (! (db_num_rows($result) > 0)) {
            return array('success' => false, 'message' => "No source ".$systypes_array[ST_QUALITY_CHECK]." found.");
        }
        
        $check_exceeded_only = $process === false ? true : false;
        
        while ($row = db_fetch($result)) {
            $id = $row['trans_id'];
            $rcp_line_id = $row['rcp_line_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                $item_type = $_POST["item_type_$id"];
                $stock_id = $_POST["stock_id_$id"];
                
                $rcp_tran_unit = $_POST["rcp_tran_unit_$id"];
                $rcp_tran_qty = input_num("rcp_tran_qty_$id");
                $unit_price = input_num("unit_price_$id");
                
                $convesion_factor = 1;
                
                // can save direct purchase rcp line
                $cn_sv_ln = can_save_direct_purchase_receipt_line($trans_no, $stock_id, $loc_code, $item_type, $rcp_tran_unit, $rcp_tran_qty, $convesion_factor, $rcp_line_id, 
                                                                  $id, $row, $check_exceeded_only, $unit_price);
                    if ($cn_sv_ln['success'] !== true) {
                        return array("success" => false, "message" => $cn_sv_ln['message']);
                    }
                    
            } else {
                
                if ($rcp_line_id > 0) {
                    $lot_row = get_lot_allocation_records($type, $trans_no, $rcp_line_id, fetch:true);
                    if (is_array($lot_row) > 0) {
                        return array("success" => false, "focus_to" => '',  
                                     "message" => "Please delete all ".$systypes_array[ST_LOT_ALLOCATION]." details in ".$systypes_array[$type]." GRN Line #$rcp_line_id.");
                    }
                }
            }
        }
        
        return array("success" => true, "message" => "");
}

function can_save_direct_purchase_receipt_line($trans_no, $stock_id, $loc_code, $item_type, $rcp_tran_unit, $rcp_tran_qty, $convesion_factor, $rcp_line_id, $id, $row, 
                                               $check_exceeded_only=true, $unit_price=0) {
    global $systypes_array;
    $type = ST_DIRECT_PURCHASE_RECEIPT;
    $dec = 4;
    
        if (! ($item_type > 0)) {
            return array("success" => false, "focus_to" => "item_type_$id", "message" => "Q.Check Line #$id please select an item type.");  
        }
    
        if ($item_type == NSIT_NON_STOCK_ITEM || $item_type == NSIT_STOCK_ITEM) {
            if (! (strlen($_POST["stock_id_$id"]) > 1)) {
                return array("success" => false, "focus_to" => "stock_id_$id", "message" => "Q.Check Line #$id please select an item.");  
            }

            if ($rcp_tran_unit == -1) {
                return array("success" => false, "focus_to" => "rcp_tran_unit_$id", "message" => "Q.Check Line #$id please select a tran unit.");  
            }
        } elseif ($item_type == NSIT_COMMENT) {
            if (! (strlen($_POST["item_description_$id"]) > 1)) {
                return array("success" => false, "focus_to" => "item_description_$id", "message" => "Q.Check Line #$id please enter item description.");  
            }
            
            if ($rcp_tran_unit == '0') {
                return array("success" => false, "focus_to" => "rcp_tran_unit_$id", "message" => "Q.Check Line #$id please select an unit.");  
            }
        }
        
        // check previous selected item's lot allocations
        if ($row['rcp_stock_control_method'] == SKCM_LOTS && $row['rcp_stock_id'] != $_POST["stock_id_$id"]) {
            $lot_row = get_lot_allocation_records($type, $trans_no, $rcp_line_id, fetch:true);
                if (is_array($lot_row) > 0) {
                    $lot_al = $systypes_array[ST_LOT_ALLOCATION];
                    return array("success" => false, "focus_to" => '',  
                                 "message" => "GRN Line #$rcp_line_id please delete all $lot_al details related to previous stock item.");
                }
        }

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

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

        $base_rcpd_qty = (float) get_quality_check_lines_total_by_source_line($type, $id, $rcp_line_id);
        $tran_rcpd_qty = $base_rcpd_qty / $convesion_factor;

        $total_tran_rcpd_qty = round($tran_rcpd_qty + $rcp_tran_qty, $dec);

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

        if ($total_tran_rcpd_qty > $req_this_tran_qty) {
            $total_issuable_tran_qty = round($req_this_tran_qty - $tran_rcpd_qty, $dec);

            return array("success" => false, "focus_to" => "rcp_tran_qty_$id", 
                         "message" => "Q.Check Line #$id exceeded the maximum issuable Qty of $total_issuable_tran_qty for selected unit.");  
        }
        
        if (! ($unit_price > 0)) {
            return array("success" => false, "focus_to" => "unit_price_$id", "message" => "Q.Check Line #$id unit price should be greater than zero.");  
        }
        
        $sk_row = get_stock_item_edit_info($_POST["stock_id_$id"]);

        // check lot allocation exceeded
        if (is_array($sk_row) && $sk_row['stock_control_method'] == SKCM_LOTS && $rcp_line_id > 0) {
            $data_arr = array('type' => $type, 'trans_no' => $trans_no, 'line_id' => $rcp_line_id, 'stock_id' => $stock_id, 'loc_code' => $loc_code, 
                              'conversion_factor' => $convesion_factor, 'tran_qty' => $rcp_tran_qty, 'tran_unit' => $rcp_tran_unit);
            $lot_ex_msg = check_total_lot_allocations_item_qty_exceed_allowable_qty($data_arr, $check_exceeded_only);
                if ($lot_ex_msg['success'] === false) {
                    if ($lot_ex_msg['exceeded'] === true) {
                        return array("success" => false, "message" => "GRN line #$rcp_line_id GRN Qty cannot smaller than total lot allcations."); 
                    } else {
                        return array("success" => false, "message" => "GRN line #$rcp_line_id GRN Qty cannot greater than total lot allcations."); 
                    }
                }
        }
                
        return array("success" => true, "focus_to" => "", "message" => ""); 
}

function save_direct_purchase_receipt_lines($qck_trans_no, $trans_no, $project_id, $tran_date, $loc_code, $process=false, $approval_status=AS_NEW) {
    global $systypes_array;
    $type = ST_DIRECT_PURCHASE_RECEIPT;
    
    $no_selected_recs = 0;
    $result = get_quality_check_with_direct_purchase_receipt_details($qck_trans_no, $trans_no);  
    
    $rcp_lines_count = get_quality_check_details_lines_count($trans_no, $type);
        if ($rcp_lines_count > 0) {
            $del_af_rows = delete_quality_check_detail_lines($type, $trans_no);
                if ($del_af_rows != $rcp_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'];
            $rcp_line_id = $row['rcp_line_id'];
            
            if (isset($_POST["checked_$id"]) && $_POST["checked_$id"] == 1) {
                
                $rcp_tran_unit = $_POST["rcp_tran_unit_$id"];
                $rcp_tran_qty = input_num("rcp_tran_qty_$id");
                $unit_price = input_num("unit_price_$id");
                $convesion_factor = 1;
                
                // save direct purchase rcp line
                $sv_ln_msg = save_direct_purchase_receipt_line($type, $trans_no, $rcp_tran_unit, $rcp_tran_qty, $convesion_factor, $row, $unit_price);
                    if ($sv_ln_msg['success'] !== true) {
                        cancel_transaction();
                        return array("success" => false, "message" => $sv_ln_msg['message']);
                    }
                    
                    $base_unit_price = $sv_ln_msg['base_unit_price'];
                    
                // process direct purchase rcp line 
                if ($process === true && $approval_status == AS_APPROVED) {
                    $sk_row = get_stock_item_edit_info($_POST["stock_id_$id"]);
                    $stock_control_method = is_array($sk_row) ? $sk_row['stock_control_method'] : null;
                    
                    $prs_msg = process_direct_purchase_receipt_line($type, $trans_no, $tran_date, $project_id, $loc_code, $rcp_line_id, $stock_control_method, 
                                                                    $base_unit_price);
                        if ($prs_msg['success'] !== true) {
                            cancel_transaction();
                            return array("success" => false, "message" => $prs_msg['message']);
                        }
                } 
                
                $no_selected_recs++;
            } 
        }
        
        if (! ($no_selected_recs > 0)) {
            cancel_transaction();
            return array("success" => false, "message" => "Please select at least one record before saving.");  
        }
        
        return array("success" => true, "message" => "");  
}

function save_direct_purchase_receipt_header(&$qck_no, &$rcp_no, &$trans_no, $type, $project_id, $loc_code, $tran_date, $rcp_row_state) {
    global $systypes_array;
    
    $dpr_hd_row = get_quality_check_header_record($qck_no);
        $jo_id = $dpr_hd_row['jo_id'];
    $af_no = write_quality_check_header($jo_id, $type, $qck_no, $rcp_no, $trans_no, $_POST['reference'], $project_id, $loc_code, $_POST['comments'], $tran_date, 
                                        $rcp_row_state); 
    
        if ($af_no > 0) {
            return array("success" => true, "message" => $systypes_array[$type]." header record #$rcp_no has been saved.");
        } else {
            return array("success" => false, "message" => "Could not be saved ".$systypes_array[$type].' header.');
        }
}

function save_direct_purchase_receipt_line($type, $trans_no, $tran_unit, $tran_qty, $conversion_factor, $row, $unit_price) {    
    global $systypes_array;
    
        $id = $row['trans_id'];
        $rcp_line_id = $row['rcp_line_id'];

        $item_type = $_POST["item_type_$id"];
        $stock_id = $_POST["stock_id_$id"];
        $item_description = $_POST["item_description_$id"];
        $site_id = $_POST["site_id_$id"];
        $line_comment = $_POST["line_comment_$id"];
        $task_id = $row['task_id'];
                
            get_convertion_factor2($stock_id, $tran_unit, $conversion_factor);

            $base_qty = $tran_qty * $conversion_factor;
            $base_unit_price = $unit_price / $conversion_factor;
            
            $ln_id = insert_quality_check_line($trans_no, $type, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, $base_qty, $conversion_factor, $unit_price, 
                                               $site_id, $line_comment, $task_id, $id, $rcp_line_id);

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

function save_direct_purchase_receipts(&$qck_no, &$rcp_no, $process=false) {
    global $systypes_array;
    
    $req_type = ST_QUALITY_CHECK; $type = ST_DIRECT_PURCHASE_RECEIPT;
    
    $cn_sv_hd = can_save_direct_purchase_receipt_header($qck_no, $rcp_no);   
        if ($cn_sv_hd["success"] !== true) {          
            return $cn_sv_hd;
        }
        
        $qck_row_state = $cn_sv_hd['qck_row_state']; $rcp_row_state = $cn_sv_hd['rcp_row_state'];
        $qc_hd = $cn_sv_hd['qc_hd']; $qck_trans_no = $qc_hd['trans_no']; $project_id = $qc_hd['project_id'];
        
    $trans_no = $approval_status = AS_NEW; 
    $rcp_hd_row = get_quality_check_header_record($rcp_no);
        if (is_array($rcp_hd_row)) {
            $trans_no = $rcp_hd_row['trans_no']; 
        }
        
    $cn_sv_line = can_save_direct_purchase_receipt_lines($qck_trans_no, $trans_no, $type, $_POST['location'], $process);   
        if ($cn_sv_line["success"] !== true) {          
            return $cn_sv_line;
        }
        
    $tran_date = date2sql($_POST['tran_date']);
       
        begin_transaction();

            $hd_msg = save_direct_purchase_receipt_header($qck_no, $rcp_no, $trans_no, $type, $project_id, $_POST['location'], $tran_date, $rcp_row_state);
                if ($hd_msg["success"] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $hd_msg['message']);
                }
                
            if ($process === true) {
                $ap_msg = approve_direct_purchase_receipt($qck_trans_no, $rcp_no, $trans_no);
                    if ($ap_msg['success'] === false ) {
                        cancel_transaction();
                        return $ap_msg;
                    }
                    
                    $approval_status = $ap_msg["approval_status"];
            }
                
            $sv_ln_msg = save_direct_purchase_receipt_lines($qck_trans_no, $trans_no, $project_id, $tran_date, $_POST['location'], $process, $approval_status);
                if ($sv_ln_msg['success'] !== true) {
                    cancel_transaction();
                    return $sv_ln_msg;       
                }
            
            // save direct purchase receipt grn returned qty => this should be called after lines saving becouse it checks with approval status
            $sv_is_rt_qty = save_quality_check_lines_grn_returned_qty_total($req_type, $qck_trans_no, $type);
                if ($sv_is_rt_qty['success'] !== true) {
                    cancel_transaction();
                    return $sv_is_rt_qty;
                }

            $all_rcpd = check_all_quality_check_lines_fully_grn($req_type, $qck_trans_no);
                if ($all_rcpd === true && $qc_hd['approval_status'] == AS_APPROVED) {
                    $qc_msg = direct_update_document_status($req_type, $qck_trans_no, AS_COMPLETED, $qck_row_state);     
                        if ($qc_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." approval status.");
                        }

                    $qck_row_state = db_new_row_state($qck_row_state);
                } elseif ($all_rcpd === false && $qc_hd['approval_status'] == AS_COMPLETED) {
                    $qc_msg = direct_update_document_status($req_type, $qck_trans_no, AS_APPROVED, $qck_row_state);     
                        if ($qc_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." approval status.");
                        }

                    $qck_row_state = db_new_row_state($qck_row_state);
                }
                
            $req_af = update_quality_check_row_state($req_type, $qck_trans_no, $qck_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." trans #$qck_trans_no row state.");
                }
                
        commit_transaction();
            
            if ($process === true) {
                set_session_variable('dp_rec_messages', $ap_msg['message']);
                meta_forward($_SERVER['PHP_SELF'], "type=$type&ProcessedID=$trans_no"); 
            } else {
                return array("success" => true, "message" => $systypes_array[$type]." Trans #$trans_no has been saved.");
            }
}

function process_direct_purchase_receipt_line($type, $trans_no, $tran_date, $project_id, $loc_code, $rcp_line_id, $stock_control_method, $base_unit_price) {
    $row = get_quality_check_details_line_by_type_trans_no_line_no($type, $trans_no, $rcp_line_id);
            
        // stock move
        $stk_mv_msg = process_direct_purchase_receipt_item($trans_no, $type, $tran_date, $project_id, $loc_code, $row, $base_unit_price);
            if ($stk_mv_msg['success'] === false) {
                cancel_transaction();
                return $stk_mv_msg;
            }
            
        // lot move
        if ($stock_control_method == SKCM_LOTS) {
            $lot_mv_msg = lot_allocations_to_lot_moves($type, $trans_no, $rcp_line_id);
                if ($lot_mv_msg['success'] === false) {
                    cancel_transaction();
                    return $lot_mv_msg;
                }
                
            $lot_loc_array = $lot_mv_msg['lot_loc_array'];
            
            // update lot balances
            $lot_bl_msg = save_lot_balances_from_array($lot_loc_array);
                if ($lot_bl_msg['success'] === false) {
                    cancel_transaction();
                    return $lot_bl_msg;
                }
        }

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

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

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

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

function approve_direct_purchase_receipt($q_trans_no, $rcp_no, $rcp_trans_no) {
    global $systypes_array;
    
    $current_user_id = $_SESSION['wa_current_user']->user;
    $task_costs = 0;
    
    $header = get_quality_check_header_record($rcp_no);
    
    // quality check records have not changed any item or no new item is added 
    $changed_q_item = check_quality_check_item_edit_or_new_items_added($q_trans_no);

    // when approval status is AS_AWAITING_APPROVAL and no any item changed or no new item is added 
    $changed_rcp_item = check_direct_purchase_receipt_item_edit_or_new_items_added($rcp_trans_no, $q_trans_no);

        if ($changed_q_item === true || $changed_rcp_item === true) {
            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']);
        } else {
            $ap_msg = direct_update_document_status($header['type'], $header['trans_no'], AS_APPROVED, $header['row_state']);     
                if ($ap_msg['success'] === false ) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not approve ".$systypes_array[$header['type']].".");
                }
        } 
        
        return array("success" => true, "message" => $systypes_array[$header['type']]." #$rcp_trans_no has been approved.", 'approval_status' => AS_APPROVED);
}

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

        if (! isset($hd_row['type']) || $hd_row['type'] != ST_DIRECT_PURCHASE_RECEIPT) {
            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_DIRECT_PURCHASE_RECEIPT, $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_direct_purchase_receipt($qck_no, $rcp_no) {
    global $systypes_array;
    
    $req_type = ST_QUALITY_CHECK;
    $type = ST_DIRECT_PURCHASE_RECEIPT;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_direct_purchase_receipt($qck_no, $rcp_no, $trans_tp_name, true);
        if ($cn_rej["success"] !== true) { 
            return $cn_rej;
        } 
        
        $req_hd_row = $cn_rej["req_hd_row"];
            $qck_row_state = $req_hd_row['row_state'];
            $qck_trans_no = $req_hd_row["trans_no"];
            $qck_ap_st = $req_hd_row["approval_status"];
        
        $hd_row = $cn_rej["hd_row"];
            $trans_no = $hd_row["trans_no"];
            $row_state = $hd_row["row_state"];
        
        begin_transaction();
        
            $rj_msg = reject_document($type, $trans_no, $hd_row['project_id'], $hd_row['next_approval_group_id'], $_SESSION['wa_current_user']->user, $row_state);
                if ($rj_msg['success'] !== true) {
                    cancel_transaction();
                    return array("success" => false, "message" => $rj_msg['message']);
                }
                
            // save direct purchase receipt grn returned qty => this should be called after lines saving becouse it checks with approval status
            $sv_is_rt_qty = save_quality_check_lines_grn_returned_qty_total($req_type, $qck_trans_no, $type);
                if ($sv_is_rt_qty['success'] !== true) {
                    cancel_transaction();
                    return $sv_is_rt_qty;
                }

            $all_rcpd = check_all_quality_check_lines_fully_grn($req_type, $qck_trans_no);
                if ($all_rcpd === true && $qck_ap_st == AS_APPROVED) {
                    $qc_msg = direct_update_document_status($req_type, $qck_trans_no, AS_COMPLETED, $qck_row_state);     
                        if ($qc_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." approval status.");
                        }

                    $qck_row_state = db_new_row_state($qck_row_state);
                } elseif ($all_rcpd === false && $qck_ap_st == AS_COMPLETED) {
                    $qc_msg = direct_update_document_status($req_type, $qck_trans_no, AS_APPROVED, $qck_row_state);     
                        if ($qc_msg['success'] === false ) {
                            cancel_transaction();
                            return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." approval status.");
                        }

                    $qck_row_state = db_new_row_state($qck_row_state);
                }
                
            $req_af = update_quality_check_row_state($req_type, $qck_trans_no, $qck_row_state);
                if (! ($req_af > 0)) {
                    cancel_transaction();
                    return array("success" => false, "message" => "Could not update ".$systypes_array[$req_type]." trans #$qck_trans_no row state.");
                }
            
        commit_transaction();

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

function back_to_originator_direct_purchase_receipt($qck_no, $rcp_no) {
    global $systypes_array;
    
    $type = ST_DIRECT_PURCHASE_RECEIPT;
    $trans_tp_name = $systypes_array[$type];
    
    $cn_rej = can_reject_back_to_originator_direct_purchase_receipt($qck_no, $rcp_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('dp_rec_bo_messages', $ap_msg['message']);
            meta_forward($_SERVER['PHP_SELF'], "type=$type&BackedOrgID=$trans_no"); 
}

function view_direct_purchase_receipt_header($type, $trans_no) {
    global $approval_statuses;
    
    $row = get_quality_check_header_type_trans_no($type, $trans_no);
        if ($type == ST_DIRECT_PURCHASE_RECEIPT) {
            $parnt_tp = ST_QUALITY_CHECK;
            $parnt_tname = 'Q.Check';
        } elseif ($type == ST_DIRECT_PURCHASE_RETURN) {
            $parnt_tp = ST_DIRECT_PURCHASE_RECEIPT;
            $parnt_tname = 'GRN';
        }
        
    $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%");
                $re_hd = get_quality_check_header_record($row['dpr_no']);
                $jo_id = $re_hd['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'"); 
                }
                label_row("$parnt_tname Trans #:", get_supplier_trans_view_str($parnt_tp, $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_direct_purchase_receipt_details($type, $trans_no) {
    global $daily_item_types_array;
    
    $view_tp = ST_LOT_ALLOCATION;
    $hd_row = get_quality_check_header_record_type_trans_no($type, $trans_no);
        if (in_array($hd_row['approval_status'], array(AS_APPROVED))) {
            $view_tp = ST_LOT_MOVE;
        }
        
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($hd_row['project_id'], $user_id);
        if ($cap['success'] !== true) {
            display_error($cap["message"]);
            display_footer_exit();
            exit;
        }
    
    start_table(TABLESTYLE, "width=99%");

        $th = array(_("ID"), _("QC Line"), _("DP.Req Line"), _("DPR Item"), _("QC Item"), _("Item Type"), _("Description"), _("Tran Unit"), _("Tran Qty"), _("Base Unit"), 
                    _("Base Qty"), _("Returned Qty"), _("Returned Alloc"), _('Budget'), _('Unit Price'), _('Project Site'), _('Comment'));  
        table_header($th);

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

                    if ($row["stock_id"] != $row["qc_stock_id"] || $row["qc_stock_id"] != $row["req_stock_id"]) {
                        start_row("style=background-color:#f3cbf7");
                    } else {
                        alt_table_row_color($k);
                    }

                        $trans_id = $row['trans_id'];
                        
                        if ($row['stock_control_method'] == SKCM_LOTS) {
                            $params = "type=".$type."&trans_no=$trans_no&line_id=$trans_id";
                            label_cell(get_data_view_str($view_tp, $params, $trans_id), 'align=center');
                        } else {
                            label_cell($row['trans_id'], 'align=center');
                        }
                        
                        label_cell($row['qc_line_id'], 'align=center');
                        if ($row['req_line_id'] > 0) {
                            label_cell($row['req_line_id'], 'align=center');
                        } else {
                            label_cell('No DPR Line');
                        }
                            
                        if ($row['req_item_type'] == NSIT_NON_STOCK_ITEM || $row['req_item_type'] == NSIT_STOCK_ITEM) {
                            label_cell(text_bold($row["req_stock_id"]." - ".$row["req_item_description"]));  
                        } else {
                            label_cell(text_bold($row["req_item_description"]));
                        }
                            
                        if ($row['qc_item_type'] == NSIT_NON_STOCK_ITEM || $row['qc_item_type'] == NSIT_STOCK_ITEM) {
                            label_cell($row["qc_stock_id"]." - ".$row["qc_item_description"]);  
                        } else {
                            label_cell($row["qc_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"]);  
                        } else {
                            label_cell($row["item_description"]);
                        }
                        label_cell($row["unit_name"]);
                        
                        $params = "type=".$type."&trans_no=$trans_no&line_id=$trans_id";
                        if ($row['stock_control_method'] == SKCM_LOTS) {
                            label_cell(get_data_view_str($view_tp, $params, number_format($row["tran_qty"], $dec)), 'align=right');
                        } else {
                            qty_cell($row["tran_qty"], false, $dec);
                        }
                        
                        label_cell(get_item_base_unit_name($row["stock_id"]));
                        if ($row['stock_control_method'] == SKCM_LOTS) {
                            label_cell(get_data_view_str($view_tp, $params, number_format($row["qty"], $dec)), 'align=right');
                        } else {
                            qty_cell($row["qty"], false, $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"]);
                        }
                        
                        if ($row["standard_cost"] > 0) {
                            qty_cell($row["standard_cost"], false, 2);
                        } else {
                            label_cell('');
                        }
                            
                        label_cell($row["site_description"]);          
                        label_cell(nl2br($row["line_comment"]));          

                    end_row();        
                }

    end_table(2);
}

function view_direct_purchase_receipt_return_headers($qck_no, $type) {
    $parent_row = get_quality_check_header_record($qck_no);
    
    $user_id = $_SESSION['wa_current_user']->user;
    $cap = can_access_project($parent_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($qck_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);
}

?>