<?php

declare(strict_types=1);

namespace MyCustomizer\WooCommerce\Connector\Libs;

use Exception;
use Symfony\Component\HttpFoundation\Session\Session;

class MczrFlashMessage
{
    const TYPE_ERROR = 'error';
    const TYPE_INFO = 'info';
    const TYPE_SUCCESS = 'success';
    const TYPE_WARNING = 'warning';

    /** @var Session */
    private $session;

    public function __construct()
    {
        $this->session = new Session();
    }

    public function init(): void
    {
        \add_action('admin_notices', [$this, 'display'], 10, 0);
    }

    public function add(string $type = self::TYPE_INFO, string $message = ''): self
    {
        $this->session->getFlashBag()->add($type, $message);

        return $this;
    }

    /**
     * @return void|string
     */
    public function display()
    {
        if (!session_start()) {
            return '';
        }
        try {
            $all = $this->session->getFlashBag()->all();
        } catch (Exception $e) {
            return '';
        }
        if (empty($all)) {
            return '';
        }
        foreach ($all as $type => $messages) {
            foreach ($messages as $message) {
                echo '<div class="notice notice-' . \esc_attr($type) . ' is-dismissible"><p>' . \esc_attr($message) . '</p></div>';
            }
        }
    }
}
