<?php

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

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

function old($key)
{
    return $_POST[$key] ?? '';
}

function set_flash($message, $type = 'success')
{
    $_SESSION['flash'] = [
        'message' => $message,
        'type' => $type
    ];
}

function get_flash()
{
    if (!isset($_SESSION['flash'])) {
        return null;
    }

    $flash = $_SESSION['flash'];

    unset($_SESSION['flash']);

    return $flash;
}

function current_user()
{
    return $_SESSION['user'] ?? null;
}

function is_logged_in()
{
    return isset($_SESSION['user']);
}

function require_login()
{
    if (!is_logged_in()) {

        redirect('../auth/login.php');

    }
}

function has_role($role)
{
    if (!is_logged_in()) {

        return false;

    }

    return strtolower($_SESSION['user']['role']) == strtolower($role);
}

function dd($data)
{
    echo "<pre>";

    print_r($data);

    die;
}