<?php

declare(strict_types=1);

if (!function_exists('hub_db')) {
    function hub_db(): ?mysqli
    {
        global $conn, $mysqli, $db, $link;
        foreach ([$conn ?? null, $mysqli ?? null, $db ?? null, $link ?? null] as $candidate) {
            if ($candidate instanceof mysqli) {
                return $candidate;
            }
        }
        return null;
    }
}

if (!function_exists('hub_table_exists')) {
    function hub_table_exists(?mysqli $db, string $table): bool
    {
        if (!$db || $table === '') return false;
        $safe = $db->real_escape_string($table);
        $res = @$db->query("SHOW TABLES LIKE '{$safe}'");
        return $res instanceof mysqli_result && $res->num_rows > 0;
    }
}

if (!function_exists('hub_column_exists')) {
    function hub_column_exists(?mysqli $db, ?string $table, string $column): bool
    {
        if (!$db || !$table || $column === '') return false;
        $safeTable = $db->real_escape_string($table);
        $safeColumn = $db->real_escape_string($column);
        $res = @$db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeColumn}'");
        return $res instanceof mysqli_result && $res->num_rows > 0;
    }
}

if (!function_exists('hub_fetch_value')) {
    function hub_fetch_value(?mysqli $db, string $sql, string $key = 'c', int|float $default = 0): int|float
    {
        if (!$db) return $default;
        try {
            $res = $db->query($sql);
            if ($res instanceof mysqli_result) {
                $row = $res->fetch_assoc();
                return isset($row[$key]) ? (is_float($default) ? (float)$row[$key] : (int)$row[$key]) : $default;
            }
        } catch (Throwable $e) {
        }
        return $default;
    }
}

if (!function_exists('hub_fetch_all')) {
    function hub_fetch_all(?mysqli $db, string $sql): array
    {
        if (!$db) return [];
        try {
            $res = $db->query($sql);
            if (!$res instanceof mysqli_result) return [];
            $rows = [];
            while ($row = $res->fetch_assoc()) {
                $rows[] = $row;
            }
            return $rows;
        } catch (Throwable $e) {
            return [];
        }
    }
}

if (!function_exists('hub_table_count')) {
    function hub_table_count(?mysqli $db, string $table, string $where = '1'): int
    {
        if (!$db || !hub_table_exists($db, $table)) return 0;
        return (int) hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$table}` WHERE {$where}");
    }
}

if (!function_exists('hub_format_iqd')) {
    function hub_format_iqd(int|float $amount): string
    {
        return number_format((float)$amount, 0) . ' د.ع';
    }
}

if (!function_exists('hub_status_badge')) {
    function hub_status_badge(string $label, string $type = 'info'): string
    {
        return '<span class="nay-badge ' . htmlspecialchars($type) . '">' . htmlspecialchars($label) . '</span>';
    }
}


if (!function_exists('hub_h')) {
    function hub_h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('hub_settings_map')) {
    function hub_settings_map(?mysqli $db): array
    {
        static $cache = null;
        if ($cache !== null) {
            return $cache;
        }
        $cache = [];
        if (!$db || !hub_table_exists($db, 'settings')) {
            return $cache;
        }
        try {
            $res = $db->query("SELECT setting_key, setting_value FROM settings");
            if ($res instanceof mysqli_result) {
                while ($row = $res->fetch_assoc()) {
                    $cache[(string)($row['setting_key'] ?? '')] = (string)($row['setting_value'] ?? '');
                }
            }
        } catch (Throwable $e) {
        }
        return $cache;
    }
}

if (!function_exists('hub_setting')) {
    function hub_setting(?mysqli $db, string $key, ?string $default = null): ?string
    {
        $settings = hub_settings_map($db);
        return array_key_exists($key, $settings) ? (string)$settings[$key] : $default;
    }
}

if (!function_exists('hub_setting_enabled')) {
    function hub_setting_enabled(?mysqli $db, string $key, bool $default = false): bool
    {
        $value = hub_setting($db, $key, $default ? '1' : '0');
        return in_array((string)$value, ['1', 'true', 'yes', 'on'], true);
    }
}
