<?php

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

function redirect($url)
{
    header("Location: " . $url);
    exit;
}

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

function admin_asset($path)
{
    return BASE_URL . '/admin/assets/' . ltrim($path, '/');
}

function generate_slug($string)
{
    $slug = strtolower(trim($string));
    $slug = preg_replace('/[^a-z0-9]+/i', '-', $slug);
    return trim($slug, '-');
}

function format_price($amount, $currency = 'GBP')
{
    $symbols = [
        'GBP' => '£',
        'USD' => '$',
        'XCD' => 'EC$',
        'LKR' => 'Rs.',
    ];

    $symbol = $symbols[$currency] ?? $currency . ' ';
    return $symbol . number_format((float)$amount, 2);
}

function is_post()
{
    return $_SERVER['REQUEST_METHOD'] === 'POST';
}

function csrf_token()
{
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return $_SESSION['csrf_token'];
}

function csrf_field()
{
    return '<input type="hidden" name="csrf_token" value="' . e(csrf_token()) . '">';
}

function verify_csrf()
{
    if (!isset($_POST['csrf_token'], $_SESSION['csrf_token'])) {
        return false;
    }

    return hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']);
}