<?php
 function get_accounts_select_list($select_id='',$parent_id=0){
 	  $CI =& get_instance();

	 
	   $CI->db->where("a.store_id",get_current_store_id());

	  $CI->db->select("a.*, c.currency_code")->where("a.status=1")->from("ac_accounts a");
	  $CI->db->join('db_currency c', 'a.currency_id = c.id', 'left');
	  $CI->db->where('(a.delete_bit = 0 OR a.delete_bit = 1)'); // Include both regular and cash accounts
	  $CI->db->order_by("a.sort_code");
	  $q1=$CI->db->get();

	  $str='';
	   if($q1->num_rows($q1)>0)
	    {  
	    	//$str.='<option value="">-Select-</option>'; 
	        foreach($q1->result() as $res1)
	      { 
	        $selected = ($select_id==$res1->id)? 'selected' : '';
	        
        		$str.= ($res1->parent_id==0) ? '<optgroup class="bg-yellow" label="'.$res1->account_name.'">' : '';
        	$str.="<option $selected data-account-name='".$res1->account_name."' data-currency-id='".$res1->currency_id."' value='".$res1->id."'>";
        			$account_display = add_dash($res1->account_name,$res1->parent_id,$res1->sort_code);
        			// Add currency code to account name if not base currency
        			$base_currency = get_base_currency();
        			if ($res1->currency_id && $res1->currency_id != $base_currency->id && $res1->currency_code) {
        				$account_display .= ' (' . $res1->currency_code . ')';
        			}
        			$str .= $account_display;
        		
        	$str.="</option>";	
        		$str.= ($res1->parent_id==0) ? '</optgroup>' : '';
	        
	      //  echo get_accounts_select_list_sub(null,$res1->id);
	      }
	    }
	    else
	    {
	    	//$str.='<option value="">No Records Found</option>'; 
	    }
	    return $str;
 }

 function add_dash($value,$parent_id,$sort_code){
 	if($parent_id==0){
 		return $value;
 	}
 	else{
 		$dash='';
 		$count = count(explode(".", $sort_code));
 		for ($i=0; $i < $count-2; $i++) { 
 			$dash .= "&nbsp;&nbsp;&nbsp;";
 		}
 		return $dash."--".$value;
 	}
 	
 }


function insert_account_transaction($data=array()){
	
		$transaction_type 			= (empty($data['transaction_type'])) ? '' : $data['transaction_type'];
		$reference_table_id			= $data['reference_table_id'];
		$debit_account_id 			= (empty($data['debit_account_id'])) ? NULL : $data['debit_account_id'];
		$credit_account_id 			= (empty($data['credit_account_id'])) ? NULL : $data['credit_account_id'];
		$debit_amt 					= (empty($data['debit_amt'])) ? 0 : $data['debit_amt'];
		$credit_amt 				= (empty($data['credit_amt'])) ? 0 : $data['credit_amt'];
		$process 					= (empty($data['process'])) ? 'SAVE' : $data['process'];
		$note 						= (empty($data['note'])) ? '' : $data['note'];
		$transaction_date			= $data['transaction_date'];
		$payment_code 				= (empty($data['payment_code'])) ? '' : $data['payment_code'];
		$customer_id 				= (empty($data['customer_id'])) ? NULL : $data['customer_id'];
		$supplier_id 				= (empty($data['supplier_id'])) ? NULL : $data['supplier_id'];
	

	$CI =& get_instance();

	// Debug transaction type and conditions
	log_message('debug', 'Transaction type: ' . $transaction_type . ', customer_id: ' . (isset($customer_id) ? $customer_id : 'not set') . ', supplier_id: ' . (isset($supplier_id) ? $supplier_id : 'not set'));

	$transaction = array();
	if($transaction_type=='EXPENSE PAYMENT'){
		if($process=='UPDATE'){
			//delete previouse data of the transactions
			$CI->db->where("ref_expense_id",$reference_table_id)->delete("ac_transactions");
		}
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_expense_id" 	=> $reference_table_id,
								"debit_account_id" 		=> $debit_account_id,
								"debit_amt"		 		=> $debit_amt,
							);
	}
	else if($transaction_type=='PURCHASE PAYMENT RETURN'){
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_purchasepaymentsreturn_id" 	=> $reference_table_id,
								"credit_account_id" 	=> $credit_account_id,
								"credit_amt"		 	=> $credit_amt,
							);
	}
	else if($transaction_type=='PURCHASE PAYMENT'){
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_purchasepayments_id" 	=> $reference_table_id,
								"debit_account_id" 		=> $debit_account_id,
								"debit_amt"		 		=> $debit_amt,
							);
	}
	else if($transaction_type=='SALES PAYMENT RETURN'){
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_salespaymentsreturn_id" 	=> $reference_table_id,
								"debit_account_id" 		=> $debit_account_id,
								"debit_amt"		 		=> $debit_amt,
							);
	}
	else if($transaction_type=='SALES PAYMENT' || $transaction_type=='SALES PAYMENT & OB'){
		//CUSTOMER BULK PAYMENT INCLUDES OB PAYMENT
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_salespayments_id" 	=> $reference_table_id,
								"credit_account_id" 	=> $credit_account_id,
								"credit_amt"		 	=> $credit_amt,
							);
		
		
	}
	else if($transaction_type=='OPENING BALANCE PAID' && !empty($supplier_id)){
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_purchasepayments_id" 		=> $reference_table_id,
								"debit_account_id" 		=> $debit_account_id,
								"debit_amt"		 		=> $debit_amt,
							);
	}
	
	else if($transaction_type=='OPENING BALANCE PAID' && !empty($customer_id)){
		//SALES PAYMENTS
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_salespayments_id" 		=> $reference_table_id,
								"credit_account_id" 	=> $credit_account_id,
								"credit_amt"		 	=> $credit_amt,
							);
	}
	
	else if($transaction_type=='OPENING BALANCE' && empty($customer_id) && empty($supplier_id)){
		//WHILE CREATING ACCOUNT
		log_message('debug', 'Matched OPENING BALANCE condition for account creation');
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_accounts_id" 		=> $reference_table_id,
								"credit_account_id" 	=> $credit_account_id,
								"credit_amt"		 	=> $credit_amt,
							);
	}
	
	else if($transaction_type=='DEPOSIT'){
		if($process=='UPDATE'){
			//delete previouse data of the transactions
			$CI->db->where("ref_moneydeposits_id",$reference_table_id)->delete("ac_transactions");
		}
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_moneydeposits_id" 	=> $reference_table_id,
								"debit_account_id" 		=> $debit_account_id,
								"credit_account_id" 	=> $credit_account_id,
								"debit_amt"		 		=> $debit_amt,
								"credit_amt"		 	=> $credit_amt,
							);
	}
	else if($transaction_type=='TRANSFER'){
		if($process=='UPDATE'){
			//delete previouse data of the transactions
			$CI->db->where("ref_moneytransfer_id",$reference_table_id)->delete("ac_transactions");
		}
		$transaction = array( 
								"transaction_type" 		=> $transaction_type,
								"ref_moneytransfer_id" 	=> $reference_table_id,
								"debit_account_id" 		=> $debit_account_id,
								"credit_account_id" 	=> $credit_account_id,
								"debit_amt"		 		=> $debit_amt,
								"credit_amt"		 	=> $credit_amt,
							);
	}
	else{
		//"Invalid Transaction Type";
		log_message('error', 'No matching transaction type condition for: ' . $transaction_type . ' (customer_id: ' . (isset($customer_id) ? $customer_id : 'not set') . ', supplier_id: ' . (isset($supplier_id) ? $supplier_id : 'not set') . ')');
		return false;
	}

	$transaction['store_id'] = get_current_store_id();
	$transaction['created_by'] = $CI->session->userdata('inv_username');
	$transaction['created_date'] = date("Y-m-d");
	$transaction['transaction_date'] = $transaction_date;
	$transaction['note'] = $note;
	$transaction['payment_code'] = $payment_code;
	$transaction['customer_id'] = $customer_id;
	$transaction['supplier_id'] = $supplier_id;
	
	// Add currency information if provided
	if (isset($data['currency_id'])) {
		$transaction['currency_id'] = $data['currency_id'];
	}
	// Add multi-currency support
	if (isset($data['transaction_currency_id'])) {
		$transaction['transaction_currency_id'] = $data['transaction_currency_id'];
	}
	if (isset($data['exchange_rate'])) {
		$transaction['exchange_rate'] = $data['exchange_rate'];
	}
	if (isset($data['base_currency_debit_amt'])) {
		$transaction['base_currency_debit_amt'] = $data['base_currency_debit_amt'];
	}
	if (isset($data['base_currency_credit_amt'])) {
		$transaction['base_currency_credit_amt'] = $data['base_currency_credit_amt'];
	}

	// Log transaction data for debugging
	log_message('debug', 'Inserting transaction: ' . json_encode($transaction));
	
	// Check if ref_accounts_id is valid before inserting
	if (isset($transaction['ref_accounts_id'])) {
		$ref_account_id = $transaction['ref_accounts_id'];
		log_message('debug', 'Checking ref_accounts_id: ' . $ref_account_id);
		
		// Verify the account exists
		$account_check = $CI->db->query("SELECT id FROM ac_accounts WHERE id = ?", array($ref_account_id));
		if ($account_check->num_rows() == 0) {
			log_message('error', 'Account ID ' . $ref_account_id . ' does not exist in ac_accounts table');
			return false;
		}
		log_message('debug', 'Account ID ' . $ref_account_id . ' verified in ac_accounts table');
	}

	if($CI->db->insert("ac_transactions",$transaction)){
		log_message('debug', 'Transaction inserted successfully');

		if(!empty($debit_account_id)){
			if(!update_account_balance($debit_account_id)){
				log_message('error', 'Failed to update debit account balance: ' . $debit_account_id);
				return false;
			}
		}

		if(!empty($credit_account_id)){
			if(!update_account_balance($credit_account_id)){
				log_message('error', 'Failed to update credit account balance: ' . $credit_account_id);
				return false;
			}
		}

		log_message('debug', 'Account balances updated successfully');
		return true;
	} else {
		log_message('error', 'Failed to insert transaction: ' . $CI->db->last_query());
		log_message('error', 'Database error: ' . $CI->db->error()['message']);
	return false;
	}
}



function get_account_balance($account_id, $convert_to_base_currency = false){
	$CI =& get_instance();
	
	// Get account currency
	$CI->db->select('currency_id');
	$CI->db->from('ac_accounts');
	$CI->db->where('id', $account_id);
	$account = $CI->db->get()->row();
	
	if (!$account) {
		return 0;
	}
	
	// Calculate balance using corrected amounts for expense transactions
	$debit = 0;
	$credit = 0;
	
	// Get all debit transactions for this account
	$debit_transactions = $CI->db->select('id, debit_amt, transaction_type, ref_expense_id')
		->where('debit_account_id', $account_id)
		->get('ac_transactions')->result();
	
	foreach ($debit_transactions as $transaction) {
		$amount = $transaction->debit_amt;
		
		// For expense transactions, use original expense amount if available
		if ($transaction->transaction_type == 'EXPENSE PAYMENT' && $transaction->ref_expense_id) {
			$expense_info = $CI->db->select('expense_amt, expense_currency_id')
				->where('id', $transaction->ref_expense_id)
				->get('db_expense')->row();
			
			if ($expense_info) {
				// Convert expense amount to account currency
				if ($expense_info->expense_currency_id == $account->currency_id) {
					$amount = $expense_info->expense_amt;
				} else {
					$amount = convert_currency($expense_info->expense_amt, $expense_info->expense_currency_id, $account->currency_id);
				}
			}
		}
		
		$debit += $amount;
	}
	
	// Get all credit transactions for this account
	$credit_transactions = $CI->db->select('id, credit_amt, transaction_type, ref_expense_id')
		->where('credit_account_id', $account_id)
		->get('ac_transactions')->result();
	
	foreach ($credit_transactions as $transaction) {
		$amount = $transaction->credit_amt;
		
		// For expense transactions, use original expense amount if available
		if ($transaction->transaction_type == 'EXPENSE PAYMENT' && $transaction->ref_expense_id) {
			$expense_info = $CI->db->select('expense_amt, expense_currency_id')
				->where('id', $transaction->ref_expense_id)
				->get('db_expense')->row();
			
			if ($expense_info) {
				// Convert expense amount to account currency
				if ($expense_info->expense_currency_id == $account->currency_id) {
					$amount = $expense_info->expense_amt;
				} else {
					$amount = convert_currency($expense_info->expense_amt, $expense_info->expense_currency_id, $account->currency_id);
				}
			}
		}
		
		$credit += $amount;
	}
		
	$balance = $credit - $debit;
	
	// If conversion to base currency is requested and account has different currency
	if ($convert_to_base_currency && $account && $account->currency_id) {
		$base_currency = get_base_currency();
		if ($account->currency_id != $base_currency->id) {
			$exchange_rate = get_exchange_rate($account->currency_id, $base_currency->id);
			$balance = $balance * $exchange_rate;
		}
	}
	
	return $balance;
}

function get_currency_conversion_factor($from_currency_id, $to_currency_id) {
	// Provide reasonable default conversion factors for common currencies
	// These are approximate rates - should be updated with actual rates
	$conversion_factors = array(
		// From UGX to USD (assuming USD is base currency with ID 1)
		3 => array(1 => 0.00027), // 1 UGX = 0.00027 USD (approximately 1 USD = 3700 UGX)
		// From KES to USD
		2 => array(1 => 0.007),   // 1 KES = 0.007 USD (approximately 1 USD = 140 KES)
		// From USD to UGX
		1 => array(3 => 3700),    // 1 USD = 3700 UGX
		// From USD to KES
		1 => array(2 => 140),     // 1 USD = 140 KES
	);
	
	if (isset($conversion_factors[$from_currency_id][$to_currency_id])) {
		return $conversion_factors[$from_currency_id][$to_currency_id];
	}
	
	// If no specific rate found, return 1 (no conversion)
	return 1.0;
}
function get_or_create_currency_account($account_type, $currency_id, $store_id = null) {
	$CI =& get_instance();
	
	if (empty($store_id)) {
		$store_id = get_current_store_id();
	}
	
	// Get currency information
	$currency = get_currency_by_id($currency_id);
	if (!$currency) {
		return null;
	}
	
	// Look for existing account with this currency
	$CI->db->select('*');
	$CI->db->from('ac_accounts');
	$CI->db->where('account_selection_name', $account_type);
	$CI->db->where('currency_id', $currency_id);
	$CI->db->where('store_id', $store_id);
	$CI->db->where('delete_bit', 0);
	$existing_account = $CI->db->get()->row();
	
	if ($existing_account) {
		return $existing_account;
	}
	
	// Create new currency-specific account
	$base_currency = get_base_currency();
	$account_name = $account_type . ' (' . $currency->currency_code . ')';
	$account_code = strtoupper($account_type) . '_' . $currency->currency_code;
	
	// Generate count_id
	$count_id = get_count_id('ac_accounts');
	
	// Generate sort_code
	$maxid = $CI->db->select("coalesce(max(id),0)+1 as maxid")->get("ac_accounts")->row()->maxid;
	$sort_code = $maxid;
	
	$account_data = array(
		'count_id' => $count_id,
		'store_id' => $store_id,
		'sort_code' => $sort_code,
		'account_code' => $account_code,
		'currency_id' => $currency_id,
		'parent_id' => 0,
		'account_name' => $account_name,
		'account_selection_name' => $account_type,
		'note' => 'Auto-created currency-specific account for ' . $currency->currency_name,
		'created_date' => date('Y-m-d'),
		'created_time' => date('H:i:s'),
		'created_by' => $CI->session->userdata('inv_username'),
		'system_ip' => $_SERVER['REMOTE_ADDR'],
		'system_name' => gethostname(),
		'status' => 1,
		'balance' => 0
	);
	
	$CI->db->insert('ac_accounts', $account_data);
	$account_id = $CI->db->insert_id();
	
	// Create opening balance transaction
	insert_account_transaction(array(
		'transaction_type' => 'OPENING BALANCE',
		'reference_table_id' => $account_id,
		'debit_account_id' => null,
		'credit_account_id' => $account_id,
		'debit_amt' => 0,
		'credit_amt' => 0,
		'process' => 'SAVE',
		'note' => 'Opening balance for currency-specific account',
		'transaction_date' => date('Y-m-d'),
		'payment_code' => '',
		'customer_id' => null,
		'supplier_id' => null,
	));
	
	return $CI->db->get_where('ac_accounts', array('id' => $account_id))->row();
}

function get_multi_currency_account_balances($store_id = null) {
	$CI =& get_instance();
	
	if (empty($store_id)) {
		$store_id = get_current_store_id();
	}
	
	// Get all accounts with their currencies and balances (including cash accounts)
	$CI->db->select('a.id, a.account_name, a.account_code, a.currency_id, a.balance, a.base_currency_balance, c.currency_name, c.currency_code, c.symbol');
	$CI->db->from('ac_accounts a');
	$CI->db->join('db_currency c', 'a.currency_id = c.id', 'left');
	$CI->db->where('a.store_id', $store_id);
	$CI->db->where('a.status', 1);
	// Include both regular accounts (delete_bit = 0) and cash accounts (delete_bit = 1)
	$CI->db->where('(a.delete_bit = 0 OR a.delete_bit = 1)');
	$accounts = $CI->db->get()->result();
	
	$balances = array();
	$base_currency = get_base_currency();
	
	foreach ($accounts as $account) {
		// Use the account's stored balance fields directly
		$balance = $account->balance;
		$balance_base = $account->base_currency_balance;
		
		$balances[] = array(
			'account_id' => $account->id,
			'account_name' => $account->account_name,
			'account_code' => $account->account_code,
			'currency_id' => $account->currency_id,
			'currency_name' => $account->currency_name ?: $base_currency->currency_name,
			'currency_code' => $account->currency_code ?: $base_currency->currency_code,
			'currency_symbol' => $account->symbol ?: $base_currency->symbol,
			'balance' => $balance,
			'balance_base' => $balance_base,
			'is_base_currency' => $account->currency_id == $base_currency->id
		);
	}
	
	return $balances;
}

function has_existing_transactions($store_id = null) {
	$CI =& get_instance();
	
	if ($store_id === null) {
		$store_id = get_current_store_id();
	}
	
	// Check for any transactions in the system
	$tables_to_check = [
		'db_sales' => 'store_id',
		'db_purchase' => 'store_id', 
		'db_salesreturn' => 'store_id',
		'db_purchasereturn' => 'store_id',
		'db_expense' => 'store_id',
		'db_quotation' => 'store_id',
		'db_salespayments' => 'store_id',
		'db_purchasepayments' => 'store_id',
		'db_custadvance' => 'store_id',
		'ac_transactions' => 'store_id'
	];
	
	$blocking_tables = [];
	
	foreach ($tables_to_check as $table => $column) {
		$CI->db->select('COUNT(*) as count');
		$CI->db->from($table);
		$CI->db->where($column, $store_id);
		$result = $CI->db->get()->row();
		
		if ($result && $result->count > 0) {
			$blocking_tables[] = $table . ' (' . $result->count . ' records)';
		}
	}
	
	// If there are blocking tables, provide detailed error message
	if (!empty($blocking_tables)) {
		$error_message = "Cannot change base currency! The following tables still contain transactions:\n\n";
		$error_message .= implode("\n", $blocking_tables);
		$error_message .= "\n\nPlease delete all records from these tables before changing the base currency.";
		echo $error_message;
		exit();
	}
	
	return false;
}

function recalculate_all_account_balances(){
	$CI =& get_instance();
	
	// Get all accounts with their details
	$accounts = $CI->db->select('id, account_name, currency_id')
		->from('ac_accounts')
		->where('delete_bit', 0)
		->get()->result();
	
	$updated_count = 0;
	$error_count = 0;
	$errors = array();
	
	log_message('info', 'Starting account balance recalculation for ' . count($accounts) . ' accounts');
	
	foreach ($accounts as $account) {
		try {
			$old_balance = get_account_balance($account->id);
			
			if (update_account_balance($account->id)) {
				$new_balance = get_account_balance($account->id);
				$updated_count++;
				
				log_message('debug', 'Account ' . $account->account_name . ' (ID: ' . $account->id . ') - Old: ' . $old_balance . ', New: ' . $new_balance);
			} else {
				$error_count++;
				$errors[] = 'Account ' . $account->account_name . ' (ID: ' . $account->id . ') - Failed to update balance';
				log_message('error', 'Failed to update balance for account ' . $account->account_name . ' (ID: ' . $account->id . ')');
			}
		} catch (Exception $e) {
			$error_count++;
			$errors[] = 'Account ' . $account->account_name . ' (ID: ' . $account->id . ') - Exception: ' . $e->getMessage();
			log_message('error', 'Exception updating account ' . $account->account_name . ' (ID: ' . $account->id . '): ' . $e->getMessage());
		}
	}
	
	log_message('info', 'Account balance recalculation completed - Updated: ' . $updated_count . ', Errors: ' . $error_count);
	
	return array(
		'updated' => $updated_count,
		'errors' => $error_count,
		'total' => count($accounts),
		'error_details' => $errors
	);
}

function update_account_balance($account_id){
	$CI =& get_instance();
	
	// Log the account balance update attempt
	log_message('debug', 'Updating account balance for account ID: ' . $account_id);
	
	// Get account currency information
	$CI->db->select('currency_id');
	$CI->db->from('ac_accounts');
	$CI->db->where('id', $account_id);
	$account = $CI->db->get()->row();
	
	if (!$account) {
		log_message('error', 'Account not found for ID: ' . $account_id);
		return false;
	}
	
	// Calculate balance using corrected amounts for expense transactions
	$debit = 0;
	$credit = 0;
	
	// Get all debit transactions for this account
	$debit_transactions = $CI->db->select('id, debit_amt, transaction_type, ref_expense_id')
		->where('debit_account_id', $account_id)
		->get('ac_transactions')->result();
	
	foreach ($debit_transactions as $transaction) {
		$amount = $transaction->debit_amt;
		
		// For expense transactions, use original expense amount if available
		if ($transaction->transaction_type == 'EXPENSE PAYMENT' && $transaction->ref_expense_id) {
			$expense_info = $CI->db->select('expense_amt, expense_currency_id')
				->where('id', $transaction->ref_expense_id)
				->get('db_expense')->row();
			
			if ($expense_info) {
				// Convert expense amount to account currency
				if ($expense_info->expense_currency_id == $account->currency_id) {
					$amount = $expense_info->expense_amt;
				} else {
					$amount = convert_currency($expense_info->expense_amt, $expense_info->expense_currency_id, $account->currency_id);
				}
			}
		}
		
		$debit += $amount;
	}
	
	// Get all credit transactions for this account
	$credit_transactions = $CI->db->select('id, credit_amt, transaction_type, ref_expense_id')
		->where('credit_account_id', $account_id)
		->get('ac_transactions')->result();
	
	foreach ($credit_transactions as $transaction) {
		$amount = $transaction->credit_amt;
		
		// For expense transactions, use original expense amount if available
		if ($transaction->transaction_type == 'EXPENSE PAYMENT' && $transaction->ref_expense_id) {
			$expense_info = $CI->db->select('expense_amt, expense_currency_id')
				->where('id', $transaction->ref_expense_id)
				->get('db_expense')->row();
			
			if ($expense_info) {
				// Convert expense amount to account currency
				if ($expense_info->expense_currency_id == $account->currency_id) {
					$amount = $expense_info->expense_amt;
				} else {
					$amount = convert_currency($expense_info->expense_amt, $expense_info->expense_currency_id, $account->currency_id);
				}
			}
		}
		
		$credit += $amount;
	}
		
	$balance = $credit - $debit;
	
	log_message('debug', 'Account ' . $account_id . ' - Debit: ' . $debit . ', Credit: ' . $credit . ', Balance: ' . $balance);
	
	// Debug: Log individual transactions for this account
	$transactions = $CI->db->select('id, transaction_type, debit_amt, credit_amt, currency_id, exchange_rate, base_currency_credit_amt, base_currency_debit_amt, ref_salespayments_id')
		->where('debit_account_id', $account_id)
		->or_where('credit_account_id', $account_id)
		->get('ac_transactions')->result();
	
	log_message('debug', 'Account ' . $account_id . ' - Transaction details: ' . json_encode($transactions));
	
	// Debug: Check if there are any sales payments for this account
	$sales_payments = $CI->db->select('id, payment, payment_currency_id, exchange_rate, base_currency_amount, account_id')
		->where('account_id', $account_id)
		->get('db_salespayments')->result();
	
	log_message('debug', 'Account ' . $account_id . ' - Sales payments: ' . json_encode($sales_payments));
	
	// Calculate base currency balance
	$base_currency_balance = $balance;
	if ($account->currency_id && $account->currency_id != get_base_currency_id()) {
		$exchange_rate = get_exchange_rate($account->currency_id, get_base_currency_id());
		$base_currency_balance = $balance * $exchange_rate;
		log_message('debug', 'Account ' . $account_id . ' - Base currency balance: ' . $base_currency_balance . ' (Exchange rate: ' . $exchange_rate . ')');
	}
	
	// Update both balance fields
	$q1 = $CI->db->set('balance', $balance)
		->set('base_currency_balance', $base_currency_balance)
		->where("id", $account_id)
		->update("ac_accounts");
		
	if(!$q1){
		log_message('error', 'Failed to update account balance for ID: ' . $account_id . ' - Query: ' . $CI->db->last_query());
		log_message('error', 'Database error: ' . json_encode($CI->db->error()));
		return false;
	}
	
	log_message('debug', 'Successfully updated account balance for ID: ' . $account_id);
	return true;
}

function clear_all_transactions_for_currency_change($store_id = null) {
	$CI =& get_instance();
	
	if ($store_id === null) {
		$store_id = get_current_store_id();
	}
	
	// Tables to clear for currency change
	$tables_to_clear = [
		'db_sales' => 'store_id',
		'db_purchase' => 'store_id', 
		'db_salesreturn' => 'store_id',
		'db_purchasereturn' => 'store_id',
		'db_expense' => 'store_id',
		'db_quotation' => 'store_id',
		'db_salespayments' => 'store_id',
		'db_purchasepayments' => 'store_id',
		'db_custadvance' => 'store_id',
		'ac_transactions' => 'store_id'
	];
	
	$CI->db->trans_begin();
	
	$cleared_tables = [];
	
	foreach ($tables_to_clear as $table => $column) {
		try {
			$CI->db->where($column, $store_id);
			$result = $CI->db->delete($table);
			
			if ($result) {
				$cleared_tables[] = $table;
			}
		} catch (Exception $e) {
			// Table might not exist, continue
		}
	}
	
	if ($CI->db->trans_status() === FALSE) {
		$CI->db->trans_rollback();
		return false;
	} else {
		$CI->db->trans_commit();
		return $cleared_tables;
	}
}
