<?php

function get_sql_for_salvage_returns_inquiry($trans_no, $jo_id, $reference, $project_id, $from_date, $to_date, $loc_code, $ap_status) {
    $sql = "SELECT sa.jo_id, 
                sa.trans_no,
                sa.reference,
                sa.type,
                l.location_name,
                sa.tran_date,
                pm.description project_description,
                IF(sa.increase = 1 , 'Yes', 'No') increase,  
                sa.comments,
                sa.approval_status, 
                sa.id 
            FROM ".TB_PREF."job_material_issues sa  
                JOIN ".TB_PREF."projects_master pm 
                    ON sa.project_id = pm.project_id 
                JOIN ".TB_PREF."locations l 
                    ON sa.loc_code = l.loc_code 
            WHERE sa.type IN (".implode(',', array(ST_SALVAGE_RETURN)).")";
    
        if ($trans_no > 0 || $jo_id > 0) {
            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 ($loc_code != '') {        
                $sql .= " AND sa.loc_code = ".db_escape($loc_code);
            }
            
            if ($ap_status > -1) {        
                $sql .= " AND sa.approval_status = ".db_escape($ap_status);
            }  
        }
    
        $sql .= " ORDER BY sa.id DESC";
    
        return $sql;
}

?>