<?php

declare( strict_types=1 );

namespace Soft_Tehnica\Freya_Sync_Service\Services;

use Soft_Tehnica\Freya_Sync_Service\Data\Notification;

class NotificationManager
{

    private static NotificationManager $instance;
    private function __construct()
    {
        $this->notifications = SessionService::get()->getNotifications();

        add_action( 'wp_ajax_nopriv_fss_get_notifications', [$this, 'ajax_notifications'] );
        add_action( 'wp_ajax_fss_get_notifications', [$this, 'ajax_notifications'] );
    }

    /** @var Notification[] */
    private array $notifications = [];

    public static function get(): NotificationManager
    {
        if ( !isset( self::$instance ) ) {
            self::$instance = new NotificationManager();
        }

        return self::$instance;
    }

    /**
     * @return Notification[]
     */
    public function getAll(): array
    {
        return $this->notifications;
    }

    public function push( Notification $notification ): void
    {
        $this->notifications[] = $notification;
        SessionService::get()->setNotifications( $this->notifications );
    }

    public function clear(): void
    {
        $this->notifications = [];
        SessionService::get()->setNotifications( [] );
    }

    public function renderAll(): void
    {
        foreach ( $this->notifications as $notification ) {
            $notification->render();
        }
    }

    public function ajax_notifications(): void
    {
        check_ajax_referer( 'wp_rest', 'nonce' );
        $notifications = $this->notifications;
        $this->clear();
        wp_send_json_success( $notifications );
    }
}
