<?php


function get_invoices_from_import_project_invoice_line_categories_table(){
    $sql = "SELECT * FROM  import_project_invoice_line_categories";
    return db_query($sql,"Could not get_invoices_from_import_project_invoice_line_categories_table");
}

function  update_project_invoice_line_category_id($inv_id, $line_category_id)
{
    $sql = "UPDATE ".TB_PREF."project_invoice_details  
            SET category_id =".db_escape($line_category_id). " 
            WHERE order_no=".db_escape($inv_id);
    
    db_query($sql,"Could not update_system_item_costs");
    
    return db_num_affected_rows();
}

function  write_import_project_invoice_line_category_message($id, $message)
{
    $sql = "UPDATE import_project_invoice_line_categories 
            SET message =".db_escape($message);
    
    if($id > 0){
        $sql .= " WHERE id=".db_escape($id);
    }
    
    db_query($sql,"write_import_project_invoice_line_category_message");
}

function cs_update_project_invoice_line_categories()
{

//    return;
    
    $result = get_invoices_from_import_project_invoice_line_categories_table();
    while ($row = db_fetch($result)) {
        $sys_inv = get_project_invoice_header_record_by_reference($row['reference']);
        if(!(isset($sys_inv['order_no']) && $sys_inv['order_no'] > 0 )){
            $message = "Invoice not found";
            write_import_project_invoice_line_category_message($row['id'], $message);
            continue;
        }
        
        $line_category = get_listvalue_by_name('PROJ_INV_LINE_CATEGORIES', $row['line_category_name']);
        if(!(isset($line_category['id']) && $line_category['id'] > 0 )){
            $message = "Line category not found";
            write_import_project_invoice_line_category_message($row['id'], $message);
            continue;
        }

        $num_recs = update_project_invoice_line_category_id($sys_inv['order_no'], $line_category['id']);     
        if($num_recs == 1){
            $message = "Updated";
        }
        else{
            $message = "$num_recs Records updated";
        }
        
        write_import_project_invoice_line_category_message($row['id'], $message);
  
    }
}

?>