<?php
/**
 * Assets Class.
 *
 * @category Class file
 * @package WLC\Algolia
 * @author White Label Coders
 * @license TO DO
 * @link TO DO
 */

namespace wlc_algolia;

use wlc_algolia\Helpers as helper;

defined( 'ABSPATH' ) || die( 'Direct file access is forbidden' );

/**
 *  Handles static assets.
 *
 * @category Connection
 * @package WLC\Algolia
 * @author WLC
 * @license TO DO
 * @link TO DO
 */
class Assets {

	/**
	 * Class constructor.
	 *
	 * @return void
	 */
	public function __construct() {
		// Enqueue scripts.
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ), 5 );
	}

	/**
	 * Enqueues scripts.
	 *
	 * @param string $hook_suffix Current admin page hook suffix (admin only).
	 */
	public function enqueue_scripts( string $hook_suffix = '' ) {
		$is_algolia_admin_screen = is_admin() && ( 'toplevel_page_wlc-algolia' === $hook_suffix );

		$scripts = \wlc_algolia\WLC_Algolia::instance()->get_config( 'scripts' );

		// Filter scripts.
		$scripts = array_filter(
			$scripts,
			function ( $script ) use ( $is_algolia_admin_screen ) {
				$scope = (array) helper\get_array_value( $script, 'scope', 'frontend' );

				// Frontend scripts only on frontend; backend scripts only on plugin settings screen.
				return ( in_array( 'frontend', $scope, true ) && ! is_admin() )
					|| ( in_array( 'backend', $scope, true ) && $is_algolia_admin_screen );
			}
		);

		// Enqueue scripts.
		foreach ( $scripts as $script ) {
			wp_enqueue_script( $script['handle'], $script['src'], helper\get_array_value( $script, 'deps', array() ), helper\get_array_value( $script, 'version', \wlc_algolia\WLC_Algolia::instance()->get_version() ), helper\get_array_value( $script, 'in_footer', true ) );

			// Add script data.
			if ( isset( $script['data'] ) ) {
				wp_localize_script( $script['handle'], lcfirst( str_replace( ' ', '', ucwords( str_replace( '-', ' ', $script['handle'] ) ) ) ) . 'Data', $script['data'] );
			}
		}
	}
}
