<?php
declare(strict_types=1);

use App\Core\Auth;
use App\Core\Config;
use App\Core\Csrf;
use App\Core\Settings;
use App\Core\Session;
use App\Core\View;

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

function app_name(): string
{
    return (string) Config::get('app.name', 'WiFi Access');
}

function company_name(): string
{
    try {
        return (string) Settings::get('company_name', app_name());
    } catch (Throwable) {
        return app_name();
    }
}

function company_logo(): ?string
{
    try {
        $logo = Settings::get('company_logo');
        return is_string($logo) && $logo !== '' ? $logo : null;
    } catch (Throwable) {
        return null;
    }
}

function setting(string $key, mixed $default = null): mixed
{
    try {
        return Settings::get($key, $default);
    } catch (Throwable) {
        return $default;
    }
}

function base_url(string $path = ''): string
{
    $url = rtrim((string) Config::get('app.url', ''), '/');
    $path = '/' . ltrim($path, '/');

    return $url . $path;
}

function asset(string $path): string
{
    return base_url($path);
}

function url(string $path = ''): string
{
    return base_url($path);
}

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

function csrf(): string
{
    return Csrf::field();
}

function verify_csrf(?string $token): void
{
    Csrf::verify($token);
}

function flash(string $key, mixed $default = null): mixed
{
    return Session::getFlash($key, $default);
}

function old(string $key, mixed $default = ''): mixed
{
    $oldInput = Session::getFlash('old_input', []);

    return is_array($oldInput) ? ($oldInput[$key] ?? $default) : $default;
}

function auth_user(): ?array
{
    return Auth::user();
}

function auth_check(): bool
{
    return Auth::check();
}

function require_auth(): void
{
    if (! Auth::check()) {
        abort(403, 'Silakan login terlebih dahulu.');
    }
}

function require_role(string $role): void
{
    require_auth();

    if (Auth::role() !== $role) {
        abort(403, 'Akses ditolak.');
    }
}

function purchase_status_label(string $status): string
{
    return match ($status) {
        'pending' => 'Pending',
        'verified' => 'Diverifikasi',
        'completed' => 'Selesai',
        'rejected' => 'Ditolak',
        default => $status,
    };
}

function view(string $template, array $data = [], string $layout = 'public/layout'): string
{
    return View::renderTemplate($template, $data, $layout);
}

function abort(int $status, string $message = ''): never
{
    http_response_code($status);
    echo View::renderTemplate('public/error', [
        'status' => $status,
        'message' => $message,
    ]);
    exit;
}
