<?php
namespace SPAATG\Controller;

if ( ! defined( 'ABSPATH' ) ) {
 exit; // Exit if accessed directly.
}

use SPAATG\Notices\NoticeController as Notices;

use SPAATG\Model\AccessModel as AccessModel;

// Use SPAATG\Model\ApiKeyModel as ApiKeyModel

/**
 * Controller for automatic Notices about status of the plugin.
 * This controller is bound for automatic fire. Regular procedural notices should just be queued using the Notices modules.
 * Called in admin_notices.
 */
class AdminNoticesController extends \SPAATG\Controller
{
    protected static $instance;

    protected $definedNotices = array( // NoticeModels by Class.  This is not optimal but until solution found, workable.
        'QuotaNoticeMonth',
        'QuotaNoticeReached',
        'ApiNotice',
        'ApiNoticeRepeat',
        'ApiNoticeRepeatLong',
        'ListviewNotice',
    );
    protected $adminNotices; // Models

    private $silent_mode = false;

    public function __construct()
    {
        add_action('admin_notices', array($this, 'displayNotices'), 50); // notices occured before page load
        add_action('admin_footer', array($this, 'displayNotices'));  // called in views.

        // no persistent notifications with this flag set.
        if (defined('SPAATG_SILENT_MODE') && SPAATG_SILENT_MODE === true)
        {
            $this->silent_mode = true;
            return;
        }
        add_action('admin_notices', array($this, 'check_admin_notices'), 5); // run before the plugin admin notices

        self::resetOldNotices();
				$this->initNotices();
    }

    public static function getInstance()
    {
        if (is_null(self::$instance))
            self::$instance = new static();

        return self::$instance;
    }

    public static function resetAllNotices()
    {
        Notices::resetNotices();
    }

		// Notices no longer in use.
		public static function resetOldNotices()
		{
			Notices::removeNoticeByID('MSG_FEATURE_SMARTCROP');
			Notices::removeNoticeByID('MSG_FEATURE_HEIC');
			Notices::removeNoticeByID('MSG_INTEGRATION_NGGALLERY');

      // This one is not old,
		}

    /** Triggered when plugin is activated */
    public static function resetCompatNotice()
    {
        Notices::removeNoticeByID('MSG_COMPAT');
    }

    public static function resetAPINotices()
    {
        Notices::removeNoticeByID('MSG_NO_APIKEY');
        Notices::removeNoticeByID('MSG_NO_APIKEY_REPEAT');
        Notices::removeNoticeByID('MSG_NO_APIKEY_REPEAT_LONG');
    }

    public static function resetQuotaNotices()
    {
        Notices::removeNoticeByID('MSG_UPGRADE_MONTH');
        Notices::removeNoticeByID('MSG_UPGRADE_BULK');
        Notices::removeNoticeByID('MSG_QUOTA_REACHED');
    }

    public static function resetIntegrationNotices()
    {
        Notices::removeNoticeByID('MSG_INTEGRATION_NGGALLERY');
    }

    public static function resetLegacyNotice()
    {
        Notices::removeNoticeByID('MSG_CONVERT_LEGACY');
    }

    public function isSilentMode()
    {
       return $this->silent_mode;
    }

    public function displayNotices()
    {
        if (! \wpSPAATG()->env()->is_screen_to_use)
        {
            if(get_current_screen()->base !== 'dashboard') // ugly exception for dashboard.
            {
                return; // suppress all when not our screen.
            }
            else {
              \wpSPAATG()->load_style('spaatg-notices');
              \wpSPAATG()->load_style('spaatg-notices-module');
            }
        }

        $access = AccessModel::getInstance();
        $screen = get_current_screen();
        $screen_id = \wpSPAATG()->env()->screen_id;
        $is_our_screen = \wpSPAATG()->env()->is_our_screen; 

        $noticeControl = Notices::getInstance();


        if ($noticeControl->countNotices() > 0)
        {

            $notices = $noticeControl->getNoticesForDisplay();
            if (count($notices) > 0)
            {

                foreach($notices as $notice)
                {
                    
                    if ($notice->checkScreen($screen_id) === false)
                    {
                        continue;
                    }
                    // Bit hacky; limit global messages to our screens. Next step here @todo would be to include a remotenotice flag in the noticemodel
                    elseif (strpos($notice->getID(), 'Global') !== false && false === $is_our_screen)
                    {
                        continue; 
                    }
	                    elseif ($access->noticeIsAllowed($notice))
	                    {
	                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Notice HTML is generated by the internal notice renderer.
	                        echo $notice->getForDisplay();
	                    }
                    else
                    {
                        continue;
                    }


                    if ($notice->getID() == 'MSG_QUOTA_REACHED' || $notice->getID() == 'MSG_UPGRADE_MONTH')
                    {
                        // This is still needed
                        wp_enqueue_script('spaatg-jquery-knob');
                        wp_enqueue_script('spaatg');
                    }
                }
            }
        }
        $noticeControl->update(); // puts views, and updates
    }

    /* General function to check on Hook for admin notices if there is something to show globally */
    public function check_admin_notices()
    {
        if (! \wpSPAATG()->env()->is_screen_to_use)
        {
            if(get_current_screen()->base !== 'dashboard') // ugly exception for dashboard.
                return; // suppress all when not our screen.
        }

       $this->loadNotices();
    }

    protected function initNotices()
    {
        foreach($this->definedNotices as $className)
        {
            $ns = '\SPAATG\Model\AdminNotices\\' . $className;
            $class = new $ns();

            $this->adminNotices[$class->getKey()] = $class;
        }

        // Init the notice icons
        $noticeControl = Notices::getInstance();
        $noticeControl->loadIcons(array(
            'normal' => '<img class="short-pixel-notice-icon" src="' . plugins_url('res/img/slider.png', SPAATG_PLUGIN_FILE) . '">',
            'success' => '<img class="short-pixel-notice-icon" src="' . plugins_url('res/img/robo-cool.png', SPAATG_PLUGIN_FILE) . '">',
            'warning' => '<img class="short-pixel-notice-icon" src="' . plugins_url('res/img/robo-scared.png', SPAATG_PLUGIN_FILE) . '">',
            'error' => '<img class="short-pixel-notice-icon" src="' . plugins_url('res/img/robo-scared.png', SPAATG_PLUGIN_FILE) . '">',
        ));

    }

		protected function loadNotices()
		{
			 foreach($this->adminNotices as $key => $class)
			 {
				  $class->load();
			 }

		}

    public function getNoticeByKey($key)
    {
        if (isset($this->adminNotices[$key]))
        {
            return $this->adminNotices[$key];
        }
        else {
            return false;
        }
    }

    public function getAllNotices()
    {
        return $this->adminNotices;
    }


    // Called by MediaLibraryModel
    public function invokeLegacyNotice()
    {
        $noticeModel = $this->getNoticeByKey('MSG_CONVERT_LEGACY');
        if (is_object($noticeModel) && false ==  $noticeModel->isDismissed())
        {
            $noticeModel->addManual();
        }
    }

    /**
     * 
     * @var SPAATG\Controller\functon
     */
    public function getRemoteOffer()
    {
       return false;
    }

} // class
