<?php
/**
 * TOPBD — Core Helper Functions
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Get dynamic setting value with fallback
 */
function get_setting(string $key, string $default = ''): string {
    static $settingsCache = null;
    if ($settingsCache === null) {
        $db = get_db();
        try {
            $stmt = $db->query("SELECT setting_key, setting_value FROM settings");
            $settingsCache = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        } catch (Exception $e) {
            $settingsCache = [];
        }
    }
    return $settingsCache[$key] ?? $default;
}

/**
 * Get dynamic frontend text value with fallback
 */
function get_text(string $key, string $default = ''): string {
    static $textsCache = null;
    if ($textsCache === null) {
        $db = get_db();
        try {
            $stmt = $db->query("SELECT text_key, text_value FROM frontend_texts");
            $textsCache = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        } catch (Exception $e) {
            $textsCache = [];
        }
    }
    return $textsCache[$key] ?? $default;
}

/**
 * Format currency as Bangladeshi Taka
 */
function format_currency(float $amount): string {
    $symbol = get_setting('currency_symbol', '৳');
    return $symbol . number_format($amount, 0);
}

/**
 * Escape HTML output securely against XSS
 */
function e(?string $string): string {
    return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
}

/**
 * CSRF Protection Token
 */
function csrf_token(): string {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verify_csrf(?string $token): bool {
    if (empty($_SESSION['csrf_token']) || empty($token)) {
        return false;
    }
    return hash_equals($_SESSION['csrf_token'], $token);
}

/**
 * Get client IP safely
 */
function get_client_ip(): string {
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ips[0]);
    }
    return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
}

/**
 * JSON Response helper
 */
function json_response(array $data, int $statusCode = 200): void {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data);
    exit;
}

/**
 * Generate unique transaction reference
 */
function generate_txn_id(string $gateway): string {
    return 'TXN-' . strtoupper($gateway) . '-' . strtoupper(substr(md5(uniqid((string)mt_rand(), true)), 0, 8));
}

/**
 * Format time since current bid was achieved
 */
function format_bid_age(?string $timestamp): string {
    if (empty($timestamp)) {
        return 'recently';
    }
    $time = strtotime($timestamp);
    if ($time === false) {
        return 'recently';
    }
    $diffSec = max(0, time() - $time);
    $diffMin = floor($diffSec / 60);
    $diffHours = floor($diffMin / 60);
    $diffDays = floor($diffHours / 24);
    $diffWeeks = floor($diffDays / 7);

    if ($diffMin < 1) {
        return 'just now';
    }
    if ($diffMin < 60) {
        return $diffMin . ($diffMin == 1 ? ' minute ago' : ' minutes ago');
    }
    if ($diffHours < 24) {
        return $diffHours . ($diffHours == 1 ? ' hour ago' : ' hours ago');
    }
    if ($diffDays == 1) {
        return 'yesterday';
    }
    if ($diffDays < 7) {
        return $diffDays . ' days ago';
    }
    return $diffWeeks . ($diffWeeks == 1 ? ' week ago' : ' weeks ago');
}
