<?php
/**
 * Please see weepie-framework.php for more details.
 */

namespace WpieFw\Hooks;

use WpieFw\Wpie\WpieGlobals;
use WpieFw\Helpers\WpieMiscHelper;
use WpieFw\Helpers\WpieMultisiteHelper;
use WpieFw\Exceptions\WpieExceptionInterface;
use WpieFw\Exceptions\WpieExceptionLogger;

if( ! defined( 'ABSPATH' ) ) exit;

/**
 * WpieHooksFrontend Class
 *
 * @author $Author: Vincent Weber <weepie-plugins@outlook.com> $
 * @since 1.4.0
 */
final class WpieHooksFrontend extends WpieHooks
{
	/**
	 * Constructor
	 *
	 * @access public
	 *
	 * @since 1.4.0
	 *
	 * @param WpieGlobals $globals
	 */
	public function __construct( WpieGlobals $globals )
	{
		parent::__construct( $globals );
	}

	/**
	 * {@inheritDoc}
	 * @see WpieHooks::add()
	 */
	public function add()
	{
		// Frontend hooks
		if( !is_admin() ) {
			/**
			 * description for hook activate_{$nameSpace}_do_frontend_hooks
			 */
			if( $this->doFrontend ===  apply_filters( $this->globals->nameSpace . '_do_frontend_hooks', true ) ) {
				add_action( 'wp_enqueue_scripts', [$this, 'setStylesFrontend'] );
				add_action( 'wp_enqueue_scripts', [$this, 'setScriptsFrontend'] );
				add_action( 'template_redirect', [ $this, 'renderTemplate' ] );

				if( isset( $_REQUEST['action'] ) && 'wpie-footer-action' === $_REQUEST['action'] ) {
					add_action( 'wp_footer', [ $this, 'processAjaxRequest' ], 99999 );
				}
			}
		}
	}

	/**
	 * Get global JavaScript parameters for the frontend
	 *
	 * @access public
	 *
	 * @since 2.0.15
	 */
	public function setScriptFrontendVars( $wpieVars )
	{
		// WordPress installation URI
		$wpuri = get_bloginfo( 'wpurl' );
		// is multisite or not
		$isMs = WpieMultisiteHelper::isMs();

		// build array with vars
		$wpieVars['ns'] = $this->globals->nameSpace;
		$wpieVars['nonce'] = wp_create_nonce( $this->globals->nameSpace . '-action' );
		$wpieVars['wpurl'] = $wpuri;
		$wpieVars['domain'] = WpieMiscHelper::getHostWithoutSubdomain( $wpuri );
		$wpieVars['ajaxurl'] = admin_url( 'admin-ajax.php' );
		$wpieVars['referer'] = wp_get_referer();
		$wpieVars['currenturl'] = ( $isMs ) ? WpieMultisiteHelper::getCurrentUri() : home_url( add_query_arg( NULL, NULL ) );
		$wpieVars['isms'] = ( $isMs ) ? true : false;
		$wpieVars['mspath'] = ( $isMs ) ? WpieMultisiteHelper::getBlogDetail( 'path' ) : '/' ;
		$wpieVars['ssl'] = is_ssl();

		// fix for install with a sub folder setup
		// @since 1.1.8
		if( false !== strpos( $wpieVars['currenturl'] , '/' ) && !$isMs ) {
			$wpieVars['currenturl'] = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		}

		return $wpieVars;
	}

	/**
	 * Callback for the wp_enqueue_scripts hook: Enqueue scripts for the front-end
	 *
	 * @acces public
	 *
	 * @uses wp_enqueue_script()
	 * @uses wp_add_inline_script()
	 *
	 * @since 0.1
	 * @since 2.0.15 uses wp_add_inline_script()
	 */
	public function setScriptsFrontend()
	{
		$uriAssetsJs = $this->globals->get( 'wfJsUri' );
		$pluginPath = $this->globals->get( 'pluginPath' );
		$jsUri = $this->globals->get( 'jsUri' );
		$isScriptDebug = WpieMiscHelper::isScriptDebug();
		$ext = ( $isScriptDebug ) ? '.js' : '.min.js';

		// make sure jQuery is enqueued
		wp_enqueue_script( 'jquery' );
		// enqueu common functions
		wp_enqueue_script( 'wpie-common',  $uriAssetsJs . '/wpie-common' . $ext, [], $this->globals->get( 'versionWf' ), true );

		if( file_exists( $pluginPath . '/assets/js/global' . $ext ) ) {
			wp_enqueue_script( $this->globals->nameSpace . '-global', $jsUri . '/global' . $ext, [ 'jquery', 'wpie-common' ], $this->globals->get('version') );
		}

		try {
			// Get global plugin vars before (the main script)
			add_filter( $this->globals->nameSpace . '_script_frontend_vars_before', [ $this, 'setScriptFrontendVars' ] );

			/**
			 * Let modules add script(s) to enqueue
			 * 
			 * @param array $moduleScripts
			 * @since 2.0.15
			 */
			$scripts = apply_filters( $this->globals->nameSpace . '_scripts_frontend', [] );

			foreach( $scripts as $k => $script ) {
				$dataBefore = $dataAfter = [];
				$isMain = isset( $script->main ) && $script->main;

				if( $isMain ) {
					$handle = $this->globals->nameSpace . '-frontend';
				} else {
					$handle = isset( $script->handle ) ? $script->handle : $this->globals->nameSpace . '-frontend-' . $k;	
				}
						
				$path = rtrim( $script->path, $ext ) . $ext;
				$dep = isset( $script->dep ) ? $script->dep : [];

				wp_enqueue_script( $handle, $path, $dep, $this->globals->get( 'version' ), $script->args );

				if( $isMain ) {
					$dataBefore = apply_filters( $this->globals->nameSpace . '_script_frontend_vars_before', [] );
					$dataAfter = apply_filters( $this->globals->nameSpace . '_script_frontend_vars_after', [] );	
				} else {
					$dataBefore = apply_filters( $this->globals->nameSpace . '_script_frontend_vars_before_' . $handle, [] );
					$dataAfter = apply_filters( $this->globals->nameSpace . '_script_frontend_vars_after_' . $handle, [] );
				}

				$dataBeforeStr = $dataBefore ? json_encode( $dataBefore ) : '';
				$dataAfterStr = $dataAfter ? json_encode( $dataAfter ) : '';

				if( $dataBeforeStr ) {
					$data = sprintf( 'var %s = %s', $this->globals->get( 'jsNamespace' ), $dataBeforeStr );
					wp_add_inline_script( $handle, $data, 'before' );
				}
				if( $dataAfterStr ) {
					wp_add_inline_script( $handle, $dataAfterStr, 'after');
				}					
			}
		} catch ( WpieExceptionInterface $e ) {
			WpieExceptionLogger::log( $e, true );
		}
	}


	/**
	 * Callback for the wp_enqueue_scripts hook
	 *
	 * @acces public
	 * 
	 * @uses wp_enqueue_style()
	 * @uses wp_add_inline_style()
	 *
	 * @since 0.1
	 * @since 2.0.15 uses wp_add_inline_style()
	 */
	public function setStylesFrontend()
	{
		$isScriptDebug = WpieMiscHelper::isScriptDebug();
		$ext = ( $isScriptDebug ) ? '.css' : '.min.css';

		try {
			/**
			 * Let modules add styles(s) to enqueue
			 * 
			 * @param array $styles
			 * @since 2.0.15
			 */
			$styles = apply_filters( $this->globals->nameSpace . '_styles_frontend', [] );		

			foreach( $styles as $k => $style ) {
				$isMain = isset( $style->main ) && $style->main;

				if( $isMain ) {
					$handle = $this->globals->nameSpace . '-frontend';
				} else {
					$handle = isset( $style->handle ) ? $style->handle : $this->globals->nameSpace . '-frontend-' . $k;	
				}
						
				$path = preg_replace( '#'. $ext .'$#', '', $style->path ) . $ext;
				$dep = isset( $style->dep ) ? $style->dep : [];

				wp_enqueue_style( $handle, $path, $dep, $this->globals->get( 'version' ) );

				if( $isMain ) {
					$inline = sprintf( '/* %s Plugin - V%s */%s', $this->globals->get( 'pluginName' ), $this->globals->get( 'version' ), PHP_EOL );
					$inline = apply_filters( $this->globals->nameSpace . '_styles_frontend_inline', $inline );	
				} else {
					$inline = apply_filters( $this->globals->nameSpace . '_styles_frontend_inline_' . $handle, '' );
				}

				if( $inline ) {
					wp_add_inline_style( $handle, $inline );
				}					
			}
		} catch ( WpieExceptionInterface $e ) {
			WpieExceptionLogger::log( $e, true );
		}
	}

	/**
	 * Callback for the template_redirect hook: render front-end templates
	 *
	 * @access public
	 *
	 * @since 0.1
	 */
	public function renderTemplate()
	{
		try {
			/**
			 * @todo description for hook {$nameSpace}_render_templates
			 */
			do_action( $this->globals->nameSpace . '_render_templates' );
		} catch ( WpieExceptionInterface $e ) {
			WpieExceptionLogger::log( $e, true );
		}
	}
}