<?php

global $path_to_root;


function cs_get_debtor_trans_no_tax_group_customers(){
    $sql = "SELECT DISTINCT debtor_no, branch_code 
            FROM  ".TB_PREF."debtor_trans   
            WHERE type IN(".ST_SALESINVOICE.", ".ST_CUSTDELIVERY.", ".ST_CUSTCREDIT." ) 
                AND trans_tax_group_id = 0 
            LIMIT 10";
    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_debtor_trans_tax_group($customer_id, $branch_code, $tax_group_id)
{
//    return;
    
    $sql = "UPDATE ".TB_PREF."debtor_trans    
            SET trans_tax_group_id =".db_escape($tax_group_id). " 
            WHERE debtor_no = ".db_escape($customer_id)."  
                AND branch_code =".db_escape($branch_code)." 
                AND type IN(".ST_SALESINVOICE.", ".ST_CUSTDELIVERY.", ".ST_CUSTCREDIT." ) 
                AND trans_tax_group_id = 0";
    
    db_query($sql,"cs_update_sales_order_tax_group");
}


function cs_write_debtor_trans_tax_groups()
{
    $message = "==================Script Sarted==========================";
    write_custom_script_log("cs_write_debtor_trans_tax_groups", $message);
    
    $invs = cs_get_debtor_trans_no_tax_group_customers();
    $recs = db_num_rows($invs);
    write_custom_script_log("cs_write_debtor_trans_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_debtor_trans_tax_group($row['debtor_no'], $row['branch_code'], $branch['tax_group_id']);
        
        $n = db_num_affected_rows();
        if($n!=0){
            $message = "Customer: ".$row['debtor_no'].", Branch: ".$row['branch_code']." updated - tax_group_id: ".$branch['tax_group_id']." Records: ".$n;
        }
        else{
            $message = "Could not update SO ".$row['order_no'];
        }
        write_custom_script_log("cs_write_debtor_trans_tax_groups", $message);
    }
    
    $message = "------------------Script Completed----------------------------";
    write_custom_script_log("cs_write_debtor_trans_tax_groups", $message);
}

?>