<?php

namespace Openguru\OpenCartFramework\Support;

use InvalidArgumentException;

class Utils
{
    /**
     * @return array|string[]
     */
    public static function ucsplit(string $string): array
    {
        return preg_split('/(?=\p{Lu})/u', $string, -1, PREG_SPLIT_NO_EMPTY) ?? [];
    }

    public static function safeJsonDecode(string $content)
    {
        $decoded = json_decode($content, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new InvalidArgumentException('JSON error: ' . json_last_error_msg());
        }

        return $decoded;
    }

    /**
     * @psalm-return list<mixed>
     */
    public static function arrayFlatten(array $array, $depth = INF): array
    {
        $result = [];

        foreach ($array as $item) {
            if (! is_array($item)) {
                $result[] = $item;
            } else {
                $values = $depth === 1
                    ? array_values($item)
                    : static::arrayFlatten($item, $depth - 1);

                foreach ($values as $value) {
                    $result[] = $value;
                }
            }
        }

        return $result;
    }

    /**
     * @return never
     */
    public static function dd()
    {
        $args = func_get_args();
        echo '<pre>';
        /** @psalm-suppress ForbiddenCode */
        var_dump(...$args);
        echo '</pre>';
        die();
    }

    public static function strContains(string $haystack, string $needle): bool
    {
        return $needle === '' || strpos($haystack, $needle) !== false;
    }

    public static function boolToInt(bool $value): int
    {
        return $value === true ? 1 : 0;
    }

    public static function getCurrentDomain(): string
    {
        $scheme = 'http';
        if (
            (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
            (! empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')
        ) {
            $scheme = 'https';
        }

        // Определяем хост
        $host = $_SERVER['HTTP_X_FORWARDED_HOST']
            ?? $_SERVER['HTTP_HOST']
            ?? $_SERVER['SERVER_NAME']
            ?? 'localhost';

        // Порт
        $port = $_SERVER['SERVER_PORT'] ?? null;
        $defaultPort = ($scheme === 'https') ? 443 : 80;

        if ($port && $port != $defaultPort && strpos($host, ':') === false) {
            $host .= ':' . $port;
        }

        return $scheme . '://' . $host;
    }
}
