<?php
namespace Tshen;

function view(string $name, array $data = []): string {
    extract($data);
    $path = __DIR__ . '/../views/' . $name . '.php';
    ob_start();
    include __DIR__ . '/../views/layout/header.php';
    include $path;
    include __DIR__ . '/../views/layout/footer.php';
    return ob_get_clean();
}

function redirect(string $to): void {
    // If $to is an absolute URL, send it as-is
    if (strpos($to, 'http://') === 0 || strpos($to, 'https://') === 0) {
        header('Location: ' . $to);
        exit;
    }
    header('Location: ' . url($to));
    exit;
}

function auth_user() { return $_SESSION['user'] ?? null; }
function require_auth() { if (!auth_user()) redirect('/login'); }

function role(): string { return $_SESSION['role'] ?? 'guest'; }

function csrf_token(): string {
    if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
    return $_SESSION['csrf'];
}
function csrf_check(): bool {
    return isset($_POST['csrf']) && isset($_SESSION['csrf']) && hash_equals($_SESSION['csrf'], $_POST['csrf']);
}
function csrf_field(): string { return '<input type="hidden" name="csrf" value="' . csrf_token() . '">'; }

function flash(string $key, ?string $val = null) {
    if ($val === null) {
        $v = $_SESSION['flash'][$key] ?? null; unset($_SESSION['flash'][$key]); return $v;
    } else { $_SESSION['flash'][$key] = $val; }
}

// Helper to determine application base path (useful when app runs in a subdirectory)
function base_path(): string {
    $bp = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
    if ($bp === '' || $bp === '/' || $bp === '\\') return '';
    return $bp;
}

// Build a URL relative to the application base path. Accepts paths like '/', '/classes', 'classes'.
function url(string $path = '/'): string {
    $bp = base_path();
    // If $path looks like an absolute http(s) URL, return as-is
    if (preg_match('#^https?://#i', $path)) return $path;
    $path = '/' . ltrim($path, '/');
    return ($bp === '') ? $path : $bp . $path;
}

// Convenience helper for assets under /public
function asset(string $path): string {
    // Normalize passed path: remove any leading `/` or `public/` so callers may pass
    // values like `public/foo.jpg`, `/public/foo.jpg` or `foo.jpg` safely.
    $p = preg_replace('#^/?public/#', '', ltrim($path, '/'));
    return url('public/' . ltrim($p, '/'));
}