<?php
/*
Plugin Name: Softech Addons for Elementor
Description: A custom addon that provides additional widgets to extend Elementor’s functionality with flexible and reusable components.
Version: 1.2.4
Author: shravanchoudhary
Author URI: https://softechaddons.sitslab.com/
License: GPL v2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: softech-addons-for-elementor
Requires Plugins: elementor
*/

namespace Softech_Addons_for_Elementor\Widgets;
// PSR‑4‑style autoloader for our namespace.  classes live in /includes.
spl_autoload_register( function( $class ) {
    // only handle our namespace
    $prefix = 'Softech_Addons_for_Elementor';
    if ( 0 !== strpos( $class, $prefix ) ) {
        return;
    }

    // convert namespace to file path
    $relative = str_replace( '\\', '/', substr( $class, strlen( $prefix ) + 1 ) );
    $file = plugin_dir_path( __FILE__ ) . "includes/{$relative}.php";

    if ( file_exists( $file ) ) {
        require_once $file;
    }
} );

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

// Load Utilities for all widgets
require_once plugin_dir_path(__FILE__) . 'includes/utilities.php';
// Define a constant for the text domain
if (! defined('SITS_ADDONS_TEXT_DOMAIN')) {
    define('SITS_ADDONS_TEXT_DOMAIN', 'softech-addons-for-elementor');
}

define('SITS_ELEMENTOR_ADDONS_VERSION', '1.2.4');
define('SITS_ELEMENTOR_ADDONS_PLUGIN_URL', plugin_dir_url(__FILE__));
define('SITS_ELEMENTOR_ADDONS_PLUGIN_PATH', plugin_dir_path(__FILE__));
define( 'SITS_REMOTE_TEMPLATES_URL', '' );

// Load helper functions FIRST (global namespace)
require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/helper-functions.php';
if ( defined( 'WP_CLI' ) && WP_CLI ) {
    require_once plugin_dir_path( __FILE__ ) . 'includes/class-sits-cli.php';
}
// Load settings page
require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/admin-settings.php';
require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/class-payment-settings.php';
// Load review notice class
require_once plugin_dir_path(__FILE__) . 'includes/class-review-notice.php';
require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/class-cache-manager.php';
// Activation hook (required by WP core)/

require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/sticky-controls.php';
add_action( 'elementor/init', function () {
    \SITS_Sticky_Controls::init();
} );
register_activation_hook(
    __FILE__,
    ['\SITSEL_Review_Notice', 'activate']
);

// Boot after plugins load
add_action('plugins_loaded', ['SITSEL_Review_Notice', 'init']);

require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/mega-menu.php';
require_once __DIR__ . '/includes/class-shortcodes.php';

// Load Header & Footer Builder
require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/class-header-footer-builder.php';

// Load Template Library
require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/template-library/class-template-library.php';


// Load Stripe AJAX Handler
require_once plugin_dir_path(__FILE__) . 'includes/stripe-handler.php';
/** ---- DATABASE TABLE ON ACTIVATE ---- */
register_activation_hook(__FILE__, function () {
    global $wpdb;
    $table = $wpdb->prefix . "sitsel_payments";
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS {$table} (
        id BIGINT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255),
        email VARCHAR(255),
        price DECIMAL(10, 2) NOT NULL DEFAULT 0.00,
        currency VARCHAR(10) DEFAULT 'USD',
        page_data VARCHAR(500),
        button_id VARCHAR(255),
        provider VARCHAR(50) DEFAULT 'stripe',
        status VARCHAR(50) DEFAULT 'pending',
        payment_id VARCHAR(255),
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        KEY idx_status (status),
        KEY idx_email (email),
        KEY idx_payment_id (payment_id),
        KEY idx_created_at (created_at),
        KEY idx_status_created (status, created_at)
    ) {$charset};";
    
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta($sql);

   // Check if table exists (activation-time schema check only)
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $table_exists = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s",
        DB_NAME,
        $table
    ));

    if ($table_exists) {
        // Reset AUTO_INCREMENT (schema operation, activation-time only)
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange
        $wpdb->query("ALTER TABLE `" . esc_sql($table) . "` AUTO_INCREMENT = 1");
    }
    
    wp_cache_delete('sitsel_payments_table_exists');
});

/**
 * Safe debug logger
 */
if (!function_exists('sits_log_debug')) {
    function sits_log_debug($message)
    {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('[SITS DEBUG] ' . $message);
        }
    }
}

final class SITS_Elementor_Addons
{
    /**
     * @var self|null
     */
    private static $instance = null;

    public static function instance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    private function __construct()
    {
        // Elementor must be active
        if (!did_action('elementor/loaded')) {
    add_action('admin_notices', [$this, 'missing_elementor_notice']);
    add_action('admin_init', function () {
        if (current_user_can('activate_plugins')) {
            deactivate_plugins(plugin_basename(SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'softech-addons-for-elementor.php'));
        }
    });
    return;
}

        // Register widgets
        add_action('elementor/widgets/register', [$this, 'register_widgets']);

        // Add custom category
        add_action('elementor/elements/categories_registered', [$this, 'register_widget_category']);

        // Enqueue frontend assets
        add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_assets']);

        // Enqueue editor assets
        add_action('elementor/editor/after_enqueue_scripts', [$this, 'enqueue_editor_assets']);

        // Enqueue editor styles
        add_action('elementor/editor/after_enqueue_styles', [$this, 'enqueue_editor_styles']);

        // Add this line for dynamic tags
        add_action('elementor/dynamic_tags/register_tags', [$this, 'register_dynamic_tags']);
    }

    // register dynamic tags
   // register dynamic tags
public function register_dynamic_tags( $dynamic_tags ) {
    // Disable this check while developing if Elementor Pro is installed
    if ( defined( 'ELEMENTOR_PRO_VERSION' ) ) {
        return;
    }

    $base = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/dynamic-tags/';

    /* ---------------------------------
     * 1. AUTO-LOAD & REGISTER ALL GROUPS
     * --------------------------------- */
    $groups_dir = $base . 'groups/';
    if ( is_dir( $groups_dir ) ) {
        $group_files = glob( $groups_dir . 'class-*-group.php' );
        
        foreach ( $group_files as $group_file ) {
            require_once $group_file;
            
            // Extract class name from file
            $filename = basename( $group_file, '.php' );
            // Convert: class-softech-post-group -> Softech_Post_Group
            $class_name = str_replace( ' ', '_', ucwords( str_replace( '-', ' ', str_replace( 'class-', '', $filename ) ) ) );
            $full_class = 'Softech_Addons_for_Elementor\\Includes\\Dynamic_Tags\\Groups\\' . $class_name;
            
            if ( class_exists( $full_class ) && method_exists( $full_class, 'get_name' ) ) {
                $dynamic_tags->register_group(
                    $full_class::get_name(),
                    [
                        'title' => $full_class::get_title(),
                    ]
                );
            }
        }
    }

    /* ---------------------------------
     * 2. AUTO-LOAD & REGISTER ALL TAGS
     * --------------------------------- */
    $tags_dir = $base . 'tags/';
    if ( is_dir( $tags_dir ) ) {
        // Get all subdirectories (post-tags, site, image, archive, etc.)
        $tag_folders = glob( $tags_dir . '*', GLOB_ONLYDIR );
        
        foreach ( $tag_folders as $folder ) {
            // Get all PHP files in this folder
            $tag_files = glob( $folder . '/class-*.php' );
            
            foreach ( $tag_files as $tag_file ) {
                require_once $tag_file;
                
                // Extract folder name and class name
                $folder_name = basename( $folder );
                $filename = basename( $tag_file, '.php' );
                
                // Convert: post-tags -> Post_Tags, class-softech-post-title -> Softech_Post_Title
                $folder_class = str_replace( ' ', '_', ucwords( str_replace( '-', ' ', $folder_name ) ) );
                $class_name = str_replace( ' ', '_', ucwords( str_replace( '-', ' ', str_replace( 'class-', '', $filename ) ) ) );
                
                $full_class = 'Softech_Addons_for_Elementor\\Includes\\Dynamic_Tags\\Tags\\' . $folder_class . '\\' . $class_name;
                
                if ( class_exists( $full_class ) ) {
                    $dynamic_tags->register( new $full_class() );
                }
            }
        }
    }
}




    private function load_base_widget_class()
    {
        static $loaded = false;
        if ($loaded) {
            return;
        }

        $base_widget_file = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/Base_Locked_Widget.php';

        if (file_exists($base_widget_file)) {
            require_once $base_widget_file;
            $loaded = true;
        }
    }

    public function missing_elementor_notice()
    {
        if (!current_user_can('activate_plugins')) {
            return;
        }

        $message = sprintf(
            /* translators: %s: Elementor plugin name */
            esc_html__('Softech Addons for Elementor requires %s to be installed and active.', 'softech-addons-for-elementor'),
            '<strong>' . esc_html__('Elementor', 'softech-addons-for-elementor') . '</strong>'
        );

        printf(
            '<div class="notice notice-error is-dismissible"><p>%s</p></div>',
            wp_kses_post($message)
        );
    }

    public function register_widget_category($elements_manager)
    {
        $elements_manager->add_category(
            'sits-category',
            [
                'title' => esc_html__('SITS Widgets', 'softech-addons-for-elementor'),
                'icon'  => 'eicon-font',
            ]
        );

        $elements_manager->add_category(
            'sits-single-post',
            [
                'title' => esc_html__('Single Post', 'softech-addons-for-elementor'),
                'icon'  => 'eicon-single-post',
            ]
        );
    }

    public function register_widgets($widgets_manager)
{
    $this->load_base_widget_class();
    $this->register_free_widgets($widgets_manager);

    // Show locked widgets only if Pro can't render them
    if (!$this->can_pro_render_widgets()) {
        $this->register_locked_widgets($widgets_manager);
    }

    if (!$this->can_pro_render_widgets()) {
    $this->register_feature_locked_widgets($widgets_manager);
}

}
    private function is_pro_licensed(): bool
    {
        // Returns true only when Pro plugin has a valid license
        return apply_filters('sits_elementor_addons_is_pro_active', false);
    }
/**
 * Check if Pro plugin can render widgets (even with expired license if once valid)
 */
private function can_pro_render_widgets(): bool
{
    // Check if Pro plugin allows rendering (includes grace period)
    return apply_filters('sits_elementor_addons_can_render_pro', false);
}
    public function is_pro_active(): bool
    {
        return $this->is_pro_licensed();
    }

    private function is_widget_enabled($filename)
    {
        $widget_name = str_replace('-', '_', $filename);
        $widget_name_dashes = str_replace('_', '-', $filename);

        $disabled_widgets = get_option('sits_elementor_addons_disabled_widgets', []);

        $is_disabled = in_array($widget_name, $disabled_widgets, true)
            || in_array($widget_name_dashes, $disabled_widgets, true)
            || in_array($filename, $disabled_widgets, true);

        return !$is_disabled;
    }

    private function register_free_widgets($widgets_manager)
    {
        $widgets_dir = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'widgets/';
        if (!is_dir($widgets_dir)) {
            return;
        }

        $widget_files = glob($widgets_dir . '*.php');
        if (empty($widget_files)) {
            return;
        }

        foreach ($widget_files as $file) {
            $this->register_widget_from_file($file, $widgets_manager);
        }
    }

    private function register_locked_widgets($widgets_manager)
    {
        $locked_widgets_dir = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'locked-widgets/';

        if (!is_dir($locked_widgets_dir)) {
            wp_mkdir_p($locked_widgets_dir);
            return;
        }

        $widget_files = glob($locked_widgets_dir . '*.php');
        if (empty($widget_files)) {
            return;
        }

        foreach ($widget_files as $file) {
            $this->register_widget_from_file($file, $widgets_manager);
        }
    }


    private function register_feature_locked_widgets($widgets_manager)
    {
        $feature_locked_widgets_dir = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'feature-locked-widgets/';

        if (!is_dir($feature_locked_widgets_dir)) {
            wp_mkdir_p($feature_locked_widgets_dir);
            return;
        }

        $widget_files = glob($feature_locked_widgets_dir . '*.php');
        if (empty($widget_files)) {
            return;
        }

        foreach ($widget_files as $file) {
            $this->register_widget_from_file($file, $widgets_manager);
        }
    }


    private function register_widget_from_file($file, $widgets_manager)
    {
        if (!file_exists($file)) {
            return;
        }

        $filename = basename($file, '.php');

        sits_log_debug('Checking file: ' . $filename);
        sits_log_debug('Disabled widgets: ' . wp_json_encode(get_option('sits_elementor_addons_disabled_widgets', [])));

        if (!$this->is_widget_enabled($filename)) {
            sits_log_debug('Widget DISABLED, skipping: ' . $filename);
            return;
        }

        require_once $file;

        $classname = str_replace('-', '_', $filename);
        $namespace = __NAMESPACE__ . '\\' . $classname;

        if (class_exists($namespace)) {
            try {
                $widgets_manager->register(new $namespace());
                sits_log_debug('Widget registered: ' . $filename);
            } catch (\Exception $e) {
                sits_log_debug('Failed to register: ' . $filename . ' - ' . $e->getMessage());
            }
        }
    }

    // public function is_pro_active(): bool {
    //     return apply_filters('sits_elementor_addons_is_pro_active', false);
    // }

    public function get_pro_widgets_info(): array
    {
        return sits_get_pro_widgets_info();
    }
    


        public function enqueue_frontend_assets()
		{
			$base_url = SITS_ELEMENTOR_ADDONS_PLUGIN_URL;
			$version  = SITS_ELEMENTOR_ADDONS_VERSION;

			//  REMOVED: Global Swiper enqueue
			// Widgets will load Swiper via get_script_depends() only when needed

			//  Register (don't enqueue) Swiper for widgets to use
			wp_register_style('sits-swiper', $base_url . 'assets/css/swiper-bundle.min.css', [], '12.0.2');
			wp_register_script('sits-swiper', $base_url . 'assets/js/swiper-bundle.min.js', [], '12.0.2', true);
			
            wp_enqueue_style( 'sits-sticky-styles', SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/css/sticky.css', [], SITS_ELEMENTOR_ADDONS_VERSION );
            wp_enqueue_script( 'sits-sticky-script', SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/js/sticky.js', [ 'jquery' ], SITS_ELEMENTOR_ADDONS_VERSION, true );

			wp_enqueue_style('sits-frontend-styles', $base_url . 'assets/css/frontend.css', [], $version);
			wp_register_style('sitsel-cta-styles', $base_url . 'assets/css/cta-widget.css', [], $version);
			

         
           
		}

    public function enqueue_editor_styles()
    {
        wp_enqueue_style(
            'sitsel-locked-widget-editor',
            SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/css/locked-widget-editor.css',
            [],
            SITS_ELEMENTOR_ADDONS_VERSION
        );
    }

    public function enqueue_editor_assets()
    {
        $locked_widgets = [];
        $pro_widgets = sits_get_pro_widgets_info();

        foreach ($pro_widgets as $widget) {
            if (isset($widget['name'])) {
                $locked_widgets[] = sanitize_key($widget['name']);
            }
        }

        wp_enqueue_script(
            'sitsel-locked-widget',
            SITS_ELEMENTOR_ADDONS_PLUGIN_URL . 'assets/js/locked-widget.js',
            ['jquery', 'elementor-editor'],
            SITS_ELEMENTOR_ADDONS_VERSION,
            true
        );
        
        

        wp_localize_script(
            'sitsel-locked-widget',
            'sitselLockedWidgets',
            [
                'widgets'  => $locked_widgets,
                'messages' => [
                    'lockedTitle'   => esc_html__('Premium Widget', 'softech-addons-for-elementor'),
                    'lockedMessage' => esc_html__('This is a premium widget. Upgrade to Pro to unlock it!', 'softech-addons-for-elementor'),
                    'upgradeUrl'    => admin_url('admin.php?page=softech-addons-for-elementor&tab=pro'),
                    'upgradeText'   => esc_html__('Upgrade Now', 'softech-addons-for-elementor'),
                ],
            ]
        );
    }
}

add_action('elementor/editor/after_enqueue_scripts', function () {
    wp_register_script(
        'sitsel-elementor-editor',
        plugins_url('assets/js/sitsel-elementor-editor.js', __FILE__),
        ['jquery'],
        '1.0.1',
        true
    );

    wp_localize_script('sitsel-elementor-editor', 'sitSelEditor', [
        'editUrlBase' => admin_url('post.php?action=elementor&post='),
    ]);


    wp_enqueue_script('sitsel-elementor-editor');
});
add_action('elementor/editor/after_enqueue_scripts', function() {

    // JS
    wp_enqueue_script(
        'sitsel-mega-menu-frontend',
        plugin_dir_url(__FILE__) . 'assets/js/mega-menu-frontend.js',
        ['jquery'],
        '1.0.1',
        true
    );

  
});

//  enqueue editor styles 
add_action('elementor/editor/after_enqueue_styles', function () {
    wp_enqueue_style(
        'softech-editor-style',
        plugins_url('assets/css/editor.css', __FILE__),
        [],
        '1.0.1'
    );
});


// Init plugin
add_action('plugins_loaded', function () {
    SITS_Elementor_Addons::instance();
});
// In your main plugin file — add inside the plugins_loaded action
add_action( 'plugins_loaded', function() {
    require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/class-gsap-manager.php';
    \SITS_GSAP_Manager::init();
});

add_filter('plugin_action_links_' . plugin_basename(__FILE__), function ($links) {
    // Settings Page Link (UPDATED)
    $settings_link = '<a href="' . esc_url(admin_url('admin.php?page=softech-addons-for-elementor')) . '">' .
        esc_html__('Settings', 'softech-addons-for-elementor') .
        '</a>';

    // Add settings link first
    array_unshift($links, $settings_link);

    // Get Pro / Register Link (only if Pro is NOT active or license not valid)
    if (!sits_ea_is_pro_active()) {
        $upgrade_link = '<a href="https://softechaddons.sitslab.com/#pro-plan" target="_blank" style="color:#d63638;font-weight:bold;">' .
            esc_html__('Get Softech Addons for Elementor Pro', 'softech-addons-for-elementor') .
            '</a>';

        // Add upgrade link BEFORE settings
        array_unshift($links, $upgrade_link);
    }

    return $links;
});
