<?php

namespace App\Helpers;

use App\Models\Currency;
use App\Models\SystemSetting;

class CurrencyHelper
{
    /**
     * Get the current system currency
     */
    public static function getCurrentCurrency()
    {
        return Currency::getCurrent();
    }

    /**
     * Get the current currency code
     */
    public static function getCurrentCurrencyCode()
    {
        $currency = self::getCurrentCurrency();
        return $currency ? $currency->code : 'KES';
    }

    /**
     * Get the current currency symbol
     */
    public static function getCurrentCurrencySymbol()
    {
        $currency = self::getCurrentCurrency();
        return $currency ? $currency->symbol : 'KSh';
    }

    /**
     * Get currency symbol by code (alias for backward compatibility)
     */
    public static function getSymbol($currencyCode = null)
    {
        if ($currencyCode) {
            $currency = Currency::where('code', $currencyCode)->first();
            return $currency ? $currency->symbol : 'KSh';
        }

        return self::getCurrentCurrencySymbol();
    }

    /**
     * Format amount with current currency
     */
    public static function formatAmount($amount, $includeSymbol = true)
    {
        $currency = self::getCurrentCurrency();

        if (!$currency) {
            return number_format($amount, 2);
        }

        $displayFormat = SystemSetting::get('currency_display_format', 'symbol');
        $decimalPlaces = (int) SystemSetting::get('decimal_places', 2);
        $thousandsSeparator = SystemSetting::get('thousands_separator', ',');
        $decimalSeparator = SystemSetting::get('decimal_separator', '.');

        $formatted = number_format($amount, $decimalPlaces, $decimalSeparator, $thousandsSeparator);

        if (!$includeSymbol) {
            return $formatted;
        }

        switch ($displayFormat) {
            case 'code':
                return $currency->code . ' ' . $formatted;
            case 'both':
                return $currency->symbol . ' ' . $formatted . ' ' . $currency->code;
            case 'symbol':
            default:
                return $currency->symbol . $formatted;
        }
    }

    /**
     * Format amount (alias for formatAmount for backward compatibility)
     */
    public static function format($amount, $includeSymbol = true)
    {
        return self::formatAmount($amount, $includeSymbol);
    }

    /**
     * Get currency options for dropdowns
     */
    public static function getCurrencyOptions()
    {
        return Currency::active()->ordered()->pluck('name', 'code')->toArray();
    }

    /**
     * Convert amount between currencies (basic implementation)
     * In a real application, you'd use exchange rates
     */
    public static function convertAmount($amount, $fromCurrencyCode, $toCurrencyCode)
    {
        // For now, just return the amount as-is
        // In a real implementation, you'd use exchange rate APIs
        return $amount;
    }
}
