<?php
/**
 * Elementor integration bootstrap.
 *
 * @package Ugcify\Elementor
 */

namespace Ugcify\Elementor;

use Ugcify\Elementor\Widgets\UGCGalleryWidget;
use Ugcify\Helpers\FeatureGate;

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

/**
 * Class Integration
 */
class Integration {
	/**
	 * Editor helper script handle.
	 *
	 * @var string
	 */
	private $editor_script_handle = 'ugcify-elementor-editor';

	/**
	 * Constructor.
	 */
	public function __construct() {
		if ( did_action( 'elementor/loaded' ) ) {
			$this->init_hooks();
			return;
		}

		add_action( 'elementor/loaded', array( $this, 'init_hooks' ) );
	}

	/**
	 * Initialize Elementor-specific hooks.
	 *
	 * @return void
	 */
	public function init_hooks() {
		add_action( 'elementor/widgets/register', array( $this, 'register_widgets' ) );
		add_action( 'elementor/editor/after_enqueue_scripts', array( $this, 'enqueue_editor_assets' ) );
	}

	/**
	 * Register Elementor widgets.
	 *
	 * @param \Elementor\Widgets_Manager $widgets_manager Widgets manager.
	 * @return void
	 */
	public function register_widgets( $widgets_manager ) {
		if ( ! class_exists( '\Elementor\Widget_Base' ) ) {
			return;
		}

		require_once UGCIFY_PATH . 'includes/Elementor/Widgets/UGCGalleryWidget.php';
		$widgets_manager->register( new UGCGalleryWidget() );
	}

	/**
	 * Enqueue Elementor editor helper assets.
	 *
	 * @return void
	 */
	public function enqueue_editor_assets() {
		$script_file = UGCIFY_PATH . 'assets/elementor/editor.js';
		$script_url  = UGCIFY_URL . 'assets/elementor/editor.js';

		if ( ! file_exists( $script_file ) ) {
			$script_file = UGCIFY_PATH . 'src/elementor/editor.js';
			$script_url  = UGCIFY_URL . 'src/elementor/editor.js';
		}

		if ( ! file_exists( $script_file ) ) {
			return;
		}

		if ( ! class_exists( UGCGalleryWidget::class ) ) {
			require_once UGCIFY_PATH . 'includes/Elementor/Widgets/UGCGalleryWidget.php';
		}

		wp_enqueue_script(
			$this->editor_script_handle,
			$script_url,
			array( 'jquery', 'elementor-editor' ),
			(string) filemtime( $script_file ),
			true
		);

		wp_localize_script(
			$this->editor_script_handle,
			'ugcCommerceElementor',
			array(
				'defaults'    => UGCGalleryWidget::get_default_settings(),
				'features'    => array(
					'block_studio_advanced' => FeatureGate::is_enabled( 'block_studio_advanced' ),
					'block_studio_reels'    => FeatureGate::is_enabled( 'block_studio_reels' ),
					'block_studio_gallery'  => FeatureGate::is_enabled( 'block_studio_gallery' ),
				),
				'isProActive' => (bool) apply_filters( 'ugcify_is_pro_active', false ),
				'licensePlan' => (string) apply_filters( 'ugcify_license_plan', '' ),
				'upgradeUrl'  => esc_url( apply_filters( 'ugcify_upgrade_url', admin_url( 'admin.php?page=ugcify#/license' ) ) ),
				'i18n'        => array(
					'resetSuccess' => __( 'Settings reset to defaults.', 'ugcify' ),
				),
			)
		);
	}
}
