<?php

use App\Core\Database;

if (!function_exists('db')) {
    function db()
    {
        return Database::getInstance();
    }
}

if (!function_exists('user_id')) {
    function user_id()
    {
        // In a real app, getting from session
        return $_SESSION['user_id'] ?? 0;
    }
}

if (!function_exists('strRandom')) {
    function strRandom($length = 16)
    {
        return bin2hex(random_bytes($length / 2));
    }
}

if (!function_exists('gs')) {
    function gs()
    {
        // Simple caching to avoid multiple DB hits
        static $settings;
        if ($settings)
            return $settings;

        $db = Database::getInstance();
        $rows = $db->fetchAll("SELECT * FROM settings WHERE `group` = 'general'"); // Adjust query as needed

        $config = new stdClass();
        // Set default values if needed
        $config->wallet = 1;
        $config->smtp_from_address = '';

        // This logic depends on how 'settings' table is structured in the original app.
        // Assuming key-value pairs or a single row with columns.
        // Based on db.sql, it seems there's a 'name' and 'payload' (or value).
        // For simplicity, we'll try to map it generically.

        foreach ($rows as $row) {
            $key = $row['name'] ?? $row['key'] ?? null;
            $value = $row['payload'] ?? $row['value'] ?? null;
            if ($key) {
                $config->$key = $value;
            }
        }

        // Manual overrides for testing/demo if DB is empty
        $config->uddoktapay_api_key = $config->uddoktapay_api_key ?? 'test_key';
        $config->uddoktapay_api_url = $config->uddoktapay_api_url ?? 'https://pay.quickpaybd.xyz';

        $settings = $config;
        return $config;
    }
}

if (!function_exists('route')) {
    function route($name, $params = [])
    {
        // Simple router mapper
        $routes = [
            'user.codes' => '/user/codes.php',
            'user.orders' => '/user/orders.php',
            'user.account' => '/user/account.php',
            'user.addfunds' => '/user/addfunds.php',
        ];
        return $routes[$name] ?? '/';
    }
}

if (!function_exists('__')) {
    function __($key)
    {
        return $key;
    }
}

if (!function_exists('back')) {
    function back()
    {
        // Return a mock object for chaining ->with()
        return new class {
            public function with($key, $message)
            {
                $_SESSION['flash'][$key] = $message;
                return $this; // allows chaining but we can't easily redirect in a helper without context
            }
        };
    }
}

if (!function_exists('redirect')) {
    function redirect($url)
    {
        // If it's the back() object, logic needs to differ. 
        // For simple redirect:
        header("Location: $url");
        return new class {
            public function with($key, $message)
            {
                $_SESSION['flash'][$key] = $message;
                // In real PHP, header is already set, so this execution happens before flush.
            }
        };
    }
}

if (!function_exists('view')) {
    function view($view, $data = [])
    {
        // In this API-centric module, we might just return the data or include a file
        extract($data);
        // require __DIR__ . "/../../views/{$view}.php"; 
        // For now, let's just return the data for debugging/API usage
        return $data;
    }
}

if (!function_exists('getPercentageAmount')) {
    function getPercentageAmount($amount, $percentage)
    {
        return ($amount * $percentage) / 100;
    }
}

if (!function_exists('auth')) {
    function auth()
    {
        // Return a dummy object covering auth()->user()->balance etc.
        return new class {
            public function user()
            {
                $db = Database::getInstance();
                $id = user_id();
                $user = $db->fetch("SELECT * FROM users WHERE id = ?", [$id]);

                if (!$user)
                    return null;

                // Return object with properties
                return (object) $user;
            }
        };
    }
}
