<?php
/**
 * Elementor integration.
 *
 * @package Vareon_Calculator_Suite_Lite
 */

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

if ( ! function_exists( 'vareoncalc_lite_is_elementor_loaded' ) ) {
	/**
	 * Check whether Elementor is active and loaded.
	 *
	 * @return bool
	 */
	function vareoncalc_lite_is_elementor_loaded() {
		return did_action( 'elementor/loaded' ) && class_exists( '\\Elementor\\Widget_Base' ) && class_exists( '\\Elementor\\Controls_Manager' );
	}
}

if ( ! function_exists( 'vareoncalc_lite_get_elementor_widget_instance' ) ) {
	/**
	 * Build the Elementor widget instance on demand.
	 *
	 * @return VareonCalc_Lite_Elementor_Widget|null
	 */
	function vareoncalc_lite_get_elementor_widget_instance() {
		if ( ! vareoncalc_lite_is_elementor_loaded() ) {
			return null;
		}

		if ( ! class_exists( 'VareonCalc_Lite_Elementor_Widget' ) ) {
			require_once VAREONCALC_DIR . 'inc/class-vareoncalc-lite-elementor-widget.php';
		}

		return new VareonCalc_Lite_Elementor_Widget();
	}
}

if ( ! function_exists( 'vareoncalc_lite_get_elementor_calculator_options' ) ) {
	/**
	 * Build Elementor select options from the existing calculator library.
	 *
	 * @return array
	 */
	function vareoncalc_lite_get_elementor_calculator_options() {
		$options = array();
		$library = function_exists( 'vareoncalc_get_calculator_library' ) ? vareoncalc_get_calculator_library() : array();

		if ( ! empty( $library ) ) {
			foreach ( $library as $type => $data ) {
				if ( ! vareoncalc_is_calculator_available( $type ) ) {
					continue;
				}

				$options[ $type ] = $data['title'] ?? ucwords( str_replace( '-', ' ', (string) $type ) );
			}
		}

		if ( empty( $options ) ) {
			foreach ( vareoncalc_get_available_calculators() as $type ) {
				$options[ $type ] = ucwords( str_replace( '-', ' ', (string) $type ) );
			}
		}

		return $options;
	}
}

if ( ! function_exists( 'vareoncalc_lite_build_elementor_shortcode' ) ) {
	/**
	 * Convert Elementor settings into the plugin shortcode.
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string
	 */
	function vareoncalc_lite_build_elementor_shortcode( array $atts ) {
		$parts = array();

		foreach ( $atts as $key => $value ) {
			if ( '' === $value || null === $value ) {
				continue;
			}

			$parts[] = sprintf( '%s="%s"', sanitize_key( (string) $key ), esc_attr( (string) $value ) );
		}

		return '[vareon ' . implode( ' ', $parts ) . ']';
	}
}

add_action(
	'elementor/widgets/register',
	function ( $widgets_manager ) {
		$widget = vareoncalc_lite_get_elementor_widget_instance();
		if ( null === $widget ) {
			return;
		}

		$widgets_manager->register( $widget );
	}
);
