<?php


namespace Easymailing\App\Core\Provider;


use Easymailing\App\Core\Application;

class EnqueueProvider implements ProviderInterface
{
	private $application;
	private $adminStyles;
	private $adminScripts;
	private $frontScripts;

	public function __construct(Application $application)
	{
		$this->application = $application;

		$this->adminStyles = [];
		$this->adminScripts = [];
		$this->frontScripts = [];
	}

	public function register()
	{
		$admin = $this->application->getConfigurations()['admin_enqueue'];

		if(array_key_exists('css', $admin) !== false){
			$this->adminStyles = $admin['css'];
		}

		if(array_key_exists('scripts', $admin) !== false){
			$this->adminScripts = $admin['scripts'];
		}

		if(array_key_exists('front_scripts', $admin) !== false){
			$this->frontScripts = $admin['front_scripts'];
		}

		add_action( 'admin_enqueue_scripts', array( $this, 'adminEnqueue' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'frontEnqueue' ) );
	}

	public function adminEnqueue() {
		$pluginUrl = $this->application->getConfigurations()['plugin_url'];
		foreach($this->adminStyles as $adminStyle) {
			wp_enqueue_style( $adminStyle['id'], $pluginUrl . 'assets/build/'.$adminStyle['file'] );
		}

		foreach($this->adminScripts as $adminScrip) {
			wp_enqueue_script( $adminScrip['id'], $pluginUrl . 'assets/build/'.$adminScrip['file'] );
			wp_localize_script($adminScrip['id'],'easymailingVars',[
				'ajaxurl' => admin_url('admin-ajax.php'),
				'plugin_configuration_url' => menu_page_url('easymailing_configuration', false),
				'plugin_synchronization_dashboard_url' => menu_page_url('easymailing_synchronization', false),
			]);
		}
	}

	public function frontEnqueue() {
		$pluginUrl = $this->application->getConfigurations()['plugin_url'];
		foreach($this->frontScripts as $frontScript) {
			wp_enqueue_script( $frontScript['id'], $pluginUrl . 'assets/build/'.$frontScript['file'] );
			wp_localize_script($frontScript['id'],'easymailingVars',[
				'ajaxurl' => admin_url('admin-ajax.php'),
				'plugin_configuration_url' => menu_page_url('easymailing_configuration', false),

			]);
		}
	}

	public static function shouldRegister(): bool
	{
		return true;
	}
}
