<?php
/**
 * Plugin Name: Elementor Addon
 * Description: Custom Elementor widgets for Hashtalk.
 * Version:     1.0.0
 * Author:      Elementor Developer
 * Text Domain: elementor-addon
 *
 * Requires Plugins: elementor
 */

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

define( 'ELEMENTOR_ADDON_VERSION', '1.0.0' );
define( 'ELEMENTOR_ADDON_PATH', plugin_dir_path( __FILE__ ) );
define( 'ELEMENTOR_ADDON_URL', plugin_dir_url( __FILE__ ) );

/**
 * Register custom Elementor category.
 */
function elementor_addon_register_widget_category( $elements_manager ) {
	$elements_manager->add_category(
		'hashtalk',
		[
			'title' => esc_html__( 'Hashtalk', 'elementor-addon' ),
			'icon'  => 'fa fa-plug',
		]
	);
}
add_action( 'elementor/elements/categories_registered', 'elementor_addon_register_widget_category' );

/**
 * Register widget files.
 */
function register_elementor_addon_widgets( $widgets_manager ) {
	require_once ELEMENTOR_ADDON_PATH . 'widgets/3d-element.php';

	$widgets_manager->register( new \Elementor_3d_Element() );
}
add_action( 'elementor/widgets/register', 'register_elementor_addon_widgets' );

/**
 * Register frontend assets only. Elementor will enqueue them only when the widget is used.
 */
function elementor_addon_register_assets() {
	$css_path = ELEMENTOR_ADDON_PATH . 'assets/css/main.css';
	$js_path  = ELEMENTOR_ADDON_PATH . 'assets/js/main.js';

	$css_ver = file_exists( $css_path ) ? filemtime( $css_path ) : ELEMENTOR_ADDON_VERSION;
	$js_ver  = file_exists( $js_path ) ? filemtime( $js_path ) : ELEMENTOR_ADDON_VERSION;

	if ( ! wp_script_is( 'three-js', 'registered' ) ) {
		wp_register_script(
			'three-js',
			'https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js',
			[],
			'0.128.0',
			true
		);
	}

	if ( ! wp_script_is( 'three-gltfloader', 'registered' ) ) {
		wp_register_script(
			'three-gltfloader',
			'https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/GLTFLoader.js',
			[ 'three-js' ],
			'0.128.0',
			true
		);
	}

	wp_register_style(
		'elementor-addon-main-css',
		ELEMENTOR_ADDON_URL . 'assets/css/main.css',
		[],
		$css_ver
	);

	wp_register_script(
		'elementor-addon-main-js',
		ELEMENTOR_ADDON_URL . 'assets/js/main.js',
		[ 'three-js', 'three-gltfloader' ],
		$js_ver,
		true
	);
}
add_action( 'wp_enqueue_scripts', 'elementor_addon_register_assets' );
add_action( 'elementor/frontend/after_register_scripts', 'elementor_addon_register_assets' );
add_action( 'elementor/frontend/after_register_styles', 'elementor_addon_register_assets' );
