<?php

namespace Core\Helpers;
// -------------------------------------------------------------
// Test display function (already in your code)
// -------------------------------------------------------------
if (!function_exists('__display_test')) {
    function __display_test($type, $file) {
        $path = TESTS_PATH . DIRECTORY_SEPARATOR . $type . DIRECTORY_SEPARATOR . $file;

        if (!file_exists($path)) {
            die('Test file not found. Please ensure the name is correct in your controller');
        }
        require_once $path;
        exit;
    }
}

if (!function_exists('excerpt')) {
    function excerpt(string $text, int $limit = 20): string
    {
        $text = strip_tags($text);

        if (mb_strlen($text) <= $limit) {
            return $text;
        }

        return mb_substr($text, 0, $limit) . '...';
    }
}

if(!function_exists('toInt')) {
function toInt(string $value): int {
    return (int) preg_replace('/[^0-9\-]/', '', $value);
}

}

// if(!function_exists('formatCurrency')) {
//     function formatCurrency($amount, $currency = '₦') {
//         return $currency . number_format((float)$amount, 2);
//     }
// }

    function formatCurrency($amount, $currency = '₦') {
        return $currency . number_format((float)$amount, 2);
    }

// -------------------------------------------------------------
// Redirect helper
// -------------------------------------------------------------
if (!function_exists('redirect')) {
    /**
     * Redirect to a given URL and exit.
     * - In development: uses config 'url'
     * - In production: auto-detects host
     */
    function redirect(string $path, int $statusCode = 302) {
        // Load app config
        $config = require __DIR__ . '/../app/config/app.php';

        // Normalize path (avoid double slashes)
        $path = '/' . ltrim($path, '/');

        if ($config['env'] === 'development') {
            // Use base URL from config
            $baseUrl = rtrim($config['url'], '/');
            $url = $baseUrl . $path;
        } else {
            // Detect protocol + host for production
            $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
            $host   = $_SERVER['HTTP_HOST'];
            $basePath = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])), '/');
            $url = "{$scheme}://{$host}{$basePath}{$path}";
        }

        header("Location: {$url}", true, $statusCode);
        exit;
    }
}


// -------------------------------------------------------------
// URL helper (current URL)
// -------------------------------------------------------------
if (!function_exists('current_url')) {
    /**
     * Get the current full URL.
     */
    function current_url(): string {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
        $host     = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $uri      = $_SERVER['REQUEST_URI'] ?? '/';
        return "{$protocol}://{$host}{$uri}";
    }
}

// -------------------------------------------------------------
// Debug helper
// -------------------------------------------------------------
if (!function_exists('dd')) {
    /**
     * Dump and Die (like Laravel's dd).
     */
    function dd(...$vars) {
        echo "<pre style='background:#222;color:#0f0;padding:10px;border-radius:5px;'>";
        foreach ($vars as $var) {
            print_r($var);
            echo "\n";
        }
        echo "</pre>";
        exit;
    }
}

// -------------------------------------------------------------
// Sanitize helper
// -------------------------------------------------------------
// if (!function_exists('sanitize')) {
//     /**
//      * Sanitize input string for XSS prevention.
//      */
//     function sanitize(string $value): string {
//         return htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
//     }
// }

// -------------------------------------------------------------
// View loader helper
// -------------------------------------------------------------
if (!function_exists('view')) {
    /**
     * Simple view loader.
     * Looks inside /app/views/
     */
    function view(string $name, array $data = []) {
        $viewPath = __DIR__ . '/../app/views/' . str_replace('.', '/', $name) . '.php';

        if (!file_exists($viewPath)) {
            die("View [{$name}] not found.");
        }

        extract($data); // Make $data available as variables in the view
        require $viewPath;
    }
}



if(!function_exists('sanitizeArray')) {
    function sanitizeArray(array $data): array {
        return array_map('sanitize', $data);
    }
}

if (!function_exists('getModelTable')) {
    /**
     * Get the database table name for a given model class.
     *
     * @param string $modelClass The fully qualified model class name.
     * @return string The table name.
     * @throws ReflectionException
     */
    function getModelTable(string $modelClass): string
    {
        $reflection = new ReflectionClass($modelClass);
        return $reflection->getStaticPropertyValue('table');
    }
}

function sanitize($data, bool $stripTags = true) {
    if (is_array($data)) {
        return array_map(fn($item) => sanitize($item, $stripTags), $data);
    }

    $data = trim($data); // Remove whitespace from beginning/end
    if ($stripTags) {
        $data = strip_tags($data); // Remove HTML tags
    }
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8'); // Convert special characters
    return $data;
}

?>
