<?php
/**
 * AR Display
 * https://augmentedrealityplugins.com
**/
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
// Create WordPress Widget
class AR_Widget extends WP_Widget {

    public function __construct() {
        add_action('init', array($this, 'register_widget'));
    }

    public function register_widget() {
        parent::__construct(
            'ar_widget',
            __('AR Display Widget', 'ar-for-wordpress'),
            array('description' => __('Displays AR model using shortcode.', 'ar-for-wordpress'))
        );

        add_action('widgets_init', function() {
            register_widget('AR_Widget');
        });
    }

    public function widget($args, $instance) {
        echo $args['before_widget'];
        if (!empty($instance['title'])) {
            echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title'];
        }
        echo do_shortcode('[ar-display]');
        echo $args['after_widget'];
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : '';
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Title:', 'ar-for-wordpress'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>">
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }
}

//Elementor Widget
function register_ar_elementor_widget( ) {
    include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
    if (is_plugin_active( 'elementor/elementor.php' )) {
        require_once( __DIR__ . '/ar-elementor-widget.php' );
        \Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \Elementor_ar_for_wordpress_Widget() );
    }
}
add_action( 'elementor/widgets/register', 'register_ar_elementor_widget' );