<?php

function cs_get_customer_credit_note_header_src(){
    $sql = "SELECT * FROM ".TB_PREF."debtor_trans_details   
            WHERE debtor_trans_type IN(".db_escape(ST_CUSTCREDIT).")  
            LIMIT 40";
    return db_query($sql, "Could not cs_get_customer_credit_note_header_src");
}

function get_parent_src_line($src_id){
    
    $sql = "SELECT * FROM ".TB_PREF."debtor_trans_details   
            WHERE id = ".db_escape($src_id);
    $row = db_query($sql, "Could not get_parent_src_id_by_id");
    return db_fetch($row);
}

function cs_update_debtor_trans_table_src_id($credit_note_no, $src_id){   
    
    $row_delivery = get_parent_src_line($src_id);
    $cnh = get_customer_trans_record(ST_CUSTCREDIT, $credit_note_no);
    if($cnh['order_'] == $row_delivery['debtor_trans_no']){
        write_custom_script_log("cs_update_customer_credit_note_header_src", "No update required");
    }
        
    $sql = "UPDATE ".TB_PREF."debtor_trans 
                SET order_ = ".db_escape($row_delivery['debtor_trans_no'])."    

                WHERE trans_no = ".db_escape($credit_note_no)." 
                AND type = ".db_escape(ST_CUSTCREDIT);
        
        
    db_query($sql, "could not cs_update_debtor_trans_table_src_id");
    
    
    
}


function cs_update_customer_credit_note_header_src(){
    
    $message = "==================Script Sarted==========================";
    write_custom_script_log("cs_update_customer_credit_note_header_src", $message);
    
    $credit_note_details = cs_get_customer_credit_note_header_src();
    $recs = db_num_rows($credit_note_details);
    write_custom_script_log("cs_update_customer_credit_note_header_src", $recs." Records selected");
    
    while($row = db_fetch($credit_note_details)){
        $src_id = $row['src_id'];
        cs_update_debtor_trans_table_src_id($row['debtor_trans_no'], $row['src_id']);
        
        $n = db_num_affected_rows();
        if($n==1){
            $message = "Debtor trans  ".$row['debtor_trans_no']." updated - order_: $src_id";
        }else{
            $message = "Could not update Debtor trans  ".$row['debtor_trans_no'];
        }
        write_custom_script_log("cs_update_customer_credit_note_header_src", $message);
    }
    
    $message = "------------------Script Completed----------------------------";
    write_custom_script_log("cs_update_customer_credit_note_header_src", $message);
}

?>