<?php
namespace PowerpackElements\Modules\AdvancedMenu;

use PowerpackElements\Base\Module_Base;
use PowerpackElements\Classes\PP_Helper;

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

class Module extends Module_Base {

	/**
	 * Breakpoints which are not offered as the menu's dropdown breakpoint.
	 *
	 * The dropdown menu is meant for smaller devices, and the widescreen breakpoint
	 * is a min-width breakpoint which the toggle media queries cannot use.
	 *
	 * @since 3.0.0
	 * @var array
	 */
	const EXCLUDED_BREAKPOINTS = [ 'laptop', 'widescreen' ];

	public function __construct() {
		parent::__construct();

		add_action( 'elementor/frontend/after_register_styles', [ $this, 'register_styles' ] );
	}

	public function get_name() {
		return 'pp-advanced-menu';
	}

	public function get_widgets() {
		return [
			'Advanced_Menu',
		];
	}

	/**
	 * Get dropdown breakpoints.
	 *
	 * Returns the active breakpoints at which the menu can be switched to the
	 * dropdown (toggle) menu. Custom breakpoints added through Elementor's
	 * Additional Breakpoints feature are included.
	 *
	 * @since 3.0.0
	 *
	 * @return \Elementor\Core\Breakpoints\Breakpoint[] Breakpoint instances, keyed by breakpoint name.
	 */
	public static function get_dropdown_breakpoints() {
		$breakpoints = PP_Helper::elementor()->breakpoints->get_active_breakpoints();

		return array_diff_key( $breakpoints, array_flip( self::EXCLUDED_BREAKPOINTS ) );
	}

	/**
	 * Register styles.
	 *
	 * @return void
	 */
	public function register_styles() {
		wp_register_style(
			'widget-pp-advanced-menu',
			$this->get_css_assets_url( 'widget-advanced-menu', null, true, true ),
			[],
			POWERPACK_ELEMENTS_VER
		);

		$breakpoints_css = $this->get_dropdown_breakpoints_css();

		if ( $breakpoints_css ) {
			wp_add_inline_style( 'widget-pp-advanced-menu', $breakpoints_css );
		}
	}

	/**
	 * Get dropdown breakpoints CSS.
	 *
	 * Builds the media queries which switch between the main menu and the toggle
	 * (dropdown) menu. Breakpoint values are user configurable, so these queries are
	 * generated from the active breakpoints instead of being hardcoded in the stylesheet.
	 *
	 * @since 3.0.0
	 *
	 * @return string
	 */
	private function get_dropdown_breakpoints_css() {
		$css = '';

		foreach ( self::get_dropdown_breakpoints() as $device => $breakpoint ) {
			$value    = (int) $breakpoint->get_value();
			$selector = '.pp-advanced-menu--dropdown-' . $device;

			$css .= sprintf(
				'@media (max-width:%1$dpx){%2$s .pp-advanced-menu--main{display:none}%2$s .pp-menu-toggle{display:-webkit-box;display:-ms-flexbox;display:flex}}',
				$value,
				$selector
			);

			$css .= sprintf(
				'@media (min-width:%1$dpx){%2$s .pp-menu-toggle:not(.pp-menu-toggle-on-all){display:none}}',
				$value + 1,
				$selector
			);
		}

		return $css;
	}
}
