<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Cash Account Helper
 * Provides functions for managing default Cash Account
 */

if (!function_exists('get_cash_account_name')) {
    function get_cash_account_name() {
        return 'Cash Account';
    }
}

if (!function_exists('create_default_cash_account')) {
    function create_default_cash_account($store_id) {
        $CI =& get_instance();
        if (!$CI->db->table_exists('ac_accounts')) {
            return null;
        }
        // Check if Cash Account already exists for this store
        $CI->db->where('store_id', $store_id);
        $CI->db->where('account_name', get_cash_account_name());
        $existing = $CI->db->get('ac_accounts')->row();
        
        if ($existing) {
            return $existing->id; // Return existing account ID
        }
        
        // Get store's currency ID
        $CI->db->select('currency_id');
        $CI->db->where('id', $store_id);
        $store = $CI->db->get('db_store')->row();
        
        if (!$store) {
            return false; // Store not found
        }
        
        // Create Cash Account
        $info = array(
            'store_id'          => $store_id,
            'count_id'          => 1, // Simple count_id for now
            'account_name'      => get_cash_account_name(),
            'account_code'      => 'CASH/' . str_pad($store_id, 3, '0', STR_PAD_LEFT),
            'currency_id'       => $store->currency_id, // Use store's currency
            'sort_code'         => 'CASH' . $store_id,
            'parent_id'         => NULL,
            'paymenttypes_id'   => NULL,
            'customer_id'       => NULL,
            'supplier_id'       => NULL,
            'expense_id'        => NULL,
            'created_date'      => date('Y-m-d'),
            'created_time'      => date('H:i:s'),
            'created_by'        => 'System',
            'system_ip'         => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1',
            'system_name'       => $_SERVER['HTTP_HOST'] ?? 'localhost',
            'status'            => 1,
            'delete_bit'        => 1, // Cannot be deleted
        );
        
        try {
            $CI->db->insert('ac_accounts', $info);
            return $CI->db->insert_id();
        } catch (Exception $e) {
            log_message('error', 'Cash Account Creation Error: ' . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('get_cash_account_id')) {
    function get_cash_account_id($store_id) {
        $CI =& get_instance();
        if (!$CI->db->table_exists('ac_accounts')) {
            return null;
        }
        // Try to get existing Cash Account
        $CI->db->where('store_id', $store_id);
        $CI->db->where('account_name', get_cash_account_name());
        $account = $CI->db->get('ac_accounts')->row();
        
        if ($account) {
            return $account->id;
        }
        
        // Create if doesn't exist
        return create_default_cash_account($store_id);
    }
}

if (!function_exists('get_cash_account_balance')) {
    function get_cash_account_balance($store_id, $as_of_date = null) {
        $CI =& get_instance();
        $cash_account_id = get_cash_account_id($store_id);
        
        if (!$cash_account_id) {
            return 0;
        }
        
        // This would need to be implemented based on your transaction system
        // For now, return 0 as we don't have transaction tracking yet
        return 0;
    }
}

if (!function_exists('sync_cash_account_currency')) {
    function sync_cash_account_currency($store_id) {
        $CI =& get_instance();
        $CI->load->database();
        $CI->load->helper('multi_currency_helper');

        // Get store's current currency
        $store_currency = get_base_currency($store_id);
        if (!$store_currency) {
            log_message('error', 'Cannot sync Cash Account currency - store currency not found for store_id: ' . $store_id);
            return false;
        }

        // Find all Cash Accounts for this store
        $CI->db->select('id, account_name, currency_id');
        $CI->db->where('store_id', $store_id);
        $CI->db->where('account_name', get_cash_account_name());
        $cash_accounts = $CI->db->get('ac_accounts')->result();

        $synced_count = 0;
        foreach ($cash_accounts as $account) {
            if ($account->currency_id != $store_currency->id) {
                // Update currency to match store
                $CI->db->where('id', $account->id);
                $CI->db->update('ac_accounts', array('currency_id' => $store_currency->id));
                
                if ($CI->db->affected_rows() > 0) {
                    $synced_count++;
                    log_message('info', 'Cash Account ID ' . $account->id . ' currency synced to ' . $store_currency->currency_code . ' (ID: ' . $store_currency->id . ')');
                }
            }
        }

        log_message('info', 'Cash Account currency sync completed for store_id: ' . $store_id . ' - ' . $synced_count . ' accounts updated');
        return $synced_count;
    }
}

if (!function_exists('sync_all_cash_accounts_currency')) {
    function sync_all_cash_accounts_currency() {
        $CI =& get_instance();
        $CI->load->database();

        // Get all stores
        $stores = $CI->db->get('db_store')->result();
        $total_synced = 0;

        foreach ($stores as $store) {
            $synced = sync_cash_account_currency($store->id);
            $total_synced += $synced;
        }

        log_message('info', 'All Cash Accounts currency sync completed - ' . $total_synced . ' total accounts updated');
        return $total_synced;
    }
}
