<?php


function process_asset_depreciation_calculation($asset_run_id)
{
    $asset_run = get_asset_depreciation_run_details($asset_run_id);
    
    update_asset_depreciation_run_status($asset_run_id, "P"); // Calculated  
    
    $a_result = get_calculated_asset_depreciation_details($asset_run_id);
       
       $j = 0;
       while($new_row = db_fetch($a_result))
       {
           $asset_id = $new_row['asset_id'];
           $current_value = $new_row['current_value'];
//           $depreciation_value = $new_row['depreciation_value'];
           
           $new_value = $new_row['current_value'] - $new_row['depreciation_value'];
           if($new_value < 0){
               $new_value = 0;
           }
           
           begin_global_transaction();
           
           $j++;
           if($current_value != $new_value){
                $n1 = update_asset_current_value($asset_id, $new_value, $asset_run_id); 
                if($n1 != 1){
                    cancel_transaction();
                    return array("success"=>false, "message"=>"Could not update asset id $asset_id with new depreciated value.");
                }
                
                $existing_asset_total = get_asset_total_qty($asset_id);
                add_asset_valuation(ST_ASSET_DEPRECIATION_RUN, $asset_run_id, $asset_run['period_end_date'], $asset_id, $new_value, $existing_asset_total, $new_row['id']);
           }
           
           add_processed_asset_depreciation_detail($asset_run_id, $asset_id, $new_row['purchase_value'], $new_row['current_value'],
                                                          $new_row['depreciation_type'], $new_row['depreciation_rate'], 
                                                          $new_row['depreciation_value'], $new_row['asset_account'], $new_row['depreciation_account'],
                                                          $new_row['accumulated_account']);
           
           $n2 = update_asset_depreciation_detail_processed($new_row['id']);
           if($n2 != 1){
               cancel_transaction();
               return array("success"=>false, "message"=>"Could not update asset depreciation calculation detail record ".$new_row['id']." as processed.");
           }
           
           commit_transaction();
       }       
       
       update_asset_depreciation_run_status($asset_run_id, "R");   
       
       return array("success"=>true, "message"=>"All calcuated depreciation values processed");
    
}




   



