<?php

namespace NeurogenesisTheme\Core;

use NeurogenesisTheme\Traits\IsSingleton;


class FlashMessages
{
    use IsSingleton;

    /**
     * optionName
     *
     * @var string
     */
    private $optionName = 'neurogenesis_theme_flash_messages';

    /**
     * Adds a Flash Message
     *
     * @param  mixed $message
     * @param  mixed $status
     * @return array
     */
    public function addMessage($message, $status = 'success')
    {
        $messages = $this->getMessages();
        $messages[] = [
            'status' => $status,
            'message' => $message
        ];
        $this->saveMessages($messages);
    }

    /**
     * Display all the Flash Messages 
     *
     * @param  mixed $echo
     * @return string
     */
    public function displayMessages($echo = true)
    {
        $messages = $this->getMessages();
        $str = '';

        if (!empty($messages)) {
            ob_start();
?>
            <div class="neurogenesis-theme-flash-messages mb-6 space-y-3" role="status" aria-live="polite">
                <?php foreach ($messages as $message) :
                    $status = isset($message['status']) ? (string) $message['status'] : 'success';
                    $is_error = 'error' === $status;
                    $classes = $is_error
                        ? 'border-red-200 bg-red-50 text-red-800'
                        : 'border-emerald-200 bg-emerald-50 text-emerald-800';
                    ?>
                    <div class="rounded-md border px-4 py-3 text-sm font-medium <?php echo esc_attr($classes); ?>">
                        <?php echo esc_html((string) ($message['message'] ?? '')); ?>
                    </div>
                <?php endforeach; ?>
            </div>
<?php
            $str = ob_get_clean();
            $this->deleteMessages();
        }

        if (!$echo) {
            return $str;
        }

        echo $str;
    }


    /**
     * Get a list of Flash Messages
     *
     * @return array
     */
    private function getMessages()
    {
        $messages = get_transient($this->optionName);

        return is_array($messages) ? $messages : [];
    }

    /**
     * Save a Flash Message
     *
     * @param  mixed $messages
     * @return void
     */
    private function saveMessages($messages)
    {
        set_transient($this->optionName, $messages, 5 * MINUTE_IN_SECONDS); //expires in 5 minutes
    }

    /**
     * Deletes a Flash Message
     *
     * @return void
     */
    private function deleteMessages()
    {
        delete_transient($this->optionName);
    }
}
//Helper functions
//neurogenesis_theme_add_flash_message() - add a new Flash Message
//neurogenesis_theme_show_flash_messages() - display all the Flash Messages