<?php

namespace HugeAddons\Classes;

class WidgetManager {
    private $widgets = [];
    private $widgets_flat = [];
    private $enabled = [];

    public function __construct() {
        $this->load_widgets();
        $this->load_enabled_widgets();
        $this->register_widget_category();
        $this->init_hooks();
    }

    private function load_widgets() {
        $json = file_get_contents(THHA_WIDGETS_JSON);
        $all_widgets = json_decode($json, true);
        foreach ($all_widgets as $widgetCategory => $widgets) {
            foreach ($widgets as $widget) {
                $this->widgets[$widgetCategory][$widget['class']] = $widget;
                $this->widgets_flat[$widget['class']] = $widget;
            }
        }
    }

    private function load_enabled_widgets() {
        $enabled = get_option('thha_enabled_widgets', null);

        if ( is_null($enabled) ) {
            $enabled = [
                0 => 'HugeAdvancedIconBoxWidget',
                1 => 'HugeFlipBoxWidget',
                2 => 'HugePostGridWidget',
                3 => 'HugeAdvancedImageGalleryWidget'
            ];
            update_option('thha_enabled_widgets', $enabled);
        } else {
            // Migrate old class names to new ones
            $mapping = [
                'THHA_Huge_Advanced_Icon_Box_Widget' => 'HugeAdvancedIconBoxWidget',
                'THHA_Huge_Flip_Box_Widget' => 'HugeFlipBoxWidget',
                'THHA_Huge_Post_Grid_Widget' => 'HugePostGridWidget',
                'THHA_Huge_Advanced_Image_Gallery_Widget' => 'HugeAdvancedImageGalleryWidget',
                // Add more mappings here for other renamed widgets
            ];
            $updated = false;
            foreach ($enabled as &$widget) {
                if (isset($mapping[$widget])) {
                    $widget = $mapping[$widget];
                    $updated = true;
                }
            }
            if ($updated) {
                update_option('thha_enabled_widgets', $enabled);
            }
        }
        $this->enabled = $enabled;
    }

    public function get_all_widgets() {
        return $this->widgets;
    }

    public function get_enabled_widgets() {
        return $this->enabled;
    }

    public function save_enabled_widgets($enabled) {
        $this->enabled = $enabled;
        update_option('thha_enabled_widgets', $enabled);
    }

    private function init_hooks() {
        add_action('wp_ajax_thha_get_widgets', [$this, 'ajax_get_widgets']);
        // The frontend sends 'thha_save_addons_ajax', so we hook it here.
        add_action('wp_ajax_thha_save_addons_ajax', [$this, 'ajax_save_widgets']);
    }


    private function register_widget_category() {
        add_action( 'elementor/elements/categories_registered', function ( $elements_manager ) {
            $elements_manager->add_category(
                'thha-addons-category',
                [
                    'title' => __( 'Huge Addons', 'huge-addons-for-elementor' ),
                    'icon'  => 'fa fa-plug',
                ]
            );
        } );
    }

    
    public function register_widgets($widgets_manager) {
        
        foreach ($this->enabled as $widget_key) {
            if($this->widgets_flat[$widget_key]['status'] !== 'available') continue;
            if (isset($this->widgets_flat[$widget_key])) {
                $filepath = THHA_PLUGIN_PATH .'/includes/widgets/' . $this->widgets_flat[$widget_key]['class'] . '.php' ;
                require_once($filepath );
                $class_name = $this->widgets_flat[$widget_key]['mainClass'];
                $widgets_manager->register( new $class_name() );
            }
        }
    }

    public function ajax_get_widgets() {
        $nonce_valid = check_ajax_referer( 'thha_settings_nonce', 'nonce', false );
        if ( ! $nonce_valid ) {
            wp_send_json_error( 'Invalid Nonce', 403 );
        }

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Insufficient Permission', 403 );
        }

        $all_widgets = $this->get_all_widgets();
        $enabled = $this->get_enabled_widgets();
        $widgets = ['all' => $all_widgets, 'enabled' =>$enabled ];
        wp_send_json_success($widgets);
    }

    public function ajax_save_widgets() {
        check_ajax_referer('thha_save_nonce', '_wpnonce');

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Insufficient Permission', 403 );
        }

		$enabled = isset($_POST['enabled_widgets']) ? array_map('sanitize_text_field', wp_unslash($_POST['enabled_widgets'])) : [];
        $this->save_enabled_widgets($enabled);

        wp_send_json_success(['message' => 'Settings saved successfully.']);
    }

    
}