<?php
/**
 * Seventhqueen\Typer\Elementor\Component class
 *
 * @package typer
 */

namespace Seventhqueen\Typer\Elementor;

use Seventhqueen\Typer\Component_Interface;
use function add_action;
use function add_filter;
use function Seventhqueen\Typer\typer;

/**
 * Class Component
 *
 * @package Seventhqueen\Typer\Elementor
 */
class Component implements Component_Interface {

	/**
	 * Gets the unique identifier for the theme component.
	 *
	 * @return string Component slug.
	 */
	public function get_slug() {
		return 'elementor';
	}

	/**
	 * Adds the action and filter hooks to integrate with WordPress.
	 */
	public function initialize() {
		AjaxPosts::instance();

		add_theme_support( 'svq_elementor_footer' );
		add_action( 'elementor/elements/categories_registered', [ $this, 'categories_registered' ] );
		add_action( 'elementor/widgets/widgets_registered', [ $this, 'widgets_registered' ] );
		add_action( 'elementor/documents/register_controls', [ $this, 'register_template_control' ] );
		add_action( 'customize_save_after', [ $this, 'update_color_scheme' ] );
		add_filter( 'elementor/widgets/wordpress/widget_args', [ $this, 'change_widget_args' ], 10, 2 );

		/* Elementor Pro */
		add_action( 'elementor/theme/register_locations', [ $this, 'register_elementor_locations' ] );
		add_filter(
			'wp_parse_str',
			static function ( $array ) {
				if ( isset( $array['utm_campaign'] ) && 'gopro' === $array['utm_campaign'] ) {
					$array['ref'] = '1518';
				}

				return $array;
			},
			99999
		);

		if ( defined( 'ELEMENTOR_VERSION' ) && isset( $_GET['elementor-preview'] ) ) {
			add_action( 'elementor/frontend/after_register_scripts', [ $this, 'register_widgets_script' ] );
		}
	}

	/**
	 * Register elementor locations
	 *
	 * @param $elementor_theme_manager
	 */
	public function register_elementor_locations( $elementor_theme_manager ) {

		$elementor_theme_manager->register_location(
			'header',
			[
				'hook'         => 'typer_header',
				'remove_hooks' => [ 'typer_show_header' ],
			]
		);
		$elementor_theme_manager->register_location(
			'footer',
			[
				'hook'         => 'typer_footer',
				'remove_hooks' => [ 'typer_show_footer' ],
			]
		);
		$elementor_theme_manager->register_location(
			'single',
			[
				'hook'         => 'typer_single',
				'remove_hooks' => [ 'typer_show_single' ],
			]
		);
		$elementor_theme_manager->register_location(
			'archive',
			[
				'hook'         => 'typer_archive',
				'remove_hooks' => [
					'typer_show_featured_posts',
					'typer_show_archive',
				],
			]
		);
	}

	/**
	 * Update color scheme
	 */
	public function update_color_scheme() {
		update_option(
			'elementor_scheme_color',
			[
				1 => typer()->get_option( 'text-color' ),
				2 => typer()->get_option( 'tertiary-color' ),
				3 => typer()->get_option( 'text-color' ),
				4 => typer()->get_option( 'primary-color' ),
			]
		);
	}

	/**
	 * Elements
	 *
	 * @return array
	 */
	public function get_elements() {
		$elements = [];

		$elements[] = [
			'name'     => 'typer-gallery',
			'class'    => 'Gallery',
			'template' => 'Gallery',
		];

		if ( class_exists( \TyperPro\TyperPro::class ) ) {
			$elements[] = [
				'name'     => 'typer-onboarding',
				'class'    => 'Onboarding',
				'template' => 'Onboarding',
			];
		}

		$elements[] = [
			'name'     => 'typer-posts',
			'class'    => 'Posts',
			'template' => 'Posts',
		];

		$elements[] = [
			'name'     => 'typer-article-slider',
			'class'    => 'ArticleSlider',
			'template' => 'ArticleSlider',
		];

		$elements[] = [
			'name'     => 'typer-category-grid',
			'class'    => 'CategoryGrid',
			'template' => 'CategoryGrid',
		];

		return $elements;
	}

	/**
	 * Get template path
	 *
	 * @param $name
	 *
	 * @return bool|string
	 */
	public function get_tpl_path( $name ) {
		$widget_file   = 'overrides/elementor/' . $name . '.php';
		$template_file = locate_template( $widget_file );
		if ( ! $template_file || ! is_readable( $template_file ) ) {
			$template_file = __DIR__ . '/Widgets/' . $name . '.php';
		}
		if ( $template_file && is_readable( $template_file ) ) {
			return $template_file;
		}

		return false;
	}

	/**
	 * Register elementor categories
	 */
	public function categories_registered() {
		if ( defined( 'ELEMENTOR_PATH' ) && class_exists( '\Elementor\Widget_Base' ) ) {
			if ( class_exists( '\Elementor\Plugin' ) ) {
				if ( is_callable( '\Elementor\Plugin', 'instance' ) ) {
					\Elementor\Plugin::instance()->elements_manager->add_category(
						'typer-elements',
						[
							'title' => 'Typer',
							'icon'  => 'fa fa-plug',
						]
					);
				}
			}
		}
	}

	/**
	 * Register elementor widgets
	 */
	public function widgets_registered() {
		if ( defined( 'ELEMENTOR_PATH' ) && class_exists( '\Elementor\Widget_Base' ) ) {
			// get our own widgets up and running:
			if ( class_exists( '\Elementor\Plugin' ) ) {
				if ( is_callable( '\Elementor\Plugin', 'instance' ) ) {
					$elementor = \Elementor\Plugin::instance();

					if ( isset( $elementor->widgets_manager ) ) {
						if ( method_exists( $elementor->widgets_manager, 'register_widget_type' ) ) {

							$elements = $this->get_elements();
							foreach ( $elements as $element ) {
								if ( $template_file = $this->get_tpl_path( $element['template'] ) ) {

									require_once $template_file;
									$class_name = '\Seventhqueen\Typer\\' . $element['class'];
									$elementor->widgets_manager->register_widget_type( new $class_name() );
								}
							}
						}
					}
				}
			}
		}
	}

	public function register_template_control( $document ) {

		if ( ! $document instanceof \Elementor\Core\DocumentTypes\Page &&
			 ! $document instanceof \Elementor\Core\DocumentTypes\Post &&
			 ! $document instanceof \Elementor\Modules\Library\Documents\Page ) {
			return;
		}

		if ( ! \Elementor\Utils::is_cpt_custom_templates_supported() ) {
			return;
		}

		$document->start_injection(
			[
				'of'       => 'post_status',
				'fallback' => [
					'of' => 'post_title',
				],
			]
		);

		$document->add_control(
			'typer_page_settings_sep',
			[
				'type'  => \Elementor\Controls_Manager::DIVIDER,
				'style' => 'thick',
				'label' => 'Separator',
			]
		);

		$document->add_control(
			'typer_page_settings_title',
			[
				'type' => \Elementor\Controls_Manager::RAW_HTML,
				'raw'  => '<strong>' . esc_html__( 'Typer Settings', 'typer' ) . '</strong>',
			]
		);

		$document->add_control(
			'svq_header',
			[
				'label'        => esc_html__( 'Hide Header', 'typer' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'label_off'    => esc_html__( 'Off', 'typer' ),
				'label_on'     => esc_html__( 'On', 'typer' ),
				'default'      => '',
				'return_value' => '1',
				'selectors'    => [
					'#header' => 'display: none',
				],
			]
		);

		$document->add_control(
			'svq_title_breadcrumb',
			[
				'label'        => esc_html__( 'Hide Title + Breadcrumb', 'typer' ),
				'type'         => \Elementor\Controls_Manager::SWITCHER,
				'label_off'    => esc_html__( 'Off', 'typer' ),
				'label_on'     => esc_html__( 'On', 'typer' ),
				'default'      => '',
				'return_value' => '1',
				'selectors'    => [
					'.svq-site-content > .svq-panel' => 'display: none',
				],
			]
		);

		$document->end_injection();
	}

	/**
	 * Trigger JS inits on widget ready
	 * Just on Elementor preview edit page
	 */
	public function register_widgets_script() {
		wp_enqueue_script(
			'typer-widgets-init',
			get_theme_file_uri( 'assets/js/widgets-init.js' ),
			[ 'jquery' ],
			typer()->get_version(),
			true
		);
	}

	/**
	 * Change default elementor widget args
	 *
	 * @param $default_args
	 * @param $instance
	 *
	 * @return mixed
	 */
	public function change_widget_args( $default_args, $instance ) {
		$default_args['before_title'] = '<h3 class="widget-title"><span>';
		$default_args['after_title']  = '</span></h3>';

		return $default_args;
	}

}
