<?php

function get_material_list_headers($jo_id) {
    $sql = "SELECT sa.id,
                sa.trans_no,
                sa.reference,
                sa.type,
                l.location_name,
                sa.tran_date,
                IF(sa.increase = 1 , 'Yes', 'No') increase,  
                sa.comments,
                IF(sa.sample_items = 1 , 'Yes', 'No') sample_items,
                sa.approval_status 
            FROM ".TB_PREF."material_lists sa  
                JOIN ".TB_PREF."locations l 
                    ON sa.loc_code = l.loc_code        
            WHERE sa.type = ".db_escape(ST_MATERIAL_LIST)." 
                AND sa.jo_id = ".db_escape($jo_id);
    
    return db_query($sql, "get_material_list_headers");
}

function write_material_list_header($type, $id, $reference, $project_id, $location, $comments, $date, $source_id=0, $jo_id=0, $row_state=0) {
    global $Refs;
     
        if ($id > 0) {
            $af_row = update_material_list_header($id, $reference, $location, $comments, $date, $row_state);
                if (! ($af_row > 0)) {
                    return 0;
                }
        } else {
            $trans_no = get_next_trans_no($type);
            $id = insert_material_list_header($type, $trans_no, $reference, $project_id, $location, $comments, $date, $source_id, $jo_id);
        }
    
        $Refs->save($type, $id, $reference);

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

        return $id;
}

function write_material_list_header_by_type_trans_no($type, $trans_no, $reference, $project_id, $location, $comments, $date, $source_id=0) {
    global $Refs;
     
        if ($trans_no > 0) {
            $af_row = update_material_list_header_by_type_trans_no($type, $trans_no, $reference, $location, $comments, $date);
                if (! ($af_row > 0)) {
                    return 0;
                }
        } else {
            $trans_no = get_next_trans_no($type);
            $inser_id = insert_material_list_header($type, $trans_no, $reference, $project_id, $location, $comments, $date, $source_id);
                if (! ($inser_id > 0)) {
                    return 0;
                }
        }
    
        $Refs->save($type, $trans_no, $reference);

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

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

function update_material_list_header($id, $reference, $location, $comments, $date, $row_state=0) {   
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql = "UPDATE ".TB_PREF."material_lists
                SET reference = ".db_escape($reference).",
                    loc_code = ".db_escape($location).",                          
                    tran_date = ".db_escape(date2sql($date)).",
                    comments = ".db_escape($comments).", 
                    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_material_list_header");
            return db_num_affected_rows();
}

function update_material_list_header_by_type_trans_no($type, $trans_no, $reference, $location, $comments, $date) {   
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql = "UPDATE ".TB_PREF."material_lists
                SET reference = ".db_escape($reference).",
                    loc_code = ".db_escape($location).",                          
                    tran_date = ".db_escape(date2sql($date)).",
                    comments = ".db_escape($comments).", 
                    updated_by = ".db_escape($updated_by).", 
                    updated_on = ".db_escape($updated_on)." 
                WHERE type = ".db_escape($type)."     
                    AND trans_no = ".db_escape($trans_no);    

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

function write_material_list_line($trans_no, $line_id, $type, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, $qty, $conversion_factor, 
                                  $standard_cost, $project_site_id, $line_comment, $source_line_id=0) {
    if ($line_id > 0) {
        return update_material_list_line($line_id, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, $qty, $conversion_factor, 
                                         $standard_cost, $project_site_id, $line_comment, $source_line_id);
    } else {
        return insert_material_list_line($trans_no, $type, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, $qty, $conversion_factor, 
                                         $standard_cost, $project_site_id, $line_comment, $source_line_id);
    }
}

function update_material_list_line($line_id, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, $qty, $conversion_factor, $standard_cost, 
                                   $project_site_id, $line_comment, $source_line_id=0) {
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql = "UPDATE ".TB_PREF."material_list_details
                SET stock_id = ".db_escape($stock_id).", 
                    item_type = ".db_escape($item_type).", 
                    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).",
                    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).",  
                    source_line_id = ".db_escape($source_line_id)." 
                WHERE trans_id = ".db_escape($line_id);

            db_query($sql, 'update_material_list_line');
            return db_num_affected_rows();
}
        
function insert_material_list_line($trans_no, $type, $stock_id, $item_type, $item_description, $tran_unit, $tran_qty, $qty, $conversion_factor, 
                                   $standard_cost, $project_site_id, $line_comment, $source_line_id=0) {
    $created_by = $_SESSION['wa_current_user']->user;
    $created_on = date('Y-m-d H:i:s');
    
        $sql = "INSERT INTO ".TB_PREF."material_list_details
                      ( trans_no, type, stock_id, 
                        tran_unit, item_type, item_description, 
                        tran_qty, qty, conversion_factor, 
                        standard_cost, project_site_id, line_comment, 
                        created_by, created_on, source_line_id)        
                VALUE ( ".db_escape($trans_no).", ".db_escape($type).", ".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($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_material_list_line');
            return db_insert_id();  
}

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

function get_material_list_header($id) {
    $sql = "SELECT sa.*,
                l.location_name,
                pm.description project_description,
                u.real_name requestor_name 
            FROM ".TB_PREF."material_lists 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 
                JOIN ".TB_PREF."users u 
                    ON sa.created_by = u.id 
            WHERE sa.id = ".db_escape($id);
    
        $result = db_query($sql, "get_material_list_header");
        return db_fetch($result);
}

function get_material_list_header_type_trans_no($type, $trans_no) {
    $sql = "SELECT sa.*,
                l.location_name,
                pm.description project_description,
                u.real_name requestor_name 
            FROM ".TB_PREF."material_lists 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 
                JOIN ".TB_PREF."users u 
                    ON sa.created_by = u.id 
            WHERE sa.type = ".db_escape($type)." 
                AND sa.trans_no = ".db_escape($trans_no);
    
        $result = db_query($sql, "get_material_list_header_type_trans_no");
        return db_fetch($result);
}

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

function delete_material_list_details_record($selected_id) {
    $sql = "DELETE 
            FROM ".TB_PREF."material_list_details 
            WHERE trans_id = ".db_escape($selected_id);
    
        db_query($sql, 'delete_material_list_details_record');
        return db_num_affected_rows();
}

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

function get_material_list_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 
            FROM ".TB_PREF."material_list_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 
            WHERE ard.trans_no = ".db_escape($trans_no)." 
                AND ard.type = ".db_escape($type);
    
        return db_query($sql, "get_material_list_details");
}

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

function get_material_list_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 
            FROM ".TB_PREF."material_list_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 
            WHERE ard.trans_id = ".db_escape($trans_id);
    
        $result = db_query($sql, "get_material_list_detail_line_details");
        return db_fetch($result);
}

function get_material_list_details_lines_count($trans_no, $type) {
    $sql = "SELECT COUNT(trans_id) lines_count 
            FROM ".TB_PREF."material_list_details 
            WHERE trans_no = ".db_escape($trans_no)." 
                AND type = ".db_escape($type);
    
        $result = db_query($sql, 'get_material_list_details_lines_count');
        return db_result_value($result, 'lines_count');
}

function update_material_list_row_state($id, $row_state) {
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql = "UPDATE ".TB_PREF."material_lists
                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_material_list_row_state");
            return db_num_affected_rows();
}

function get_sql_for_material_lists_inquiry($trans_no, $jo_id, $reference, $project_id, $from_date, $to_date, $loc_code, $trans_status=-1, $only_outstanding=false) {
    $sql = "SELECT sa.id,
                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,
                IF(sa.sample_items = 1 , 'Yes', 'No') sample_items,
                sa.approval_status, 
                sa.project_id  
        FROM ".TB_PREF."material_lists 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 = ".db_escape(ST_MATERIAL_LIST);
    
        if ($only_outstanding === true) {        
            $sql .= " AND sa.approval_status = ".db_escape(AS_APPROVED);
        }
    
        if ($trans_no > 0){
            $sql .= " AND sa.trans_no = ".db_escape($trans_no);
        } elseif ($jo_id > 0){
            $sql .= " AND sa.jo_id = ".db_escape($jo_id);
        } else {
        
            if (strlen($reference) > 0) {
                $sql .= " AND sa.reference = ".db_escape($reference);
            }

            if ($project_id > 0) {
                $sql .= " AND sa.project_id = ".db_escape($project_id);
            }

            $sql .= " AND sa.tran_date >= ".db_escape(date2sql($from_date))." AND sa.tran_date <= ".db_escape(date2sql($to_date)); 

            if ($loc_code != '') {        
                $sql .= " AND sa.loc_code = ".db_escape($loc_code);
            }
            
            if ($trans_status > -1) {        
                $sql .= " AND sa.approval_status = ".db_escape($trans_status);
            }                      
        }
    
        $sql .= " ORDER BY sa.tran_date, sa.id";
    
    return $sql;
}

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

        $sql = "UPDATE ".TB_PREF."material_lists
                SET approval_status = ".db_escape($new_status).",
                    row_state = ".db_new_row_state($row_state).", 
                    approved_by = ".db_escape($approved_by).", 
                    approved_on = ".db_escape($approved_on)." 
                WHERE id = ".db_escape($id)."   
                    AND approval_status = ".db_escape($pre_status)." 
                    AND row_state = ".db_escape($row_state);

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

function update_material_list_header_totals($type, $trans_no, $row_state=0) {
    $lines_total = get_material_list_lines_total($type, $trans_no);
    
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql =  "UPDATE ".TB_PREF."material_lists  
                    SET total = ".db_escape($lines_total).", 
                        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_material_list_header_totals");   
        return db_num_affected_rows();
}

function get_material_list_lines_total($type, $trans_no) {
    $sql = "SELECT SUM(standard_cost * qty) lines_amount_total
            FROM ".TB_PREF."material_list_details 
            WHERE type = ".db_escape($type)." 
                AND trans_no = ".db_escape($trans_no);
    
    $result = db_query($sql, "get_material_list_lines_total");
    return db_result_value($result, 'lines_amount_total');
}

function update_material_list_jmr_quantity($type, $trans_no, $line_id) {
    $total_base_qty = get_job_material_requisition_lines_quantity_by_source($type, $trans_no, $line_id);
    
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql =  "UPDATE ".TB_PREF."material_list_details    
                    SET jmr_quantity = ".db_escape($total_base_qty).", 
                        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 trans_id = ".db_escape($line_id)." 
                        AND qty >= ".db_escape($total_base_qty); 

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

function update_material_list_dpr_quantity($type, $trans_no, $line_id) {
    $total_base_qty = get_direct_purchase_requisition_lines_quantity_by_source($type, $trans_no, $line_id);
    
    $updated_by = $_SESSION['wa_current_user']->user;
    $updated_on = date('Y-m-d H:i:s');
    
        $sql =  "UPDATE ".TB_PREF."material_list_details    
                    SET dpr_quantity = ".db_escape($total_base_qty).", 
                        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 trans_id = ".db_escape($line_id)." 
                        AND qty >= ".db_escape($total_base_qty); 

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

function check_all_material_list_lines_fully_purchase_requisted($type, $trans_no) {
    $sql = "SELECT qty, SUM(dpr_quantity) total_requisted_qty 
            FROM ".TB_PREF."material_list_details 
            WHERE type = ".db_escape($type)." 
                AND trans_no = ".db_escape($trans_no)." 
            GROUP BY trans_id 
            HAVING total_requisted_qty < qty ";
            
        $result = db_query($sql, "check_all_material_list_lines_fully_purchase_requisted");
            if (db_num_rows($result) > 0) {
                return false;
            } 
            
        return true;
}

function get_material_list_headers_by_filters($jo_id=0, $id=0, $type=0, $trans_no=0, $loc_code='', $project_id=0, $from_date=null, $to_date=null) {
    $sql = "SELECT sa.*,
                l.location_name,
                pm.description project_description,
                u.real_name requestor_name 
            FROM ".TB_PREF."material_lists 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 
                JOIN ".TB_PREF."users u 
                    ON sa.created_by = u.id 
            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($loc_code) > 0) {
            $sql .= " AND sa.loc_code = ".db_escape($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);
        }
    
        return db_query($sql, "get_material_list_headers_by_filters");
}

function get_sql_for_approve_job_material_lists($current_user_id, $type=ST_MATERIAL_LIST) {
    $sql = "SELECT ml.id,
                ml.trans_no,
                ml.type,
                ml.jo_id,
                ml.reference,
                ml.tran_date,                   
                l.location_name,                   
                ml.project_id,                   
                pm.description project_description,
                ml.total,
                c.real_name,
                ml.created_on,
                ml.approval_status, 
                ml.next_approval_group_id,  
                apgp.approval_group_description 
            FROM ".TB_PREF."material_lists ml 
                JOIN ".TB_PREF."projects_master pm 
                    ON ml.project_id = pm.project_id
                JOIN ".TB_PREF."users c 
                    ON ml.created_by = c.id  
                JOIN ".TB_PREF."approvers apr 
                    ON ml.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."approval_group apgp  
                    ON ml.next_approval_group_id = apgp.approval_group_id  
                LEFT JOIN ".TB_PREF."locations l 
                    ON ml.loc_code = l.loc_code   
            WHERE ml.approval_status IN (".implode(',', array(AS_AWAITING_APPROVAL, AS_WITH_THE_APPROVER)).") 
                AND apr.user_id = ".db_escape($current_user_id)." 
                AND ml.type = ".db_escape($type);
      
        return $sql;
}

?>