<?php

if (!function_exists('setting')) {
    /**
     * Get setting value by key
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    function setting($key, $default = null)
    {
        static $settings = null;
        
        // Try to get from cache first
        if ($settings === null) {
            try {
                // Check if Settings model exists and table exists
                if (class_exists('App\Models\Setting') && \Schema::hasTable('settings')) {
                    $settings = cache()->remember('system_settings', 3600, function() {
                        return \App\Models\Setting::pluck('value', 'key')->toArray();
                    });
                } else {
                    // Fallback to config
                    $settings = config('settings', []);
                }
            } catch (\Exception $e) {
                // If any error, return default
                return $default;
            }
        }
        
        return $settings[$key] ?? $default;
    }
}

if (!function_exists('format_currency')) {
    /**
     * Format amount as currency
     *
     * @param float $amount
     * @return string
     */
    function format_currency($amount)
    {
        return '৳ ' . number_format($amount, 2);
    }
}

if (!function_exists('generate_invoice_no')) {
    /**
     * Generate invoice number
     *
     * @return string
     */
    function generate_invoice_no()
    {
        $prefix = 'INV';
        $date = date('Ymd');
        
        try {
            if (class_exists('App\Models\Sale')) {
                $lastId = \App\Models\Sale::max('id') ?? 0;
                $number = str_pad($lastId + 1, 6, '0', STR_PAD_LEFT);
            } else {
                $number = str_pad(1, 6, '0', STR_PAD_LEFT);
            }
        } catch (\Exception $e) {
            $number = str_pad(1, 6, '0', STR_PAD_LEFT);
        }
        
        return $prefix . '-' . $date . '-' . $number;
    }
}

if (!function_exists('generate_payment_no')) {
    /**
     * Generate payment number
     *
     * @return string
     */
    function generate_payment_no()
    {
        $prefix = 'PAY';
        $date = date('Ymd');
        
        try {
            if (class_exists('App\Models\Payment')) {
                $lastId = \App\Models\Payment::max('id') ?? 0;
                $number = str_pad($lastId + 1, 6, '0', STR_PAD_LEFT);
            } else {
                $number = str_pad(1, 6, '0', STR_PAD_LEFT);
            }
        } catch (\Exception $e) {
            $number = str_pad(1, 6, '0', STR_PAD_LEFT);
        }
        
        return $prefix . '-' . $date . '-' . $number;
    }
}