<?php

global $path_to_root;


function cs_get_sales_orders_with_no_tax_group(){
    $sql = "SELECT * FROM  ".TB_PREF."sales_orders  
            WHERE trans_type IN(30) 
                AND tax_group_id = 0 
            LIMIT 1000";
    return db_query($sql,"Could not cs_get_supplier_invoices_with_no_tax_group");
}

function cs_get_cust_branch_sales_type($customer_id, $branch_code)
{
	$sql = "SELECT b.branch_code, b.br_name, b.tax_group_id, d.debtor_no, d.name, s.tax_included 
                FROM ".TB_PREF."cust_branch b 
                    JOIN ".TB_PREF."debtors_master d 
                        ON b.debtor_no = d.debtor_no 
                    JOIN ".TB_PREF."sales_types s 
                        ON d.sales_type = s.id 
		WHERE b.branch_code=".db_escape($branch_code)."
		AND b.debtor_no=".db_escape($customer_id);
	$result = db_query($sql,"cs_get_cust_branch_sales_type");
	return db_fetch($result);
}

function  cs_update_sales_order_tax_group($type, $trans_no, $tax_included, $tax_group_id, $row_state)
{
//    return;
    
    $sql = "UPDATE ".TB_PREF."sales_orders   
            SET tax_included =".db_escape($tax_included). ",
                tax_group_id =".db_escape($tax_group_id). ", 
                row_state =". db_new_row_state($row_state). " 
            WHERE trans_type = ".db_escape($type)."  
                AND order_no =".db_escape($trans_no)." 
                AND row_state =".db_escape($row_state)." 
                AND tax_group_id = 0";
    
    db_query($sql,"cs_update_sales_order_tax_group");
}


function cs_write_sales_orders_tax_groups()
{
    $message = "==================Script Sarted==========================";
    write_custom_script_log("cs_write_sales_orders_tax_groups", $message);
    
    
    $invs = cs_get_sales_orders_with_no_tax_group();
    $recs = db_num_rows($invs);
    write_custom_script_log("cs_write_sales_orders_tax_groups", $recs." Records selected");
    
    while ($row = db_fetch($invs)) {
        $branch = cs_get_cust_branch_sales_type($row['debtor_no'], $row['branch_code']);             
        cs_update_sales_order_tax_group($row['trans_type'], $row['order_no'], $branch['tax_included'], $branch['tax_group_id'], $row['row_state']);
        
        $n = db_num_affected_rows();
        if($n==1){
            $message = "SO ".$row['order_no']." updated - tax_included: ".$branch['tax_included'].", tax_group_id: ".$branch['tax_group_id'];
        }
        else{
            $message = "Could not update SO ".$row['order_no'];
        }
        write_custom_script_log("cs_write_sales_orders_tax_groups", $message);
    }
    
    $message = "------------------Script Completed----------------------------";
    write_custom_script_log("cs_write_sales_orders_tax_groups", $message);
}

?>