<?php

function write_outside_material_receipt_header($type, $omr_no, &$id, &$trans_no, $reference, $project_id, $from_location, $to_loc_code, $comments, $date, $receipt_row_state, 
                                               $jo_id, $source_id=0) {
    global $Refs;
     
        if ($trans_no > 0) {
            $af_row = update_outside_material_receipt_header($id, $reference, $from_location, $to_loc_code, $comments, $date, $receipt_row_state);
                if (! ($af_row > 0)) {
                    return 0;
                }
        } else {
            $trans_no = get_next_trans_no($type);
            $id = insert_outside_material_receipt_header($type, $omr_no, $trans_no, $reference, $project_id, $from_location, $to_loc_code, $comments, $date, $jo_id, 
                                                         $source_id);
        }
    
        $Refs->save($type, $trans_no, $reference);

        if (! ($id > 0)) {
            return 0;
        }

        return $id;
}
     
function insert_outside_material_receipt_header($type, $omr_no, $trans_no, $reference, $project_id, $from_location, $to_loc_code, $comments, $date, $jo_id, $source_id=0) {
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
        $sql = "INSERT INTO ".TB_PREF."outside_material_receipts
                      ( type, omr_no, trans_no, reference, 
                        project_id, from_location, to_loc_code, comments, 
                        tran_date, jo_id, created_by, created_on, source_id )         
                VALUES( ".db_escape($type).", ".db_escape($omr_no).", ".db_escape($trans_no).", ".db_escape($reference).", 
                        ".db_escape($project_id).", ".db_escape($from_location).", ".db_escape($to_loc_code).", ".db_escape($comments).", 
                        ".db_escape($date).", ".db_escape($jo_id).", ".db_escape($created_by).", ".db_escape($created_on).", ".db_escape($source_id).")";

            db_query($sql, 'insert_outside_material_receipt_header');
            return db_insert_id();        
}

// from location and to location do not update because details lines table has thse locations
function update_outside_material_receipt_header($id, $reference, $from_location, $to_loc_code, $comments, $date, $receipt_row_state) {   
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql = "UPDATE ".TB_PREF."outside_material_receipts
                SET reference = ".db_escape($reference).",
                    tran_date = ".db_escape($date).",
                    from_location = ".db_escape($from_location).",
                    to_loc_code = ".db_escape($to_loc_code).",
                    comments = ".db_escape($comments).", 
                    updated_by = ".db_escape($updated_by).", 
                    updated_on = ".db_escape($updated_on).",
                    row_state = ". db_new_row_state($receipt_row_state)." 
                WHERE id = ".db_escape($id)."   
                    AND row_state = ".db_escape($receipt_row_state);    

            db_query($sql, "update_outside_material_receipt_header");
            return db_num_affected_rows();
}

function insert_outside_material_receipt_line($trans_no, $type, $from_location, $to_loc_code, $tran_date, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, 
                                              $qty, $conversion_factor, $standard_cost, $project_site_id, $line_comment, $task_id, $source_line_id=0, $line_id=0) {
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
        if ($line_id > 0) {
            $sql = "INSERT INTO ".TB_PREF."outside_material_receipt_details
                          ( trans_id, trans_no, type, from_location, 
                            to_loc_code, tran_date, stock_id, tran_unit, 
                            item_type, item_description, tran_qty, qty, 
                            conversion_factor, task_id, standard_cost, project_site_id, 
                            line_comment, created_by, created_on, source_line_id)        
                    VALUE ( ".db_escape($line_id).", ".db_escape($trans_no).", ".db_escape($type).", ".db_escape($from_location).",
                            ".db_escape($to_loc_code).", ".db_escape($tran_date).", ".db_escape($stock_id).", ".db_escape($tran_unit).",  
                            ".db_escape($item_type).", ".db_escape($item_description).", ".db_escape($tran_qty).", ".db_escape($qty).", 
                            ".db_escape($conversion_factor).", ".db_escape($task_id).", ".db_escape($standard_cost).", ".db_escape($project_site_id).", 
                            ".db_escape($line_comment).", ".db_escape($created_by).", ".db_escape($created_on).", ".db_escape($source_line_id)." )";     
        } else {
            $sql = "INSERT INTO ".TB_PREF."outside_material_receipt_details
                          ( trans_no, type, from_location, to_loc_code, 
                            tran_date, stock_id, tran_unit, item_type, 
                            item_description, tran_qty, qty, conversion_factor, 
                            task_id, standard_cost, project_site_id, line_comment, 
                            created_by, created_on, source_line_id)        
                    VALUE ( ".db_escape($trans_no).", ".db_escape($type).", ".db_escape($from_location).", ".db_escape($to_loc_code).",
                            ".db_escape($tran_date).", ".db_escape($stock_id).", ".db_escape($tran_unit).", ".db_escape($item_type).", 
                            ".db_escape($item_description).", ".db_escape($tran_qty).", ".db_escape($qty).", ".db_escape($conversion_factor).", 
                            ".db_escape($task_id).", ".db_escape($standard_cost).", ".db_escape($project_site_id).", ".db_escape($line_comment).", 
                            ".db_escape($created_by).", ".db_escape($created_on).", ".db_escape($source_line_id)." )";     
        }

            db_query($sql, 'insert_outside_material_receipt_line');
            return db_insert_id();  
}

function update_outside_material_receipt_line($id, $from_location, $to_loc_code, $item_type, $stock_id, $item_description, $tran_unit, $tran_qty, $qty, $conversion_factor, 
                                              $task_id=0, $project_site_id=0, $standard_cost=0, $line_comment='') {   
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql = "UPDATE ".TB_PREF."outside_material_receipt_details 
                SET from_location = ".db_escape($from_location).",
                    to_loc_code = ".db_escape($to_loc_code).",
                    item_type = ".db_escape($item_type).",
                    stock_id = ".db_escape($stock_id).", 
                    item_description = ".db_escape($item_description).", 
                    tran_unit = ".db_escape($tran_unit).", 
                    tran_qty = ".db_escape($tran_qty).", 
                    qty = ".db_escape($qty).", 
                    conversion_factor = ".db_escape($conversion_factor).", 
                    task_id = ".db_escape($task_id).", 
                    standard_cost = ".db_escape($standard_cost).", 
                    project_site_id = ".db_escape($project_site_id).", 
                    line_comment = ".db_escape($line_comment).", 
                    updated_by = ".db_escape($updated_by).", 
                    updated_on = ".db_escape($updated_on)." 
                WHERE trans_id = ".db_escape($id);   

            db_query($sql, "update_outside_material_receipt_line");
            return db_num_affected_rows();
}

function get_outside_material_receipt_header_record($id) {
    $sql = "SELECT * 
            FROM ".TB_PREF."outside_material_receipts    
            WHERE id = ".db_escape($id);
    
        $result = db_query($sql, "get_outside_material_receipt_header_record");
        return db_fetch($result);
}

function get_outside_material_receipt_header($id) {
    $sql = "SELECT sa.*,
                l.location_name from_location_name,
                l2.location_name to_location_name,
                pm.description project_description,
                u.real_name requestor_name 
            FROM ".TB_PREF."outside_material_receipts sa 
                JOIN ".TB_PREF."projects_master pm 
                    ON sa.project_id = pm.project_id 
                JOIN ".TB_PREF."users u 
                    ON sa.created_by = u.id 
                LEFT JOIN ".TB_PREF."locations l 
                    ON sa.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON sa.to_loc_code = l2.loc_code 
            WHERE sa.id = ".db_escape($id);
    
        $result = db_query($sql, "get_outside_material_receipt_header");
        return db_fetch($result);
}

function get_outside_material_receipt_header_type_trans_no($type, $trans_no) {
    $sql = "SELECT sa.*,
                l.location_name from_location_name,
                l2.location_name to_location_name,
                pm.description project_description,
                u.real_name requestor_name 
            FROM ".TB_PREF."outside_material_receipts sa 
                JOIN ".TB_PREF."projects_master pm 
                    ON sa.project_id = pm.project_id 
                JOIN ".TB_PREF."users u 
                    ON sa.created_by = u.id 
                LEFT JOIN ".TB_PREF."locations l 
                    ON sa.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON sa.to_loc_code = l2.loc_code 
            WHERE sa.type = ".db_escape($type)." 
                AND sa.trans_no = ".db_escape($trans_no);
    
        $result = db_query($sql, "get_outside_material_receipt_header_type_trans_no");
        return db_fetch($result);
}

function get_outside_material_receipt_header_record_type_trans_no($type, $trans_no) {
    $sql = "SELECT * 
            FROM ".TB_PREF."outside_material_receipts    
            WHERE type = ".db_escape($type)." 
                AND trans_no = ".db_escape($trans_no);
    
        $result = db_query($sql, "get_outside_material_receipt_header_record_type_trans_no");
        return db_fetch($result);
}

function get_outside_material_receipt_details($trans_no, $type) {
    $sql = "SELECT ard.*,
                am.description stock_description,
                am.stock_id,
                am.mb_flag,
                un.name unit_name,
                ps.description site_description, 
                pt.description task_description, 
                am.stock_control_method   
            FROM ".TB_PREF."outside_material_receipt_details ard 
                LEFT JOIN ".TB_PREF."locations l 
                    ON ard.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON ard.to_loc_code = l2.loc_code 
                LEFT JOIN ".TB_PREF."stock_master am 
                    ON ard.stock_id = am.stock_id 
                LEFT JOIN ".TB_PREF."item_units un  
                    ON ard.tran_unit = un.abbr  
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON ard.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON ard.task_id = pt.task_id 
            WHERE ard.trans_no = ".db_escape($trans_no)." 
                AND ard.type = ".db_escape($type);
    
        return db_query($sql, "get_outside_material_receipt_details");
}

function get_outside_material_receipt_lines($trans_no, $type) {
    $sql = "SELECT * 
            FROM ".TB_PREF."outside_material_receipt_details   
            WHERE trans_no = ".db_escape($trans_no)." 
                AND type = ".db_escape($type);
    
        return db_query($sql, "get_outside_material_receipt_lines");
}

function get_outside_material_receipt_details_with_om_requsition_details($trans_no, $type) {
    $sql = "SELECT ard.*,
                am.description stock_description,
                am.stock_id,
                am.mb_flag,
                un.name unit_name,
                ps.description site_description, 
                pt.description task_description, 
                am.stock_control_method,
                omrc_rd.stock_id request_stock_id,
                am2.description request_stock_description 
            FROM ".TB_PREF."outside_material_receipt_details ard 
                JOIN ".TB_PREF."locations l 
                    ON ard.to_loc_code = l.loc_code 
                JOIN ".TB_PREF."stock_master am 
                    ON ard.stock_id = am.stock_id 
                JOIN ".TB_PREF."item_units un  
                    ON ard.tran_unit = un.abbr  
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON ard.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON ard.task_id = pt.task_id 
                LEFT JOIN ".TB_PREF."outside_material_requisition_details omrc_rd 
                    ON ard.source_line_id = omrc_rd.trans_id  
                        AND omrc_rd.type = ".db_escape(ST_OUTSIDE_MATERIAL_REQ)." 
                LEFT JOIN ".TB_PREF."stock_master am2  
                    ON omrc_rd.stock_id = am2.stock_id              
            WHERE ard.trans_no = ".db_escape($trans_no)." 
                AND ard.type = ".db_escape($type);
    
        return db_query($sql, "get_outside_material_receipt_details_with_om_requsition_details");
}

function get_outside_material_requisition_with_outside_material_receipt_details($req_trans_no, $receipt_trans_no) {
    $sql = "SELECT ard.*,
                am.description stock_description,
                am.stock_id,
                am.mb_flag,
                am.stock_control_method,
                un.name unit_name,
                ps.description site_description, 
                pt.description task_description, 
                omrcd.trans_id receipt_line_id, 
                omrcd.item_type receipt_item_type, 
                omrcd.stock_id receipt_stock_id, 
                omrcd.item_description receipt_item_description, 
                omrcd.tran_unit receipt_tran_unit, 
                omrcd.tran_qty receipt_tran_qty, 
                omrcd.task_id receipt_task_id, 
                omrcd.project_site_id receipt_project_site_id, 
                omrcd.line_comment receipt_line_comment 
            FROM ".TB_PREF."outside_material_requisition_details ard 
                JOIN ".TB_PREF."outside_material_requisitions mth  
                    ON ard.type = mth.type   
                        AND ard.trans_no = mth.trans_no  
                JOIN ".TB_PREF."locations l 
                    ON mth.to_loc_code = l.loc_code 
                LEFT JOIN ".TB_PREF."stock_master am 
                    ON ard.stock_id = am.stock_id 
                LEFT JOIN ".TB_PREF."item_units un  
                    ON ard.tran_unit = un.abbr  
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON ard.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON ard.task_id = pt.task_id 
                LEFT JOIN ".TB_PREF."outside_material_receipt_details omrcd 
                    ON ard.trans_id = omrcd.source_line_id  
                        AND omrcd.type = ".db_escape(ST_OUTSIDE_MATERIAL_RECEIPT)." 
                        AND omrcd.trans_no = ".db_escape($receipt_trans_no)." 
            WHERE ard.trans_no = ".db_escape($req_trans_no)." 
                AND ard.type = ".db_escape(ST_OUTSIDE_MATERIAL_REQ)." 
            ORDER BY ard.trans_id";
    
        return db_query($sql, "get_outside_material_requisition_with_outside_material_receipt_details");
}

function get_outside_material_receipt_details_with_no_source($receipt_trans_no, $type) {
    $sql = "SELECT ard.*,
                am.description stock_description,
                am.stock_id,
                am.mb_flag,
                am.stock_control_method,
                un.name unit_name,
                ps.description site_description, 
                pt.description task_description, 
                ard.trans_id receipt_line_id, 
                ard.item_type receipt_item_type, 
                ard.stock_id receipt_stock_id, 
                ard.item_description receipt_item_description, 
                ard.tran_unit receipt_tran_unit, 
                ard.tran_qty receipt_tran_qty  
            FROM ".TB_PREF."outside_material_receipt_details ard 
                LEFT JOIN ".TB_PREF."stock_master am 
                    ON ard.stock_id = am.stock_id 
                LEFT JOIN ".TB_PREF."item_units un  
                    ON ard.tran_unit = un.abbr  
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON ard.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON ard.task_id = pt.task_id 
            WHERE ard.trans_no = ".db_escape($receipt_trans_no)." 
                AND ard.type = ".db_escape($type)." 
                AND ard.source_line_id = 0  
            ORDER BY ard.trans_id";
    
        return db_query($sql, "get_outside_material_receipt_details_with_no_source");
}

function get_outside_material_receipt_detail_records_with_no_source($type, $trans_no) {
    $sql = "SELECT * 
            FROM ".TB_PREF."outside_material_receipt_details   
            WHERE type = ".db_escape($type)." 
                AND trans_no = ".db_escape($trans_no)." 
                AND source_line_id = 0";
    
        return db_query($sql, "get_outside_material_receipt_detail_records_with_no_source");
}

function get_outside_material_receipt_details_lines_count($trans_no, $type, $has_source_line=null, $not_id=0) {
    $sql = "SELECT COUNT(trans_id) lines_count 
            FROM ".TB_PREF."outside_material_receipt_details 
            WHERE trans_no = ".db_escape($trans_no)." 
                AND type = ".db_escape($type);
    
        if ($has_source_line === false) {
            $sql .= " AND source_line_id = 0";
        } elseif ($has_source_line === true) {
            $sql .= " AND source_line_id > 0";
        }
        
        if ($not_id > 0) {
            $sql .= " AND trans_id <> ".db_escape($not_id);
        }
    
        $result = db_query($sql, 'get_outside_material_receipt_details_lines_count');
        return db_result_value($result, 'lines_count');
}

function update_outside_material_receipt_header_approval_status($type, $trans_no, $pre_status, $new_status) {
    $approved_by = $_SESSION['wa_current_user']->user;
    $approved_on = date('Y-m-d H:i:s');

        $sql = "UPDATE ".TB_PREF."outside_material_receipts
                SET approval_status = ".db_escape($new_status).",
                    approved_by = ".db_escape($approved_by).", 
                    approved_on = ".db_escape($approved_on)." 
                WHERE type = ".db_escape($type)."   
                    AND trans_no = ".db_escape($trans_no)."   
                    AND approval_status = ".db_escape($pre_status);    

            db_query($sql, "update_outside_material_receipt_header_approval_status");
            return db_num_affected_rows();
}

function get_outside_material_receipt_lines_total_by_source_line($type, $source_line_id, $not_trans_id=0) {
    $sql = "SELECT SUM(qty) total_qty 
            FROM ".TB_PREF."outside_material_receipt_details 
            WHERE source_line_id = ".db_escape($source_line_id)." 
                AND type = ".db_escape($type);
    
        if ($not_trans_id > 0) {
            $sql .= " AND trans_id <> ".db_escape($not_trans_id);
        }
    
        $result = db_query($sql, 'get_outside_material_receipt_lines_total_by_source_line');
        return db_result_value($result, 'total_qty');
}

function save_outside_material_requisition_lines_receipt_alloc_receipt_qty_total($type, $trans_no) {
    global $systypes_array;
    
    $result = get_outside_material_requisition_lines($trans_no, $type);
        while ($row = db_fetch($result)) {
            $id = $row['trans_id'];
            $row_state = $row['row_state'];
            $returned_quantity = $row['returned_quantity'];
            
            $up_af_rw = update_outside_material_requisition_line_receipt_alloc_qty_receipt_qty($id, $row_state, $returned_quantity);
                if ($up_af_rw != 1) {
                    return array("success" => false, "message" => 'Could not update '.$systypes_array[$type].' total receipt/ receipt alloc qty.');
                }
        }
        
        return array("success" => true, "message" => '');
}

function get_outside_material_receipt_lines_total_qty($type, $source_line_id, $ap_array, $not_trans_id=0) {
    $sql = "SELECT SUM(ln.qty) total_qty 
            FROM ".TB_PREF."outside_material_receipt_details ln 
                JOIN ".TB_PREF."outside_material_receipts hd  
                    ON ln.type = hd.type 
                        AND ln.trans_no = hd.trans_no  
            WHERE ln.source_line_id = ".db_escape($source_line_id)." 
                AND hd.type = ".db_escape($type)."
                AND hd.approval_status IN (". implode(',', $ap_array).")";
    
        if ($not_trans_id > 0) {
            $sql .= " AND ln.trans_id <> ".db_escape($not_trans_id);
        }
    
        $result = db_query($sql, 'get_outside_material_receipt_lines_total_qty');
        return db_result_value($result, 'total_qty');
}

function update_outside_material_requisition_line_receipt_alloc_qty_receipt_qty($trans_id, $req_line_row_state=0, $returned_quantity=0) {
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $ap_array = array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR);
        $total_receipt_alloc_qty_ = get_outside_material_receipt_lines_total_qty(ST_OUTSIDE_MATERIAL_RECEIPT, $trans_id, $ap_array);
        $total_receipt_alloc_qty = abs($total_receipt_alloc_qty_);

        $total_receipt_qty_ = get_outside_material_receipt_lines_total_qty(ST_OUTSIDE_MATERIAL_RECEIPT, $trans_id, array(AS_APPROVED, AS_COMPLETED));
        $total_receipt_qty = abs($total_receipt_qty_);

        $total_qty_receipt_qty_receipt_alloc_qty = $total_receipt_qty + $total_receipt_alloc_qty - $returned_quantity;
            
            $sql = "UPDATE ".TB_PREF."outside_material_requisition_details  
                    SET receipt_alloc = ".db_escape($total_receipt_alloc_qty).",  
                        updated_by = ".db_escape($updated_by).", 
                        updated_on = ".db_escape($updated_on).",  
                        row_state = ".db_new_row_state($req_line_row_state)." 
                    WHERE trans_id = ".db_escape($trans_id)." 
                        AND qty >= $total_qty_receipt_qty_receipt_alloc_qty";
            
            db_query($sql, 'update_outside_material_requisition_line_receipt_alloc_qty_receipt_qty');
                $af_row = db_num_affected_rows();
            
                    if ($af_row != 1) {
                        return 0;
                    }
            
    $nw_qch_line_row_state = db_new_row_state($req_line_row_state);
    $nw_updated_on = date('Y-m-d H:i:s');
            
            $sql_1 = "UPDATE ".TB_PREF."outside_material_requisition_details  
                    SET receipt_quantity = ".db_escape($total_receipt_qty).",  
                        updated_by = ".db_escape($updated_by).", 
                        updated_on = ".db_escape($nw_updated_on).",  
                        row_state = ".db_new_row_state($nw_qch_line_row_state)." 
                    WHERE trans_id = ".db_escape($trans_id)." 
                        AND qty >= $total_qty_receipt_qty_receipt_alloc_qty";
            
            db_query($sql_1, 'update_outside_material_requisition_line_receipt_alloc_qty_receipt_qty');
                $af_row_2 = db_num_affected_rows();

                    if ($af_row_2 != 1) {
                        return 0;
                    } 
                    
        return 1;
}

function update_outside_material_receipt_line_returned_alloc_returned($trans_id, $line_row_state=0) {
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $ap_array = array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR);
        $total_returned_alloc_qty_ = get_outside_material_receipt_lines_total_qty(ST_OUTSIDE_MATERIAL_RETURN, $trans_id, $ap_array);
        $total_returned_alloc_qty = abs($total_returned_alloc_qty_);

        $total_returned_qty_ = get_outside_material_receipt_lines_total_qty(ST_OUTSIDE_MATERIAL_RETURN, $trans_id, array(AS_APPROVED));
        $total_returned_qty = abs($total_returned_qty_);
        
        $all_returned_qty = $total_returned_alloc_qty + $total_returned_qty;

            $sql = "UPDATE ".TB_PREF."outside_material_receipt_details   
                    SET returned_alloc = ".db_escape($total_returned_alloc_qty).",  
                        updated_by = ".db_escape($updated_by).", 
                        updated_on = ".db_escape($updated_on).",  
                        row_state = ".db_new_row_state($line_row_state)." 
                    WHERE trans_id = ".db_escape($trans_id)." 
                        AND qty >= $all_returned_qty";
            
            db_query($sql, 'update_outside_material_receipt_line_returned_alloc_returned');
                $af_row = db_num_affected_rows();
            
                    if ($af_row != 1) {
                        return 0;
                    }
            
    $nw_line_row_state = db_new_row_state($line_row_state);
    $nw_updated_on = date('Y-m-d H:i:s');
            
            $sql_1 = "UPDATE ".TB_PREF."outside_material_receipt_details   
                    SET returned_quantity = ".db_escape($total_returned_qty).",  
                        updated_by = ".db_escape($updated_by).", 
                        updated_on = ".db_escape($nw_updated_on).",  
                        row_state = ".db_new_row_state($nw_line_row_state)." 
                    WHERE trans_id = ".db_escape($trans_id)." 
                        AND qty >= $all_returned_qty";
            
            db_query($sql_1, 'update_outside_material_receipt_line_returned_alloc_returned');
                $af_row_2 = db_num_affected_rows();

                    if ($af_row_2 != 1) {
                        return 0;
                    }

        return 1;
}

function get_sql_for_outside_material_receipts_inquiry($trans_no, $req_trans_no, $jo_id, $reference, $project_id, $from_date, $to_date, $from_location, $to_loc_code, 
                                                       $ap_status) {
    $sql = "SELECT sa.jo_id, req.trans_no req_trans_no,
                sa.trans_no,
                sa.reference,
                sa.type,
                sa.from_location,
                l.location_name to_location_name,
                sa.tran_date,
                pm.description project_description,
                IF(sa.increase = 1 , 'Yes', 'No') increase,  
                sa.comments,
                sa.approval_status, 
                sa.id,
                req.type req_type 
            FROM ".TB_PREF."outside_material_receipts sa  
                JOIN ".TB_PREF."outside_material_requisitions req 
                    ON sa.omr_no = req.id 
                JOIN ".TB_PREF."projects_master pm 
                    ON sa.project_id = pm.project_id 
                JOIN ".TB_PREF."locations l 
                    ON sa.to_loc_code = l.loc_code 
            WHERE sa.type IN (".implode(',', array(ST_OUTSIDE_MATERIAL_RECEIPT)).")";
    
        if ($req_trans_no > 0 || $trans_no > 0 || $jo_id > 0) {
            if ($req_trans_no > 0) {
                $sql .= " AND req.trans_no = ".db_escape($req_trans_no);
            }
            
            if ($trans_no > 0) {
                $sql .= " AND sa.trans_no = ".db_escape($trans_no);
            }
            
            if ($jo_id > 0) {
                $sql .= " AND sa.jo_id = ".db_escape($jo_id);
            }
        } else {
            if (strlen($reference) > 0) {
                $sql .= " AND sa.reference = ".db_escape($reference);
            }
            
            $sql .= " AND sa.tran_date >= ".db_escape(date2sql($from_date))." AND sa.tran_date <= ".db_escape(date2sql($to_date)); 

            if($project_id > 0){
                $sql .= " AND sa.project_id = ".db_escape($project_id);
            }
            
            if (strlen($from_location) > 0) {        
                $sql .= " AND sa.from_location LIKE '%$from_location%'";
            }

            if ($to_loc_code != '') {        
                $sql .= " AND sa.to_loc_code = ".db_escape($to_loc_code);
            }
            
            if ($ap_status > -1) {        
                $sql .= " AND sa.approval_status = ".db_escape($ap_status);
            }  
        }
    
        $sql .= " ORDER BY sa.id DESC";
    
        return $sql;
}

function get_sql_for_outside_material_returns_inquiry($trans_no, $receipt_trans_no, $jo_id, $reference, $project_id, $from_date, $to_date, $from_location, $to_loc_code, 
                                                      $ap_status) {
    $sql = "SELECT sa.jo_id, req.trans_no receipt_trans_no,
                sa.trans_no,
                sa.reference,
                sa.type,
                sa.from_location,
                l.location_name from_location_name,
                l2.location_name to_location_name,
                sa.tran_date,
                pm.description project_description,
                IF(sa.increase = 1 , 'Yes', 'No') increase,  
                sa.comments,
                sa.approval_status, 
                sa.id,
                sa.to_loc_code,
                req.type receipt_type 
            FROM ".TB_PREF."outside_material_receipts sa  
                JOIN ".TB_PREF."outside_material_receipts req 
                    ON sa.omr_no = req.id 
                JOIN ".TB_PREF."projects_master pm 
                    ON sa.project_id = pm.project_id 
                LEFT JOIN ".TB_PREF."locations l 
                    ON sa.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON sa.to_loc_code = l2.loc_code 
            WHERE sa.type IN (".implode(',', array(ST_OUTSIDE_MATERIAL_RETURN)).")";
    
        if ($receipt_trans_no > 0 || $trans_no > 0 || $jo_id > 0) {
            if ($receipt_trans_no > 0) {
                $sql .= " AND req.trans_no = ".db_escape($receipt_trans_no);
            }
            
            if ($trans_no > 0) {
                $sql .= " AND sa.trans_no = ".db_escape($trans_no);
            }
            
            if ($jo_id > 0) {
                $sql .= " AND sa.jo_id = ".db_escape($jo_id);
            }
        } else {
            if (strlen($reference) > 0) {
                $sql .= " AND sa.reference = ".db_escape($reference);
            }
            
            $sql .= " AND sa.tran_date >= ".db_escape(date2sql($from_date))." AND sa.tran_date <= ".db_escape(date2sql($to_date)); 

            if($project_id > 0){
                $sql .= " AND sa.project_id = ".db_escape($project_id);
            }
            
            if (strlen($from_location) > 0) {        
                $sql .= " AND sa.from_location LIKE '%$from_location%'";
            }

            if ($to_loc_code != '') {        
                $sql .= " AND sa.to_loc_code = ".db_escape($to_loc_code);
            }
            
            if ($ap_status > -1) {        
                $sql .= " AND sa.approval_status = ".db_escape($ap_status);
            }  
        }
    
        $sql .= " ORDER BY sa.id DESC";
    
        return $sql;
}

function delete_outside_material_receipt_detail_lines($type, $trans_no, $has_source_line=null) {
    $sql = "DELETE FROM ".TB_PREF."outside_material_receipt_details 
            WHERE type = ".db_escape($type)." 
                AND trans_no = ".db_escape($trans_no);
    
        if ($has_source_line === false) {
            $sql .= " AND source_line_id = 0";
        } elseif ($has_source_line === true) {
            $sql .= " AND source_line_id > 0";
        }
    
	db_query($sql, "delete_outside_material_receipt_detail_lines");
        return db_num_affected_rows();
}

function delete_outside_material_receipt_detail_line_by_id($id) {
    $sql = "DELETE FROM ".TB_PREF."outside_material_receipt_details 
            WHERE trans_id = ".db_escape($id);
    
	db_query($sql, "delete_outside_material_receipt_detail_line_by_id");
        return db_num_affected_rows();
}

function get_outside_material_receipt_detail_record($line_id) {
    $sql = "SELECT *
            FROM ".TB_PREF."outside_material_receipt_details 
            WHERE trans_id = ".db_escape($line_id);
    
	$result = db_query($sql, "get_outside_material_receipt_detail_record");
        return db_fetch($result);
}

function get_outside_material_receipt_detail_record_type_trans_no_line_no($type, $trans_no, $line_id) {
    $sql = "SELECT *
            FROM ".TB_PREF."outside_material_receipt_details 
            WHERE type = ".db_escape($type)." 
                AND trans_no = ".db_escape($trans_no)." 
                AND trans_id = ".db_escape($line_id);
    
	$result = db_query($sql, "get_outside_material_receipt_detail_record_type_trans_no_line_no");
        return db_fetch($result);
}

function get_outside_material_receipt_details_line_by_type_trans_no_line_no($type, $trans_no, $line_id) {
    $sql = "SELECT ard.*,
                am.description stock_description,
                am.stock_id,
                am.mb_flag,
                un.name tran_unit_name,
                un2.name base_unit_name,
                ps.description site_description, 
                pt.description task_description, 
                l.location_name to_location_name  
            FROM ".TB_PREF."outside_material_receipt_details ard 
                LEFT JOIN ".TB_PREF."locations l 
                    ON ard.to_loc_code = l.loc_code 
                LEFT JOIN ".TB_PREF."stock_master am 
                    ON ard.stock_id = am.stock_id 
                LEFT JOIN ".TB_PREF."item_units un  
                    ON ard.tran_unit = un.abbr  
                LEFT JOIN ".TB_PREF."item_units un2   
                    ON am.units = un2.abbr  
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON ard.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON ard.task_id = pt.task_id 
            WHERE ard.trans_no = ".db_escape($trans_no)." 
                AND ard.type = ".db_escape($type)." 
                AND ard.trans_id = ".db_escape($line_id);
    
        $result = db_query($sql, "get_outside_material_receipt_details_line_by_type_trans_no_line_no");
        return db_fetch($result);
}

function update_outside_material_receipt_row_state($type, $trans_no, $row_state) {
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql = "UPDATE ".TB_PREF."outside_material_receipts 
                SET row_state = ". db_new_row_state($row_state).",
                    updated_by = ".db_escape($updated_by).", 
                    updated_on = ".db_escape($updated_on)." 
                WHERE type = ".db_escape($type)." 
                    AND trans_no = ".db_escape($trans_no)." 
                    AND row_state = ".db_escape($row_state);

            db_query($sql, "update_outside_material_receipt_row_state");
            return db_num_affected_rows();
}

function update_outside_material_receipt_row_state_by_id($id, $row_state) {
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql = "UPDATE ".TB_PREF."outside_material_receipts 
                SET row_state = ". db_new_row_state($row_state).",
                    updated_by = ".db_escape($updated_by).", 
                    updated_on = ".db_escape($updated_on)." 
                WHERE id = ".db_escape($id)." 
                    AND row_state = ".db_escape($row_state);

            db_query($sql, "update_outside_material_receipt_row_state_by_id");
            return db_num_affected_rows();
}

function get_outside_material_receipt_headers_by_omr_no_type($omr_no, $type) {
    $sql = "SELECT sa.*,
                l.location_name to_location_name,
                pm.description project_description,
                u.real_name requestor_name 
            FROM ".TB_PREF."outside_material_receipts sa 
                JOIN ".TB_PREF."projects_master pm 
                    ON sa.project_id = pm.project_id 
                JOIN ".TB_PREF."locations l 
                    ON sa.to_loc_code = l.loc_code 
                JOIN ".TB_PREF."users u 
                    ON sa.created_by = u.id 
            WHERE sa.omr_no = ".db_escape($omr_no)." 
                AND sa.type = ".db_escape($type);
    
        return db_query($sql, "get_outside_material_receipt_headers_by_omr_no_type");
}

function get_outside_material_receipt_headers_by_filters($jo_id=0, $id=0, $type=0, $trans_no=0, $from_location='', $to_loc_code='', $project_id=0, $from_date=null, 
                                                         $to_date=null, $order='') {
    $sql = "SELECT sa.*,
                l.location_name from_location_name,
                l2.location_name to_location_name,
                pm.description project_description,
                u.real_name requestor_name 
            FROM ".TB_PREF."outside_material_receipts sa 
                JOIN ".TB_PREF."projects_master pm 
                    ON sa.project_id = pm.project_id 
                JOIN ".TB_PREF."users u 
                    ON sa.created_by = u.id 
                LEFT JOIN ".TB_PREF."locations l 
                    ON sa.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON sa.to_loc_code = l2.loc_code 
            WHERE 1 = 1 ";
    
        if ($jo_id > 0) {
            $sql .= " AND sa.jo_id = ".db_escape($jo_id);
        }
        if ($id > 0) {
            $sql .= " AND sa.id = ".db_escape($id);
        }
        if ($type > 0) {
            $sql .= " AND sa.type = ".db_escape($type);
        }
        if ($trans_no > 0) {
            $sql .= " AND sa.trans_no = ".db_escape($trans_no);
        }
        if (strlen($from_location) > 0) {        
            $sql .= " AND sa.from_location LIKE '%$from_location%'";
        }
        if (strlen($to_loc_code) > 0) {
            $sql .= " AND sa.to_loc_code = ".db_escape($to_loc_code);
        }
        if ($project_id > 0) {
            $sql .= " AND sa.project_id = ".db_escape($project_id);
        }
        if ($from_date !== null) {
            $sql .= " AND sa.tran_date >= ".db_escape($from_date);
        }
        if ($to_date !== null) {
            $sql .= " AND sa.tran_date <= ".db_escape($to_date);
        }
    
        if (strlen($order) > 0) {
            $sql .= " ORDER BY $order";
        }
    
        return db_query($sql, "get_outside_material_receipt_headers_by_filters");
}

function get_outside_material_receipt_details_by_filters($jo_id=0, $id=0, $type=0, $trans_no=0, $from_location='', $to_loc_code='', $project_id=0, $from_date=null, 
                                                         $to_date=null, $task_id=0, $project_site_id=0, $order='', $fetch=false) {
    
    $sql = "SELECT ard.*, hd.jo_id, l.location_name from_location_name, l2.location_name to_location_name, am.description stock_description, am.stock_id, 
                am.mb_flag, un.name tran_unit_name, un2.name base_unit_name, ps.description site_description, pt.description task_description  
            FROM ".TB_PREF."outside_material_receipt_details ard 
                JOIN ".TB_PREF."outside_material_receipts hd 
                    ON ard.type = hd.type  
                        AND ard.trans_no = hd.trans_no   
                LEFT JOIN ".TB_PREF."locations l 
                    ON ard.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON ard.to_loc_code = l2.loc_code 
                LEFT JOIN ".TB_PREF."stock_master am 
                    ON ard.stock_id = am.stock_id 
                LEFT JOIN ".TB_PREF."item_units un  
                    ON ard.tran_unit = un.abbr  
                LEFT JOIN ".TB_PREF."item_units un2   
                    ON am.units = un2.abbr  
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON ard.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON ard.task_id = pt.task_id 
            WHERE 1 = 1 ";
    
        if ($jo_id > 0) {
            $sql .= " AND hd.jo_id = ".db_escape($jo_id);
        }
        if ($id > 0) {
            $sql .= " AND ard.id = ".db_escape($id);
        }
        if ($type > 0) {
            $sql .= " AND ard.type = ".db_escape($type);
        }
        if ($trans_no > 0) {
            $sql .= " AND ard.trans_no = ".db_escape($trans_no);
        }
        if (strlen($from_location) > 0) {        
            $sql .= " AND ard.from_location LIKE '%$from_location%'";
        }
        if (strlen($to_loc_code) > 0) {
            $sql .= " AND ard.to_loc_code = ".db_escape($to_loc_code);
        }
        if ($project_id > 0) {
            $sql .= " AND ard.project_id = ".db_escape($project_id);
        }
        if ($from_date !== null) {
            $sql .= " AND ard.tran_date >= ".db_escape($from_date);
        }
        if ($to_date !== null) {
            $sql .= " AND ard.tran_date <= ".db_escape($to_date);
        }
        if ($task_id > 0) {
            $sql .= " AND ard.task_id = ".db_escape($task_id);
        }
        if ($project_site_id > 0) {
            $sql .= " AND ard.project_site_id = ".db_escape($project_site_id);
        }
    
        if (strlen($order) > 0) {
            $sql .= " ORDER BY $order";
        }
        
            $result = db_query($sql, "get_outside_material_receipt_details_by_filters");
                if ($fetch === false) {
                    return $result; 
                } else {
                    return db_fetch($result);
                }
}

function get_sql_for_approve_outside_material_receipts($current_user_id, $type) {
    $sql = "SELECT omrc.id,
                omrc.trans_no,
                omrc.type,
                omrc.jo_id,
                omrc.reference,
                omrc.tran_date,                   
                omrc.from_location,                   
                l.location_name from_location_name,                   
                l2.location_name to_location_name,                   
                omrc.project_id,                   
                pm.description project_description,
                c.real_name,
                omrc.created_on,
                omrc.approval_status,
                omrc.to_loc_code ";
    
        if (in_array($type , array(ST_OUTSIDE_MATERIAL_RECEIPT, ST_OUTSIDE_MATERIAL_RETURN))) {
            $sql .= " , om_req.type req_type,
                        om_req.trans_no req_trans_no ";
        }
            
    $sql .= " FROM ".TB_PREF."outside_material_receipts omrc 
                JOIN ".TB_PREF."projects_master pm 
                    ON omrc.project_id = pm.project_id
                JOIN ".TB_PREF."users c 
                    ON omrc.created_by = c.id  
                JOIN ".TB_PREF."approvers apr 
                    ON omrc.next_approval_group_id = apr.approval_group_id  
                JOIN ".TB_PREF."user_data_access_groups udag 
                    ON pm.dag_id = udag.dag_id 
                        AND udag.user_id = apr.user_id  
                JOIN ".TB_PREF."users u 
                    ON apr.user_id = u.id 
                LEFT JOIN ".TB_PREF."locations l 
                    ON omrc.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON omrc.to_loc_code = l2.loc_code ";
    
        if ($type == ST_OUTSIDE_MATERIAL_RECEIPT) {
            $sql .= " LEFT JOIN ".TB_PREF."outside_material_requisitions om_req 
                        ON omrc.omr_no = om_req.id 
                            AND om_req.type = ".db_escape(ST_OUTSIDE_MATERIAL_REQ);
        } elseif ($type == ST_OUTSIDE_MATERIAL_RETURN) {
            $sql .= " LEFT JOIN ".TB_PREF."outside_material_receipts om_req 
                        ON omrc.omr_no = om_req.id 
                            AND om_req.type = ".db_escape(ST_OUTSIDE_MATERIAL_RECEIPT);
        }
                    
    $sql .= " WHERE omrc.approval_status IN (".implode(',', array(AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER)).") 
                AND apr.user_id = ".db_escape($current_user_id)." 
                AND omrc.type = ".db_escape($type);
      
        return $sql;
}

function get_outside_material_requisition_line_remain_qty_array($source_base_qty, $source_line_id=0, $tran_qty=0, $conversion_factor=1, $line_id=0, $dec=4, $returned_qty=0) {
    
    $source_tran_qty = $source_base_qty / $conversion_factor;
            
        $total_receipt_qty_ = get_outside_material_receipt_lines_total_qty(ST_OUTSIDE_MATERIAL_RECEIPT, $source_line_id, array(AS_APPROVED, AS_COMPLETED));
        $total_receipt_qty = abs($total_receipt_qty_);

        $ap_array_2 = array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR);
        $total_receipt_alloc_qty_ = get_outside_material_receipt_lines_total_qty(ST_OUTSIDE_MATERIAL_RECEIPT, $source_line_id, $ap_array_2, $line_id);
        $total_receipt_alloc_qty = abs($total_receipt_alloc_qty_);
        
        $processed_qty = $total_receipt_qty + $total_receipt_alloc_qty - $returned_qty;
        
            $old_processed_tran_qty = $processed_qty / $conversion_factor;
            $old_rem_trn_qty = $source_tran_qty - $old_processed_tran_qty;

            $new_rem_trn_qty = $old_rem_trn_qty - $tran_qty;
                
            return array('old_rem_trn_qty' => number_format($old_rem_trn_qty, $dec), 'new_rem_trn_qty' => number_format($new_rem_trn_qty, $dec));
}

function get_outside_material_receipt_lines_total_qty_by_om_req($om_req_type, $om_req_trans_no, $om_req_line_id, $ap_array, $not_trans_id=0) {
    $sql = "SELECT SUM(isd.qty) total_qty 
            FROM ".TB_PREF."outside_material_receipt_details isd  
                JOIN ".TB_PREF."outside_material_receipts ish  
                    ON isd.type = ish.type 
                        AND isd.trans_no = ish.trans_no  
                JOIN ".TB_PREF."outside_material_requisition_details ird   
                    ON isd.source_line_id = ird.trans_id   
                        AND ird.type = ".db_escape(ST_OUTSIDE_MATERIAL_REQ)." 
                JOIN ".TB_PREF."outside_material_requisition_details rd   
                    ON ird.source_type = rd.type 
                        AND ird.source_trans_no = rd.trans_no  
                        AND ird.source_line_id = rd.trans_id   
            WHERE rd.type = ".db_escape($om_req_type)." 
                AND rd.trans_no = ".db_escape($om_req_trans_no)."
                AND rd.trans_id = ".db_escape($om_req_line_id)."
                AND ish.approval_status IN (". implode(',', $ap_array).") 
                AND ish.type = ".db_escape(ST_OUTSIDE_MATERIAL_RECEIPT);
    
        if ($not_trans_id > 0) {
            $sql .= " AND ln.trans_id <> ".db_escape($not_trans_id);
        }
    
        $result = db_query($sql, 'get_outside_material_receipt_lines_total_qty_by_om_req');
        return db_result_value($result, 'total_qty');
}

function get_not_outside_material_requisition_lines_from_outside_material_receipt($req_trans_no, $receipt_trans_no) {
    $sql = "SELECT ard.*,
                omrcd.trans_id receipt_line_id, 
                omrcd.item_type receipt_item_type, 
                omrcd.stock_id receipt_stock_id, 
                omrcd.item_description receipt_item_description, 
                omrcd.tran_unit receipt_tran_unit, 
                omrcd.tran_qty receipt_tran_qty  
            FROM ".TB_PREF."outside_material_requisition_details ard 
                JOIN ".TB_PREF."outside_material_receipt_details omrcd 
                    ON ard.trans_id = omrcd.source_line_id  
            WHERE ard.trans_no = ".db_escape($req_trans_no)." 
                AND ard.type = ".db_escape(ST_OUTSIDE_MATERIAL_REQ)." 
                AND omrcd.trans_no = ".db_escape($receipt_trans_no)." 
                AND omrcd.type = ".db_escape(ST_OUTSIDE_MATERIAL_RECEIPT)." 
                AND omrcd.stock_id <> ard.stock_id 
            ORDER BY ard.trans_id";
    
        return db_query($sql, "get_not_outside_material_requisition_lines_from_outside_material_receipt");
}

function get_outside_material_receipt_with_outside_material_return_details($receipt_trans_no, $return_trans_no) {
    $sql = "SELECT ard.*,
                am.description stock_description,
                am.stock_id,
                am.mb_flag,
                am.stock_control_method,
                un.name unit_name,
                ps.description site_description, 
                pt.description task_description, 
                omrtd.trans_id return_line_id, 
                omrtd.item_type return_item_type, 
                omrtd.stock_id return_stock_id, 
                omrtd.item_description return_item_description, 
                omrtd.tran_unit return_tran_unit, 
                omrtd.tran_qty return_tran_qty, 
                omrtd.task_id return_task_id, 
                omrtd.project_site_id return_project_site_id, 
                omrtd.line_comment return_line_comment 
            FROM ".TB_PREF."outside_material_receipt_details ard 
                JOIN ".TB_PREF."outside_material_receipts mth  
                    ON ard.type = mth.type   
                        AND ard.trans_no = mth.trans_no  
                JOIN ".TB_PREF."locations l 
                    ON mth.to_loc_code = l.loc_code 
                LEFT JOIN ".TB_PREF."stock_master am 
                    ON ard.stock_id = am.stock_id 
                LEFT JOIN ".TB_PREF."item_units un  
                    ON ard.tran_unit = un.abbr  
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON ard.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON ard.task_id = pt.task_id 
                LEFT JOIN ".TB_PREF."outside_material_receipt_details omrtd 
                    ON ard.trans_id = omrtd.source_line_id  
                        AND omrtd.type = ".db_escape(ST_OUTSIDE_MATERIAL_RETURN)." 
                        AND omrtd.trans_no = ".db_escape($return_trans_no)." 
            WHERE ard.trans_no = ".db_escape($receipt_trans_no)." 
                AND ard.type = ".db_escape(ST_OUTSIDE_MATERIAL_RECEIPT)." 
            ORDER BY ard.trans_id";
    
        return db_query($sql, "get_outside_material_receipt_with_outside_material_return_details");
}

function get_outside_material_receipt_detail_line_details($trans_id) {
    $sql = "SELECT ard.*,
                am.description stock_description,
                am.stock_id,
                am.mb_flag,
                un.name unit_name,
                ps.description site_description, 
                pt.description task_description,
                l.location_name from_location_name,    
                l2.location_name to_location_name 
            FROM ".TB_PREF."outside_material_receipt_details ard 
                LEFT JOIN ".TB_PREF."stock_master am 
                    ON ard.stock_id = am.stock_id 
                LEFT JOIN ".TB_PREF."item_units un  
                    ON ard.tran_unit = un.abbr  
                LEFT JOIN ".TB_PREF."project_sites ps 
                    ON ard.project_site_id = ps.id 
                LEFT JOIN ".TB_PREF."project_tasks pt 
                    ON ard.task_id = pt.task_id 
                LEFT JOIN ".TB_PREF."locations l 
                    ON ard.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON ard.to_loc_code = l2.loc_code 
            WHERE ard.trans_id = ".db_escape($trans_id);
    
        $result = db_query($sql, "get_outside_material_receipt_detail_line_details");
        return db_fetch($result);
}

function get_outside_material_receipt_line_remain_qty_array($source_base_qty, $source_line_id=0, $tran_qty=0, $conversion_factor=1, $line_id=0, $dec=4) {
    
    $source_tran_qty = $source_base_qty / $conversion_factor;
            
        $total_receipt_qty_ = get_outside_material_receipt_lines_total_qty(ST_OUTSIDE_MATERIAL_RETURN, $source_line_id, array(AS_APPROVED, AS_COMPLETED));
        $total_receipt_qty = abs($total_receipt_qty_);

        $ap_array_2 = array(AS_NEW, AS_WITH_THE_APPROVER, AS_AWAITING_APPROVAL, AS_BACK_TO_ORIGINATOR);
        $total_receipt_alloc_qty_ = get_outside_material_receipt_lines_total_qty(ST_OUTSIDE_MATERIAL_RETURN, $source_line_id, $ap_array_2, $line_id);
        $total_receipt_alloc_qty = abs($total_receipt_alloc_qty_);
        
        $processed_qty = $total_receipt_qty + $total_receipt_alloc_qty;
        
            $old_processed_tran_qty = $processed_qty / $conversion_factor;
            $old_rem_trn_qty = $source_tran_qty - $old_processed_tran_qty;

            $new_rem_trn_qty = $old_rem_trn_qty - $tran_qty;
                
            return array('old_rem_trn_qty' => number_format($old_rem_trn_qty, $dec), 'new_rem_trn_qty' => number_format($new_rem_trn_qty, $dec));
}

function save_outside_material_receipt_lines_return_alloc_return_qty_total($type, $trans_no) {
    global $systypes_array;
    
    $result = get_outside_material_receipt_lines($trans_no, $type);
        while ($row = db_fetch($result)) {
            $id = $row['trans_id'];
            $row_state = $row['row_state'];
            
            $up_af_rw = update_outside_material_receipt_line_returned_alloc_returned($id, $row_state);
                if ($up_af_rw != 1) {
                    return array("success" => false, "message" => 'Could not update '.$systypes_array[$type].' total return/ return alloc qty.');
                }
        }
        
        return array("success" => true, "message" => '');
}

function check_all_outside_material_receipt_lines_fully_processed($type, $trans_no) {
    $sql = "SELECT qty, SUM(returned_quantity + returned_alloc) total_qty 
            FROM ".TB_PREF."outside_material_receipt_details  
            WHERE type = ".db_escape($type)." 
                AND trans_no = ".db_escape($trans_no)." 
            GROUP BY trans_id 
            HAVING total_qty < qty ";
            
        $result = db_query($sql, "check_all_outside_material_receipt_lines_fully_processed");
            if (db_num_rows($result) > 0) {
                return false;
            } 
            
        return true;
}

function get_outside_material_return_headers_by_omrc_no_type($omrc_no, $type) {
    $sql = "SELECT sa.*,
                l.location_name from_location_name,
                l2.location_name to_location_name,
                pm.description project_description,
                u.real_name requestor_name 
            FROM ".TB_PREF."outside_material_receipts sa 
                JOIN ".TB_PREF."projects_master pm 
                    ON sa.project_id = pm.project_id 
                JOIN ".TB_PREF."users u 
                    ON sa.created_by = u.id 
                LEFT JOIN ".TB_PREF."locations l 
                    ON sa.from_location = l.loc_code 
                LEFT JOIN ".TB_PREF."locations l2 
                    ON sa.to_loc_code = l2.loc_code 
            WHERE sa.omr_no = ".db_escape($omrc_no)." 
                AND sa.type = ".db_escape($type);
    
        return db_query($sql, "get_outside_material_return_headers_by_omrc_no_type");
}

function get_om_requisition_lines_from_om_receipt_with_om_return($receipt_trans_no, $return_trans_no) {
    $sql = "SELECT rtn.trans_id ret_line_id, rcp.trans_id rcp_line_id, req.trans_id, 
                req.row_state, req_h.row_state req_hd_row_state, req_h.trans_no req_trans_no, req_h.approval_status 
            FROM ".TB_PREF."outside_material_receipt_details rtn  
                JOIN ".TB_PREF."outside_material_receipt_details rcp 
                    ON rtn.source_line_id = rcp.trans_id   
                        AND rcp.type = ".db_escape(ST_OUTSIDE_MATERIAL_RECEIPT)." 
                        AND rcp.trans_no = ".db_escape($receipt_trans_no)." 
                JOIN ".TB_PREF."outside_material_requisition_details req 
                    ON rcp.source_line_id = req.trans_id   
                        AND req.type = ".db_escape(ST_OUTSIDE_MATERIAL_REQ)." 
                JOIN ".TB_PREF."outside_material_requisitions req_h 
                    ON req.type = req_h.type 
                        AND req.trans_no = req_h.trans_no 
            WHERE rtn.trans_no = ".db_escape($return_trans_no)." 
                AND rtn.type = ".db_escape(ST_OUTSIDE_MATERIAL_RETURN)." 
            GROUP BY req.trans_id
            ORDER BY req.trans_id";
    
        return db_query($sql, "get_om_requisition_lines_from_om_receipt_with_om_return");
}

function update_outside_material_requisition_line_retruned_qty($trans_id, $line_row_state=0) {
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $ap_array = array(AS_APPROVED, AS_COMPLETED);
        
        $total_returned_alloc_qty_ = get_outside_material_receipt_lines_returned_total_qty(ST_OUTSIDE_MATERIAL_RECEIPT, $trans_id, $ap_array, 0, false);
        $total_returned_alloc_qty = abs($total_returned_alloc_qty_);

        $total_returned_qty_ = get_outside_material_receipt_lines_returned_total_qty(ST_OUTSIDE_MATERIAL_RECEIPT, $trans_id, $ap_array, 0, true);
        $total_returned_qty = abs($total_returned_qty_);

        $total_all_returned = $total_returned_alloc_qty + $total_returned_qty;
            
            $sql = "UPDATE ".TB_PREF."outside_material_requisition_details  
                    SET returned_alloc = ".db_escape($total_returned_alloc_qty).",  
                        updated_by = ".db_escape($updated_by).", 
                        updated_on = ".db_escape($updated_on).",  
                        row_state = ".db_new_row_state($line_row_state)." 
                    WHERE trans_id = ".db_escape($trans_id)." 
                        AND receipt_quantity >= $total_all_returned";
            
            db_query($sql, 'update_outside_material_requisition_line_retruned_qty');
                $af_row = db_num_affected_rows();
            
                    if ($af_row != 1) {
                        return 0;
                    }
            
    $nw_line_row_state = db_new_row_state($line_row_state);
    $nw_updated_on = date('Y-m-d H:i:s');
            
            $sql_1 = "UPDATE ".TB_PREF."outside_material_requisition_details  
                    SET returned_quantity = ".db_escape($total_returned_qty).",  
                        updated_by = ".db_escape($updated_by).", 
                        updated_on = ".db_escape($nw_updated_on).",  
                        row_state = ".db_new_row_state($nw_line_row_state)." 
                    WHERE trans_id = ".db_escape($trans_id)." 
                        AND receipt_quantity >= $total_all_returned";
            
            db_query($sql_1, 'update_outside_material_requisition_line_retruned_qty');
                $af_row_2 = db_num_affected_rows();

                    if ($af_row_2 != 1) {
                        return 0;
                    } 
                    
        return 1;
}

function get_outside_material_receipt_lines_returned_total_qty($type, $source_line_id, $ap_array, $not_trans_id=0, $approved_qty=true) {
    if ($approved_qty === true) {
        $sql = "SELECT SUM(ln.returned_quantity) total_qty ";
    } else {
        $sql = "SELECT SUM(ln.returned_alloc) total_qty ";
    }
    
    $sql .= "FROM ".TB_PREF."outside_material_receipt_details ln 
                JOIN ".TB_PREF."outside_material_receipts hd  
                    ON ln.type = hd.type 
                        AND ln.trans_no = hd.trans_no  
            WHERE ln.source_line_id = ".db_escape($source_line_id)." 
                AND hd.type = ".db_escape($type)."
                AND hd.approval_status IN (". implode(',', $ap_array).")";
    
        if ($not_trans_id > 0) {
            $sql .= " AND ln.trans_id <> ".db_escape($not_trans_id);
        }
    
        $result = db_query($sql, 'get_outside_material_receipt_lines_returned_total_qty');
        return db_result_value($result, 'total_qty');
}

?>