<?php

function cs_get_floats()
{
    $sql = "SELECT id, name 
            FROM ".TB_PREF."petty_cash_floats  

            LIMIT 100";
    
    return db_query($sql, "cs_get_floats");
}

function cs_get_float_transactions($float_id)
{
    $sql = "SELECT * 
            FROM ".TB_PREF."petty_cash_float_trans  
            WHERE float_id = ". db_escape($float_id)."
                
            ORDER BY id" ;
    
    return db_query($sql, "cs_get_float_transactions");
}

function cs_update_float_transaction_balance($id, $balance)
{
    $sql = "UPDATE ".TB_PREF."petty_cash_float_trans  
                SET balance = ".db_escape($balance)." 
            WHERE id = ". db_escape($id);
    
    db_query($sql, "cs_update_float_transaction_balance");
    
    return db_num_affected_rows();
}


function cs_update_petty_cash_float_balances()
{
    $message = "==================Script Sarted==========================";
    write_custom_script_log("cs_update_petty_cash_float_balances", $message);
    
    $float_res = cs_get_floats();
    
    while($float = db_fetch($float_res)){
        
        $msg = cs_update_float_balance($float);
        if($msg['success'] !== true){
            $message = $msg['message'];
            write_custom_script_log("cs_update_petty_cash_float_balances", $message);
            return;
        }
   
        $message = $float['name']." (".$float['id'].") completed";
        write_custom_script_log("cs_update_petty_cash_float_balances", $message);
    }
    
    $message = "------------------Script Completed----------------------------";
    write_custom_script_log("cs_update_petty_cash_float_balances", $message);
}

function cs_update_float_balance($float){

    $new_balance = 0;
    $res = cs_get_float_transactions($float['id']);
    while($tran = db_fetch($res)){        
        $new_balance += $tran['amount'];
        $id = $tran['id'];
        
        $balance = (float)trim($tran['balance']);
        $a = $new_balance - $balance;
        if(abs($a) < 0.001){
            continue;
        }
        
        $n = cs_update_float_transaction_balance($id, $new_balance);
        if($n !== 1){
            $message = "Could not update the balance ($new_balance) of transaction ".$id;
            write_custom_script_log("cs_update_float_balance", $message);
            return array("success"=>false, "message"=>$message);
        }
    }

        
    return array("success"=>true, "message"=>"");
    
}
