<?php

declare(strict_types=1);

use Core\Csrf;
use Core\Session;

function loadEnv(string $path): void
{
    if (!file_exists($path)) {
        return;
    }

    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    foreach ($lines as $line) {
        $line = trim($line);

        if ($line === '' || str_starts_with($line, '#')) {
            continue;
        }

        [$name, $value] = array_pad(explode('=', $line, 2), 2, '');
        $name = trim($name);
        $value = trim($value);

        if ($value !== '' && ((str_starts_with($value, '"') && str_ends_with($value, '"')) || (str_starts_with($value, "'") && str_ends_with($value, "'")))) {
            $value = substr($value, 1, -1);
        }

        $_ENV[$name] = $value;
        $_SERVER[$name] = $value;
        putenv($name . '=' . $value);
    }
}

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

function baseUrl(string $path = ''): string
{
    $configured = trim((string) env('APP_URL', ''));

    if ($configured !== '') {
        $root = rtrim($configured, '/');
    } else {
        $isHttps = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
        $scheme = $isHttps ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
        $scriptDir = rtrim($scriptDir, '/');

        $root = $scheme . '://' . $host;
        if ($scriptDir !== '' && $scriptDir !== '/') {
            $root .= $scriptDir;
        }
    }

    return $root . ($path ? '/' . ltrim($path, '/') : '');
}

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

function redirect(string $path): never
{
    header('Location: ' . $path);
    exit;
}

function data_get(array $array, string $key, mixed $default = null): mixed
{
    if ($key === '') {
        return $array;
    }

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

    foreach ($segments as $segment) {
        if (is_array($value) && array_key_exists($segment, $value)) {
            $value = $value[$segment];
            continue;
        }
        return $default;
    }

    return $value;
}

function old(string $key, mixed $default = ''): mixed
{
    $old = Session::getOldInput();
    return data_get($old, $key, $default);
}

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

function formatDate(?string $date): string
{
    if (!$date) {
        return '-';
    }
    try {
        return (new DateTimeImmutable($date))->format('d/m/Y');
    } catch (Throwable) {
        return (string) $date;
    }
}

function formatMoney(mixed $value): string
{
    if ($value === null || $value === '') {
        return '-';
    }
    return 'R$ ' . number_format((float) $value, 2, ',', '.');
}

function yesNo(?int $value): string
{
    return (int) $value === 1 ? 'Sim' : 'Não';
}

function selected(mixed $value, mixed $expected): string
{
    return (string) $value === (string) $expected ? 'selected' : '';
}

function checked(mixed $value, mixed $expected = 1): string
{
    return (string) $value === (string) $expected ? 'checked' : '';
}

function csrf_field(): string
{
    return '<input type="hidden" name="_token" value="' . e(Csrf::token()) . '">';
}
