<?php

if (!function_exists('ec_toast')) {
    function ec_toast(string $message, string $type = 'success', ?string $title = null): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            @session_start();
        }

        $_SESSION['ec_toasts'][] = [
            'type' => $type,
            'title' => $title,
            'message' => $message,
            'time' => time(),
        ];
    }
}

if (!function_exists('ec_toast_success')) {
    function ec_toast_success(string $message, ?string $title = null): void
    {
        ec_toast($message, 'success', $title);
    }
}

if (!function_exists('ec_toast_error')) {
    function ec_toast_error(string $message, ?string $title = null): void
    {
        ec_toast($message, 'error', $title);
    }
}

if (!function_exists('ec_toast_warning')) {
    function ec_toast_warning(string $message, ?string $title = null): void
    {
        ec_toast($message, 'warning', $title);
    }
}

if (!function_exists('ec_toast_info')) {
    function ec_toast_info(string $message, ?string $title = null): void
    {
        ec_toast($message, 'info', $title);
    }
}

if (!function_exists('ec_take_toasts')) {
    function ec_take_toasts(): array
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            @session_start();
        }

        $toasts = $_SESSION['ec_toasts'] ?? [];

        foreach (['flash_success' => 'success', 'flash_error' => 'error', 'flash_warning' => 'warning', 'flash_info' => 'info'] as $k => $type) {
            if (!empty($_SESSION[$k])) {
                $toasts[] = [
                    'type' => $type,
                    'title' => null,
                    'message' => (string)$_SESSION[$k],
                    'time' => time(),
                ];
                unset($_SESSION[$k]);
            }
        }

        unset($_SESSION['ec_toasts']);

        return $toasts;
    }
}
