<?php

declare(strict_types=1);

use App\Core\Security;

function env(string $key, mixed $default = null): mixed
{
    $value = $_ENV[$key] ?? getenv($key);

    if ($value === false || $value === null || $value === '') {
        return $default;
    }

    return match (strtolower((string) $value)) {
        'true', '(true)' => true,
        'false', '(false)' => false,
        'null', '(null)' => null,
        default => $value,
    };
}

function config(string $key, mixed $default = null): mixed
{
    static $config = null;

    if ($config === null) {
        $config = require BASE_PATH . '/config/app.php';
    }

    $segments = explode('.', $key);
    $value = $config;

    foreach ($segments as $segment) {
        if (!is_array($value) || !array_key_exists($segment, $value)) {
            return $default;
        }

        $value = $value[$segment];
    }

    return $value;
}

function e(mixed $value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function u_lower(string $value): string
{
    return function_exists('mb_strtolower') ? mb_strtolower($value, 'UTF-8') : strtolower($value);
}

function u_substr(string $value, int $start, ?int $length = null): string
{
    if (function_exists('mb_substr')) {
        return $length === null
            ? mb_substr($value, $start, null, 'UTF-8')
            : mb_substr($value, $start, $length, 'UTF-8');
    }

    return $length === null ? substr($value, $start) : substr($value, $start, $length);
}

function u_upper(string $value): string
{
    return function_exists('mb_strtoupper') ? mb_strtoupper($value, 'UTF-8') : strtoupper($value);
}

function asset(string $path): string
{
    return '/assets/' . ltrim($path, '/');
}

function route_path(string $path): string
{
    return '/' . ltrim($path, '/');
}

function is_active(string $path): string
{
    $current = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
    return rtrim($current, '/') === rtrim(route_path($path), '/') ? 'active' : '';
}

function csrf_field(): string
{
    return '<input type="hidden" name="_csrf" value="' . e(Security::csrfToken()) . '">';
}

function status_label(string $status): string
{
    return match ($status) {
        'solved' => 'Решен',
        'in_progress' => 'В процес',
        'late' => 'Просрочен',
        'unresolved' => 'Нерешен',
        default => $status,
    };
}

function status_class(string $status): string
{
    return match ($status) {
        'solved' => 'success',
        'in_progress' => 'warning',
        'late', 'unresolved' => 'danger',
        default => 'secondary',
    };
}

function initials(string $name): string
{
    $parts = preg_split('/\s+/u', trim($name)) ?: [];
    $first = u_substr($parts[0] ?? 'C', 0, 1);
    $second = u_substr($parts[1] ?? '', 0, 1);

    return u_upper($first . $second);
}
