<?php

/**
 * Admin Settings Page
 * 
 * @package Softech_Addons_for_Elementor
 * @since 1.0.0
 */

namespace Softech_Addons_for_Elementor\Includes;

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

class SITS_Elementor_Addons_Settings
{
    private $option_name = 'sits_elementor_addons_options';
    private $option_group = 'sits_elementor_addons_options_group';
    private $page_slug = 'softech-addons-for-elementor';
    private $widgets_option = 'sits_elementor_addons_disabled_widgets';
    
    public function __construct()
    {
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        add_action('wp_ajax_sits_toggle_widget', [$this, 'ajax_toggle_widget']);
        add_action('wp_ajax_sits_toggle_all_widgets', [$this, 'ajax_toggle_all_widgets']);
        add_action('wp_ajax_sits_load_tab', [$this, 'ajax_load_tab']);
        // Point 3: Clear plugin cache via AJAX.
        add_action('wp_ajax_sits_clear_plugin_cache', [$this, 'ajax_clear_plugin_cache']);
        
    }

   public function add_admin_menu()
{
    add_menu_page(
        esc_html__('Softech Addons', 'softech-addons-for-elementor'),
        esc_html__('Softech Addons', 'softech-addons-for-elementor'),
        'manage_options',
        $this->page_slug,
        [$this, 'render_settings_page'],
        'dashicons-screenoptions',
        59
    );
    
    
}


    public function register_settings()
    {
        register_setting(
            $this->option_group,
            $this->option_name,
            [
                'sanitize_callback' => [$this, 'sanitize_options'],
                'default' => $this->get_default_options(),
            ]
        );

        register_setting(
            $this->option_group,
            $this->widgets_option,
            [
                'sanitize_callback' => [$this, 'sanitize_widgets'],
                'default' => [],
            ]
        );

       

        // GSAP Global Settings Section
        add_settings_section(
            'sits_elementor_addons_gsap_section',
            esc_html__('GSAP Global Settings', 'softech-addons-for-elementor'),
            null,
            $this->page_slug
        );

        add_settings_field(
            'gsap_global_split_enable',
            esc_html__('Enable Global Split Text', 'softech-addons-for-elementor'),
            [$this, 'render_gsap_global_split_enable_field'],
            $this->page_slug,
            'sits_elementor_addons_gsap_section'
        );

        add_settings_field(
            'gsap_global_split_class',
            esc_html__('Global Split Text Class', 'softech-addons-for-elementor'),
            [$this, 'render_gsap_global_split_class_field'],
            $this->page_slug,
            'sits_elementor_addons_gsap_section'
        );

        add_settings_field(
            'gsap_global_split_type',
            esc_html__('Global Split Type', 'softech-addons-for-elementor'),
            [$this, 'render_gsap_global_split_type_field'],
            $this->page_slug,
            'sits_elementor_addons_gsap_section'
        );
        add_settings_field(
            'gsap_global_split_animation',
            esc_html__( 'Global Split Animation Style', 'softech-addons-for-elementor' ),
            [ $this, 'render_gsap_global_split_animation_field' ],
            $this->page_slug,
            'sits_elementor_addons_gsap_section'
        );

        add_settings_field(
            'gsap_global_split_stagger',
            esc_html__('Global Split Stagger (s)', 'softech-addons-for-elementor'),
            [$this, 'render_gsap_global_split_stagger_field'],
            $this->page_slug,
            'sits_elementor_addons_gsap_section'
        );

        add_settings_field(
            'gsap_global_split_line_stagger',
            esc_html__('Global Line Stagger (s)', 'softech-addons-for-elementor'),
            [$this, 'render_gsap_global_split_line_stagger_field'],
            $this->page_slug,
            'sits_elementor_addons_gsap_section'
        );
        add_settings_field(
            'gsap_global_split_scroll_start',
            esc_html__( 'Global Trigger Point (%)', 'softech-addons-for-elementor' ),
            [ $this, 'render_gsap_global_split_scroll_start_field' ],
            $this->page_slug,
            'sits_elementor_addons_gsap_section'
        );
    }
    
    public function render_gsap_global_split_animation_field() {
    $options = get_option( $this->option_name, $this->get_default_options() );
    $value   = $options['gsap_global_split_animation'] ?? 'slideUp';
    $choices = [
        'slideUp'   => 'Slide Up (default)',
        'fadeIn'    => 'Fade In',
        'rotateIn'  => 'Rotate In (3D)',
        'scaleIn'   => 'Scale In',
        'blurIn'    => 'Blur In',
        'slideDown' => 'Slide Down',
        'flipIn'    => 'Flip In (X-axis)',
        'waveIn'    => 'Wave (chars only)',
    ];
    printf( '<select name="%s[gsap_global_split_animation]">', esc_attr( $this->option_name ) );
    foreach ( $choices as $key => $label ) {
        printf( '<option value="%s" %s>%s</option>', esc_attr($key), selected($value,$key,false), esc_html($label) );
    }
    echo '</select><p class="description">' . esc_html__('Animation style for split text units.','softech-addons-for-elementor') . '</p>';
}
    public function render_gsap_global_split_scroll_start_field() {
        $options = get_option( $this->option_name, $this->get_default_options() );
        $value   = isset( $options['gsap_global_split_scroll_start'] ) ? intval( $options['gsap_global_split_scroll_start'] ) : 100;
        printf(
            '<input type="number" name="%s[gsap_global_split_scroll_start]" value="%d" min="0" max="100" step="5" class="regular-text" />',
            esc_attr( $this->option_name ), absint( $value )
        );
        echo '<p class="description">' . esc_html__( '100 = triggers as element enters bottom of viewport. Lower = triggers earlier.', 'softech-addons-for-elementor' ) . '</p>';
    }
    public function render_slider_speed_field()
    {
        $options = get_option($this->option_name, $this->get_default_options());
        $value = isset($options['loop_slider_speed']) ? absint($options['loop_slider_speed']) : 400;

        printf(
            '<input type="number" name="%s[loop_slider_speed]" value="%d" min="100" max="5000" step="50" class="regular-text" />',
            esc_attr($this->option_name),
            esc_attr($value)
        );
        echo '<p class="description">' . esc_html__('Set the default transition speed for sliders (100-5000ms)', 'softech-addons-for-elementor') . '</p>';
    }

    public function render_accordion_height_field()
    {
        $options = get_option($this->option_name, $this->get_default_options());
        $value = isset($options['accordion_height']) ? absint($options['accordion_height']) : 400;

        printf(
            '<input type="number" name="%s[accordion_height]" value="%d" min="200" max="1000" step="10" class="regular-text" />',
            esc_attr($this->option_name),
            esc_attr($value)
        );
        echo '<p class="description">' . esc_html__('Set the default height for image accordions (200-1000px)', 'softech-addons-for-elementor') . '</p>';
    }
    
    public function render_gsap_global_split_enable_field()
    {
        $options = get_option($this->option_name, $this->get_default_options());
        $value = isset($options['gsap_global_split_enable']) ? $options['gsap_global_split_enable'] : '';

        printf(
            '<input type="checkbox" name="%s[gsap_global_split_enable]" value="yes" %s />',
            esc_attr($this->option_name),
            checked($value, 'yes', false)
        );
        echo '<p class="description">' . esc_html__('Enable global split text animation for elements with the specified class.', 'softech-addons-for-elementor') . '</p>';
    }

    public function render_gsap_global_split_class_field()
    {
        $options = get_option($this->option_name, $this->get_default_options());
        $value = isset($options['gsap_global_split_class']) ? $options['gsap_global_split_class'] : '.global-split-text';

        printf(
            '<input type="text" name="%s[gsap_global_split_class]" value="%s" class="regular-text" placeholder="ADD Selector" />',
            esc_attr($this->option_name),
            esc_attr($value)
        );
        echo '<p class="description">' . esc_html__( 'Comma-separated selectors. Each is automatically added to widgets in "Global" mode, and can be manually added to any HTML element. e.g. ', 'softech-addons-for-elementor' ) . '<code>.global-split-text, .my-heading, h1.hero</code></p>';
    }

    public function render_gsap_global_split_type_field()
    {
        $options = get_option($this->option_name, $this->get_default_options());
        $value = isset($options['gsap_global_split_type']) ? $options['gsap_global_split_type'] : 'chars';

        $options_array = [
            'chars' => esc_html__('Characters', 'softech-addons-for-elementor'),
            'words' => esc_html__('Words', 'softech-addons-for-elementor'),
        ];

        printf('<select name="%s[gsap_global_split_type]">', esc_attr($this->option_name));
        foreach ($options_array as $key => $label) {
            printf(
                '<option value="%s" %s>%s</option>',
                esc_attr($key),
                selected($value, $key, false),
                esc_html($label)
            );
        }
        echo '</select>';
        echo '<p class="description">' . esc_html__('Choose whether to split text into characters or words.', 'softech-addons-for-elementor') . '</p>';
    }

    public function render_gsap_global_split_stagger_field()
    {
        $options = get_option($this->option_name, $this->get_default_options());
        $value = isset($options['gsap_global_split_stagger']) ? floatval($options['gsap_global_split_stagger']) : 0.008;

        printf(
            '<input type="number" name="%s[gsap_global_split_stagger]" value="%s" min="0.001" max="0.1" step="0.001" class="regular-text" />',
            esc_attr($this->option_name),
            esc_attr($value)
        );
        echo '<p class="description">' . esc_html__('Stagger delay between each character/word animation (seconds).', 'softech-addons-for-elementor') . '</p>';
    }

    public function render_gsap_global_split_line_stagger_field()
    {
        $options = get_option($this->option_name, $this->get_default_options());
        $value = isset($options['gsap_global_split_line_stagger']) ? floatval($options['gsap_global_split_line_stagger']) : 0.08;

        printf(
            '<input type="number" name="%s[gsap_global_split_line_stagger]" value="%s" min="0" max="1" step="0.01" class="regular-text" />',
            esc_attr($this->option_name),
            esc_attr($value)
        );
        echo '<p class="description">' . esc_html__('Stagger delay between each line animation (seconds).', 'softech-addons-for-elementor') . '</p>';
    }
    
    public function sanitize_options($options)
    {
        if (!is_array($options)) {
            // Return existing options + defaults, don't lose data!
            $existing = get_option($this->option_name, []);
            return is_array($existing) ? $existing : $this->get_default_options();
        }

        // Get existing options to preserve fields not in current form submission
        $existing = get_option($this->option_name, []);
        if (!is_array($existing)) {
            $existing = [];
        }

        $sanitized = $existing; // Start with existing to preserve values

       

        // ===== GSAP Global Settings =====
        if (isset($options['gsap_global_split_enable'])) {
            $sanitized['gsap_global_split_enable'] = sanitize_text_field($options['gsap_global_split_enable']);
        }

        if (isset($options['gsap_global_split_class'])) {
            $sanitized['gsap_global_split_class'] = sanitize_text_field($options['gsap_global_split_class']);
        }

        if (isset($options['gsap_global_split_type'])) {
            $sanitized['gsap_global_split_type'] = sanitize_text_field($options['gsap_global_split_type']);
        }

        if (isset($options['gsap_global_split_stagger'])) {
            $stagger = floatval($options['gsap_global_split_stagger']);
            $sanitized['gsap_global_split_stagger'] = max(0.001, min(0.1, $stagger));
        }

        if (isset($options['gsap_global_split_line_stagger'])) {
            $line_stagger = floatval($options['gsap_global_split_line_stagger']);
            $sanitized['gsap_global_split_line_stagger'] = max(0, min(1, $line_stagger));
        }

        // ===== Payment Settings (from Payment Settings tab) =====
        if (isset($options['stripe_secret_key'])) {
            $sanitized['stripe_secret_key'] = sanitize_text_field($options['stripe_secret_key']);
        }

        if (isset($options['stripe_publishable_key'])) {
            $sanitized['stripe_publishable_key'] = sanitize_text_field($options['stripe_publishable_key']);
        }

        if (isset($options['stripe_webhook_secret'])) {
            $sanitized['stripe_webhook_secret'] = sanitize_text_field($options['stripe_webhook_secret']);
        }

        if (isset($options['stripe_currency'])) {
            $sanitized['stripe_currency'] = sanitize_text_field($options['stripe_currency']);
        }

        if (isset($options['stripe_success_url'])) {
            $sanitized['stripe_success_url'] = esc_url_raw($options['stripe_success_url']);
        }

        if (isset($options['stripe_cancel_url'])) {
            $sanitized['stripe_cancel_url'] = esc_url_raw($options['stripe_cancel_url']);
        }
        
        if ( isset( $options['gsap_global_split_animation'] ) ) {
            $allowed = [ 'slideUp','fadeIn','rotateIn','scaleIn','blurIn','slideDown','flipIn','waveIn' ];
            $sanitized['gsap_global_split_animation'] = in_array( $options['gsap_global_split_animation'], $allowed, true )
                ? $options['gsap_global_split_animation'] : 'slideUp';
        }
        if ( isset( $options['gsap_global_split_scroll_start'] ) ) {
            $sanitized['gsap_global_split_scroll_start'] = max( 0, min( 100, intval( $options['gsap_global_split_scroll_start'] ) ) );
        }

        return $sanitized;
    }

    public function sanitize_widgets($widgets)
    {
        if (!is_array($widgets)) {
            return [];
        }
        return array_map('sanitize_text_field', $widgets);
    }

    public function render_settings_page()
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'softech-addons-for-elementor'));
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'widgets';
        $is_pro_active = \sits_ea_is_pro_active();

        $allowed_tabs = $is_pro_active ? ['widgets', 'settings', 'theme-builder', 'payment-settings'] : ['widgets', 'settings', 'theme-builder', 'payment-settings', 'go-pro'];

        if (!in_array($active_tab, $allowed_tabs, true)) {
            $active_tab = 'widgets';
        }
?>
        <div class="wrap sits-admin-wrap">
            <div class="sits-admin-header">
                <div class="sits-header-left">
                    <h1 class="sits-main-title">
                        <span class="sits-logo-icon">
                            <svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <rect width="32" height="32" rx="6" fill="#0f3d4a" />
                                <path d="M8 12h16M8 16h16M8 20h10" stroke="white" stroke-width="2" stroke-linecap="round" />
                            </svg>
                        </span>
                        <?php esc_html_e('Softech Addons', 'softech-addons-for-elementor'); ?>
                        <?php if ($is_pro_active): ?>
                            <div class="sits-header-right">
                                <span class="sits-pro-badge-header">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M8 1l2.5 5 5.5.5-4 4 1 5.5L8 13l-5 3 1-5.5-4-4 5.5-.5L8 1z" fill="currentColor" />
                                    </svg>
                                    <?php esc_html_e('PRO', 'softech-addons-for-elementor'); ?>
                                </span>
                            </div>
                        <?php endif; ?>
                    </h1>
                    <p class="sits-subtitle"><?php esc_html_e('Where Elementor Meets Infinite Possibilities', 'softech-addons-for-elementor'); ?></p>
                </div>

            </div>

            <nav class="sits-nav-tabs">
    <a href="#" class="sits-nav-tab sits-tab-link <?php echo $active_tab === 'widgets' ? 'active' : ''; ?>" data-tab="widgets">
        <?php esc_html_e('Widgets', 'softech-addons-for-elementor'); ?>
    </a>
    <a href="#" class="sits-nav-tab sits-tab-link <?php echo $active_tab === 'settings' ? 'active' : ''; ?>" data-tab="settings">
        <?php esc_html_e('Settings', 'softech-addons-for-elementor'); ?>
    </a>
    <a href="<?php echo esc_url( admin_url( 'edit.php?post_type=' . \Softech_Addons_for_Elementor\Includes\SITS_Header_Footer_Builder::POST_TYPE ) ); ?>" class="sits-nav-tab sits-tab-link <?php echo $active_tab === 'theme-builder' ? 'active' : ''; ?>" data-tab="theme-builder" data-redirect-url="<?php echo esc_url( admin_url( 'edit.php?post_type=' . \Softech_Addons_for_Elementor\Includes\SITS_Header_Footer_Builder::POST_TYPE ) ); ?>">
        <?php esc_html_e('Theme Builder', 'softech-addons-for-elementor'); ?>
    </a>
    <a href="#" class="sits-nav-tab sits-tab-link <?php echo $active_tab === 'payment-settings' ? 'active' : ''; ?>" data-tab="payment-settings" data-subtab="general">
    <?php esc_html_e('Payment Settings', 'softech-addons-for-elementor'); ?>
    </a>
    <?php if (!$is_pro_active): ?>
        <a href="#" class="sits-nav-tab sits-nav-tab-pro sits-tab-link <?php echo $active_tab === 'go-pro' ? 'active' : ''; ?>" data-tab="go-pro">
            <?php esc_html_e('Go Pro', 'softech-addons-for-elementor'); ?>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M7 1l1.5 4.5L13 7l-4.5 1.5L7 13l-1.5-4.5L1 7l4.5-1.5L7 1z" fill="currentColor" />
            </svg>
        </a>
    <?php endif; ?>
</nav>

            <div class="sits-tab-content" id="sits-tab-content">
    <?php if ($active_tab === 'widgets'): ?>
        <?php $this->render_widgets_tab(); ?>
    <?php elseif ($active_tab === 'settings'): ?>
        <?php $this->render_settings_tab(); ?>
    <?php elseif ($active_tab === 'theme-builder'): ?>
        <?php $this->render_theme_builder_tab(); ?>
    <?php elseif ($active_tab === 'payment-settings'): ?>
    <?php 
         if (class_exists('Softech_Addons_for_Elementor\Includes\SITS_Elementor_Payment_Settings')) {
        $payment_settings = \Softech_Addons_for_Elementor\Includes\SITS_Elementor_Payment_Settings::instance();
        $payment_settings->render_payment_settings_tab();
        }
    ?>
    <?php elseif ($active_tab === 'go-pro' && !$is_pro_active): ?>
        <?php $this->render_pro_tab(); ?>

    <?php endif; ?>
</div>
        </div>
    <?php
    }

    private function render_widgets_tab()
{
    $is_pro_active = \sits_ea_is_pro_active();
    $can_pro_render = apply_filters('sits_elementor_addons_can_render_pro', false);
    $disabled_widgets = get_option($this->widgets_option, []);

    $all_widgets = $this->get_all_available_widgets();

    // Show locked widgets ONLY if Pro is not active AND Pro can't render (license never valid)
    if (!$is_pro_active && !$can_pro_render) {
        $pro_widgets_info = \sits_get_pro_widgets_info();
        
        $active_names = wp_list_pluck($all_widgets, 'name');
        
        foreach ($pro_widgets_info as $pro_widget) {
            if (!in_array($pro_widget['name'], $active_names, true)) {
                $all_widgets[] = $pro_widget;
            }
        }
    }
?>
    <div class="sits-widgets-container">
        <div class="sits-widgets-header">
            <div class="sits-widgets-search">
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <circle cx="8" cy="8" r="6" stroke="currentColor" stroke-width="2" />
                    <path d="M12.5 12.5L16 16" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
                </svg>
                <input type="text" id="sits-widget-search" placeholder="<?php esc_attr_e('Search Widgets...', 'softech-addons-for-elementor'); ?>">
            </div>
            <div class="sits-widgets-toggle">
                <label class="sits-toggle-label">
                    <span><?php esc_html_e('Toggle all Widgets', 'softech-addons-for-elementor'); ?></span>
                    <div class="sits-toggle-switch">
                        <input type="checkbox" id="sits-toggle-all" <?php checked(empty($disabled_widgets)); ?>>
                        <span class="sits-toggle-slider"></span>
                    </div>
                </label>
                <p class="sits-toggle-description"><?php esc_html_e('You can disable some widgets for faster page speed.', 'softech-addons-for-elementor'); ?></p>
            </div>
        </div>

        <?php if (!$this->is_elementor_active()): ?>
            <div class="notice notice-error">
                <p>
                    <strong><?php esc_html_e('Elementor', 'softech-addons-for-elementor'); ?></strong>
                    <?php esc_html_e('is not active. Cannot retrieve widgets.', 'softech-addons-for-elementor'); ?>
                </p>
            </div>
        <?php endif; ?>

        <div class="sits-widgets-grid">
            <?php if (!empty($all_widgets)): ?>
                <?php foreach ($all_widgets as $widget): ?>
                    <?php
                    $is_locked = isset($widget['is_locked']) && $widget['is_locked'];
                    $is_pro = isset($widget['is_pro']) && $widget['is_pro'];
                    $widget_title = isset($widget['title']) ? $widget['title'] : '';
                    $widget_name = isset($widget['name']) ? $widget['name'] : '';
                    $widget_description = isset($widget['description']) ? $widget['description'] : '';
                    $widget_categories = isset($widget['categories']) && is_array($widget['categories']) ? $widget['categories'] : [];
                    $is_disabled = in_array($widget_name, $disabled_widgets, true);
                    ?>
                    <div class="sits-widget-card <?php echo $is_locked ? 'sits-widget-locked' : ''; ?> <?php echo $is_disabled ? 'sits-widget-disabled' : ''; ?>" data-widget-name="<?php echo esc_attr($widget_name); ?>" data-widget-title="<?php echo esc_attr($widget_title); ?>">
                        <?php if ($is_locked): ?>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=' . $this->page_slug . '&tab=go-pro')); ?>" class="sits-pro-badge-link">
                                <div class="sits-pro-badge">
                                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M6 3V2m0 1v1m0-1h1m-1 0H5m3 3H4a1 1 0 00-1 1v3a1 1 0 001 1h4a1 1 0 001-1V7a1 1 0 00-1-1z" stroke="currentColor" stroke-linecap="round" />
                                    </svg>
                                    <span><?php esc_html_e('PRO', 'softech-addons-for-elementor'); ?></span>
                                </div>
                            </a>
                        <?php else: ?>
                            <div class="sits-widget-toggle">
                                <label class="sits-widget-switch">
                                    <input type="checkbox"
                                        class="sits-widget-checkbox"
                                        data-widget="<?php echo esc_attr($widget_name); ?>"
                                        <?php checked(!$is_disabled); ?>>
                                    <span class="sits-widget-slider"></span>
                                </label>
                            </div>
                        <?php endif; ?>

                        <div class="sits-widget-header">
                            
                            <h3><?php echo esc_html($widget_title); ?></h3>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="sits-widget-card sits-widget-empty">
                    <h3><?php esc_html_e('No SITS widgets found', 'softech-addons-for-elementor'); ?></h3>
                    <p><?php esc_html_e('Ensure Elementor is active and the SITS widgets are registered properly.', 'softech-addons-for-elementor'); ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>
<?php
}

   private function render_settings_tab()
{
    ?>
        <div class="sits-settings-container">
            <form method="post" action="options.php" id="sits-settings-form">
                <?php
                settings_fields($this->option_group);
                do_settings_sections($this->page_slug);
                submit_button();
                ?>
            </form>

            <hr style="margin:30px 0;">

            <div class="sits-cache-section">
                <h3><?php esc_html_e( 'Cache Management', 'softech-addons-for-elementor' ); ?></h3>
                <p class="description"><?php esc_html_e( 'Clear all plugin-generated caches including Elementor CSS, transients, and widget caches. Use this if your changes are not reflecting on the frontend.', 'softech-addons-for-elementor' ); ?></p>
                <br>
                <button type="button" id="sits-clear-cache-btn" class="button button-secondary">
                    <span class="dashicons dashicons-trash" style="vertical-align:middle;margin-top:-2px;margin-right:4px;"></span>
                    <?php esc_html_e( 'Clear Plugin Cache', 'softech-addons-for-elementor' ); ?>
                </button>
                <span id="sits-clear-cache-msg" style="margin-left:12px;display:none;color:#46b450;font-weight:600;"></span>
            </div>
        </div>
    <?php
    }
    
    private function render_pro_tab()
    {
        $pro_widgets_info = \sits_get_pro_widgets_info();
    ?>
        <div class="sits-pro-page">
            <div class="sits-pro-header">
                <h2><?php esc_html_e('Upgrade to Softech Addons for Elementor Pro', 'softech-addons-for-elementor'); ?></h2>
                <p><?php esc_html_e('Unlock premium widgets and features to supercharge your website', 'softech-addons-for-elementor'); ?></p><br>
                <a href="https://softechaddons.sitslab.com/#pro-plan" target="_blank" type="button" class="elementor-button button"><?php esc_html_e('Upgrade Now', 'softech-addons-for-elementor'); ?></a>
            </div>

            <div class="sits-pro-features">
                <div class="sits-feature-card">
                    <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect width="48" height="48" rx="12" fill="#0f3d4a" opacity="0.1" />
                        <path d="M24 14l3 9h9l-7 5 3 9-8-6-8 6 3-9-7-5h9l3-9z" fill="#0f3d4a" />
                    </svg>
                    <h3><?php esc_html_e('Premium Widgets', 'softech-addons-for-elementor'); ?></h3>
                    <p><?php esc_html_e('Access exclusive widgets like Call to Action and more', 'softech-addons-for-elementor'); ?></p>
                </div>
                <div class="sits-feature-card">
                    <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect width="48" height="48" rx="12" fill="#0f3d4a" opacity="0.1" />
                        <circle cx="24" cy="24" r="8" stroke="#0f3d4a" stroke-width="2" />
                        <path d="M24 20v4l3 3" stroke="#0f3d4a" stroke-width="2" stroke-linecap="round" />
                    </svg>
                    <h3><?php esc_html_e('Advanced Customization', 'softech-addons-for-elementor'); ?></h3>
                    <p><?php esc_html_e('More styling options and controls for your widgets', 'softech-addons-for-elementor'); ?></p>
                </div>
                <div class="sits-feature-card">
                    <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <rect width="48" height="48" rx="12" fill="#0f3d4a" opacity="0.1" />
                        <path d="M24 16v16M32 24l-8 8-8-8" stroke="#0f3d4a" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    </svg>
                    <h3><?php esc_html_e('Priority Support', 'softech-addons-for-elementor'); ?></h3>
                    <p><?php esc_html_e('Get priority support and regular updates', 'softech-addons-for-elementor'); ?></p>
                </div>
            </div>

            <?php if (!empty($pro_widgets_info)): ?>
               <div class="sits-pro-locked-widgets">
    <h3><?php esc_html_e('Premium Widgets', 'softech-addons-for-elementor'); ?></h3>
    <div class="sits-locked-widgets-grid">
        <?php foreach ($pro_widgets_info as $widget): ?>
            <?php
            $widget_title = isset($widget['title']) ? $widget['title'] : '';
            $widget_description = isset($widget['description']) ? $widget['description'] : '';
            $widget_icon = isset($widget['icon']) ? $widget['icon'] : 'eicon-star';
            ?>
            <div class="sits-locked-widget-item">
                <i class="<?php echo esc_attr($widget_icon); ?>" style="font-size: 36px; color: #0f3d4a;"></i>
                <h4><?php echo esc_html($widget_title); ?></h4>
                <p><?php echo esc_html($widget_description); ?></p>
            </div>
        <?php endforeach; ?>
    </div>
</div>
            <?php endif; ?>
        </div>
        <?php
    }
    
    
    public function ajax_toggle_widget()
    {
        check_ajax_referer('sits_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'softech-addons-for-elementor')]);
        }

        // Sanitize input
        $widget_name = isset($_POST['widget']) ? sanitize_text_field(wp_unslash($_POST['widget'])) : '';
        $enabled     = isset($_POST['enabled']) ? filter_var(wp_unslash($_POST['enabled']), FILTER_VALIDATE_BOOLEAN) : false;

        if (empty($widget_name)) {
            wp_send_json_error(['message' => esc_html__('Invalid widget name.', 'softech-addons-for-elementor')]);
        }

        $disabled_widgets = get_option($this->widgets_option, []);

        if ($enabled) {
            $disabled_widgets = array_diff($disabled_widgets, [$widget_name]);
        } else {
            if (!in_array($widget_name, $disabled_widgets, true)) {
                $disabled_widgets[] = $widget_name;
            }
        }

        update_option($this->widgets_option, array_values($disabled_widgets));

        $this->clear_elementor_cache();

        update_option('sits_widgets_version', (int) get_option('sits_widgets_version', 0) + 1);

        wp_send_json_success([
            'message'         => esc_html__('Widget toggled successfully.', 'softech-addons-for-elementor'),
            'reload_required' => false,
        ]);
    }



    public function ajax_toggle_all_widgets()
    {
        check_ajax_referer('sits_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Unauthorized', 'softech-addons-for-elementor')]);
        }

        $widgets = [];

        if (isset($_POST['widgets']) && is_array($_POST['widgets'])) {
            // Unslash and sanitize
            $raw_widgets       = wp_unslash($_POST['widgets']); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $widgets           = array_map('sanitize_text_field', $raw_widgets);
        }

        $enabled = isset($_POST['enabled'])
            ? filter_var(wp_unslash($_POST['enabled']), FILTER_VALIDATE_BOOLEAN)
            : false;

        if (empty($widgets)) {
            wp_send_json_error(['message' => esc_html__('No widgets provided.', 'softech-addons-for-elementor')]);
        }

        $disabled_widgets = get_option($this->widgets_option, []);
        if (!is_array($disabled_widgets)) {
            $disabled_widgets = [];
        }

        $disabled_widgets = $enabled
            ? array_diff($disabled_widgets, $widgets)
            : array_unique(array_merge($disabled_widgets, $widgets));

        update_option($this->widgets_option, array_values($disabled_widgets));

        $this->clear_elementor_cache();

        update_option('sits_widgets_version', (int) get_option('sits_widgets_version', 0) + 1);

        wp_send_json_success([
            'message'         => esc_html__('All widgets toggled successfully.', 'softech-addons-for-elementor'),
            'reload_required' => false,
            'affected_count'  => count($widgets),
        ]);
    }
    
   public function ajax_load_tab()
{
    check_ajax_referer('sits_admin_nonce', 'nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => esc_html__('Unauthorized', 'softech-addons-for-elementor')]);
    }

    $tab = isset($_POST['tab']) ? sanitize_key($_POST['tab']) : 'widgets';
    $subtab = isset($_POST['subtab']) ? sanitize_key($_POST['subtab']) : '';

    ob_start();

    if ($tab === 'widgets') {
        $this->render_widgets_tab();
    } elseif ($tab === 'settings') {
        $this->render_settings_tab();
    } elseif ($tab === 'theme-builder') {
        $this->render_theme_builder_tab();
    } elseif ($tab === 'payment-settings') {
        if (class_exists('Softech_Addons_for_Elementor\Includes\SITS_Elementor_Payment_Settings')) {
            $payment_settings = \Softech_Addons_for_Elementor\Includes\SITS_Elementor_Payment_Settings::instance();
            $payment_settings->render_payment_settings_tab($subtab);
        }
    } elseif ($tab === 'go-pro') {
        $this->render_pro_tab();
    }

    $html = ob_get_clean();

    wp_send_json_success(['html' => $html]);
}

    /**
     * Point 2: Render the Theme Builder tab — embeds the template list table.
     */
    private function render_theme_builder_tab()
    {
        $post_type   = \Softech_Addons_for_Elementor\Includes\SITS_Header_Footer_Builder::POST_TYPE;
        $new_url     = admin_url( 'edit.php?post_type=' . $post_type );
        $hf_builder  = \Softech_Addons_for_Elementor\Includes\SITS_Header_Footer_Builder::instance();
        $active_opt  = $hf_builder->get_active_option();

        // Retrieve all published templates.
        $templates = get_posts( [
        'post_type'      => $post_type,
        'post_status'    => 'any',
        'posts_per_page' => 100,       
        'no_found_rows'  => true,      
        'orderby'        => 'title',
        'order'          => 'ASC',
        ] );
        ?>
        <div class="sits-theme-builder-tab">
            <div class="sits-theme-builder-header" style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
                <h2 style="margin:0;"><?php esc_html_e( 'Theme Builder Templates', 'softech-addons-for-elementor' ); ?></h2>
                <a href="<?php echo esc_url( $new_url ); ?>" class="button button-primary">
                    <?php esc_html_e( '+ Add New Template', 'softech-addons-for-elementor' ); ?>
                </a>
            </div>

            <?php if ( empty( $templates ) ) : ?>
                <p><?php esc_html_e( 'No templates found. Click "Add New Template" to create your first Header or Footer.', 'softech-addons-for-elementor' ); ?></p>
            <?php else : ?>
                <table class="wp-list-table widefat fixed striped sits-theme-builder-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e( 'Title', 'softech-addons-for-elementor' ); ?></th>
                            <th><?php esc_html_e( 'Type', 'softech-addons-for-elementor' ); ?></th>
                            <th><?php esc_html_e( 'Status', 'softech-addons-for-elementor' ); ?></th>
                            <th><?php esc_html_e( 'Post Status', 'softech-addons-for-elementor' ); ?></th>
                            <th><?php esc_html_e( 'Actions', 'softech-addons-for-elementor' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ( $templates as $tpl ) :
                            $type      = get_post_meta( $tpl->ID, \Softech_Addons_for_Elementor\Includes\SITS_Header_Footer_Builder::META_TYPE, true );
                            $is_active = in_array( $tpl->ID, $active_opt[ $type ] ?? [], true );
                            $edit_url  = admin_url( 'post.php?post=' . $tpl->ID . '&action=elementor' );
                            $status_label = $is_active
                                ? '<span class="sits-hf-status-badge sits-active">' . esc_html__( 'Active', 'softech-addons-for-elementor' ) . '</span>'
                                : '<span class="sits-hf-status-badge sits-inactive">' . esc_html__( 'Inactive', 'softech-addons-for-elementor' ) . '</span>';
                            $type_badge = $type
                                ? '<span class="sits-hf-type sits-hf-type-' . esc_attr( $type ) . '">' . esc_html( ucfirst( $type ) ) . '</span>'
                                : '—';
                        ?>
                            <tr>
                                <td><strong><?php echo esc_html( $tpl->post_title ); ?></strong></td>
                                <td><?php echo $type_badge; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td>
                                <td><?php echo $status_label; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td>
                                <td><?php echo esc_html( ucfirst( $tpl->post_status ) ); ?></td>
                                <td>
                                    <a href="<?php echo esc_url( $edit_url ); ?>" class="button button-small">
                                        <?php esc_html_e( 'Edit with Elementor', 'softech-addons-for-elementor' ); ?>
                                    </a>
                                    <a href="<?php echo esc_url( admin_url( 'edit.php?post_type=' . $post_type ) ); ?>" class="button button-small">
                                        <?php esc_html_e( 'Manage', 'softech-addons-for-elementor' ); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Point 3: AJAX handler for the Clear Cache button in the Settings tab.
     */
    public function ajax_clear_plugin_cache()
    {
        check_ajax_referer( 'sits_admin_nonce', 'nonce' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( [ 'message' => esc_html__( 'Unauthorized', 'softech-addons-for-elementor' ) ] );
        }

        // Clear Elementor's generated CSS / file cache.
        $this->clear_elementor_cache();

        // Clear plugin-specific transients.
        delete_transient( 'sits_hf_synced_ids' );
        delete_transient( 'elementor_widgets_cache' );

        // Flush WP object cache group used by Cache_Manager.
        wp_cache_flush_group( \Softech_Addons_for_Elementor\Includes\Cache_Manager::CACHE_GROUP );

        // Bump the widgets version so any widget-related caches are invalidated.
        update_option( 'sits_widgets_version', (int) get_option( 'sits_widgets_version', 0 ) + 1 );

        wp_send_json_success( [ 'message' => esc_html__( 'Cache cleared successfully.', 'softech-addons-for-elementor' ) ] );
    }

    private function clear_elementor_cache()
    {
        if (! did_action('elementor/loaded') || ! class_exists('\Elementor\Plugin')) {
            return;
        }

        global $wpdb;

        try {
            \Elementor\Plugin::$instance->files_manager->clear_cache();

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
                    $wpdb->esc_like('_transient_elementor_') . '%',
                    $wpdb->esc_like('_transient_timeout_elementor_') . '%'
                )
            );

            delete_option('_elementor_global_css');
            delete_post_meta_by_key('_elementor_css');
            delete_transient('elementor_widgets_cache');
        } catch (\Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
                trigger_error(
                    'SITS: Error clearing Elementor cache - ' . esc_html($e->getMessage()),
                    E_USER_WARNING
                );
            }
        }
    }



    private function is_elementor_active(): bool
    {
        if (!function_exists('is_plugin_active')) {
            include_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        return is_plugin_active('elementor/elementor.php');
    }

    private function get_default_options(): array
    {
        return [
           
            'gsap_global_split_enable' => '',
            'gsap_global_split_class' => '.global-split-text',
            'gsap_global_split_type' => 'chars',
            'gsap_global_split_animation' => 'slideUp',
            'gsap_global_split_stagger' => 0.008,
            'gsap_global_split_line_stagger' => 0.08,
            'gsap_global_split_scroll_start' => 100,
        ];
    }

    public function enqueue_admin_assets($hook)
    {
        if (strpos($hook, $this->page_slug) === false) {
            return;
        }

        wp_enqueue_style(
            'sits-admin-style',
            SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/css/admin.css',
            [],
            SITS_ELEMENTOR_ADDONS_VERSION
        );

        wp_enqueue_script(
            'sits-admin-script',
            SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/js/admin.js',
            ['jquery'],
            SITS_ELEMENTOR_ADDONS_VERSION,
            true
        );

        wp_localize_script('sits-admin-script', 'sitsAdmin', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('sits_admin_nonce'),
        ]);
    }
    
    private function get_all_available_widgets()
{
    $widgets = [];
    $can_pro_render = apply_filters('sits_elementor_addons_can_render_pro', false);

    $widget_dirs = [
        SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'widgets/',
    ];

    if (! $can_pro_render) {
        $widget_dirs[] = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'feature-locked-widgets/';
    }



        // Loop through each directory
        foreach ($widget_dirs as $widgets_dir) {
            if (is_dir($widgets_dir)) {
                $widget_files = glob($widgets_dir . '*.php');

                if (!empty($widget_files)) {
                    foreach ($widget_files as $file) {
                        $filename = basename($file, '.php');
                        $widget_name = str_replace('-', '_', $filename);

                        $widget_info = $this->extract_widget_info_from_file($file);

                        if ($widget_info) {
                            $widgets[] = $widget_info;
                        } else {
                            $widgets[] = [
                                'name' => $widget_name,
                                'title' => ucwords(str_replace(['_', '-'], ' ', $filename)),
                                'description' => '',
                                'categories' => ['sits-category'],
                                'is_locked' => false,
                            ];
                        }
                    }
                }
            }
        }

   

if ($can_pro_render && defined('SITS_ELEMENTOR_ADDONS_PRO_PLUGIN_PATH')) {
    $pro_widget_dirs = [
        SITS_ELEMENTOR_ADDONS_PRO_PLUGIN_PATH . 'widgets/',

    ];

            foreach ($pro_widget_dirs as $pro_widgets_dir) {
                if (is_dir($pro_widgets_dir)) {
                    $pro_widget_files = glob($pro_widgets_dir . '*.php');

                    if (!empty($pro_widget_files)) {
                        foreach ($pro_widget_files as $file) {
                            $filename = basename($file, '.php');
                            $widget_name = str_replace('-', '_', $filename);

                            $widget_info = $this->extract_widget_info_from_file($file);

                            if ($widget_info) {
                                $widget_info['is_pro'] = true;
                                $widgets[] = $widget_info;
                            } else {
                                $widgets[] = [
                                    'name' => $widget_name,
                                    'title' => ucwords(str_replace(['_', '-'], ' ', $filename)) . ' (PRO)',
                                    'description' => '',
                                    'categories' => ['sits-category'],
                                    'is_locked' => false,
                                    'is_pro' => true,
                                ];
                            }
                        }
                    }
                }
            }
        }

        return $widgets;
    }



    /**
     * Extract widget information from file without loading it into Elementor
     */
    private function extract_widget_info_from_file($file)
    {
        if (!file_exists($file)) {
            return null;
        }

        $filename = basename($file, '.php');
        $widget_name = str_replace('-', '_', $filename);
        $file_contents = file_get_contents($file);

        if (false === $file_contents) {
            return null;
        }

        // Extract title from get_title() method
        $title = $filename;
        if (preg_match('/function\s+get_title\s*\(\s*\)\s*\{[^}]*return\s+[_]*\(\s*[\'"]([^\'"]+)[\'"]/s', $file_contents, $matches)) {
            $title = $matches[1];
        }

        // Extract description if exists
        $description = '';
        if (preg_match('/function\s+get_description\s*\(\s*\)\s*\{[^}]*return\s+[_]*\(\s*[\'"]([^\'"]+)[\'"]/s', $file_contents, $matches)) {
            $description = $matches[1];
        }

        return [
            'name' => $widget_name,
            'title' => $title,
            'description' => $description,
            'categories' => ['sits-category'],
            'is_locked' => false,
            'file' => $filename,
        ];
    }
}

new SITS_Elementor_Addons_Settings();
