<?php

// Hook to add admin menu
add_action('admin_menu', 'atomicslider_plugin_menu');

/**
 * Get dynamic widget count from widget files
 */
function atomicslider_get_widget_count() {
    $widget_dir = plugin_dir_path(__FILE__) . 'widgets/';
    $widget_files = glob($widget_dir . '*.php');
    
    if ($widget_files === false) {
        return 0;
    }
    
    return count($widget_files);
}

/**
 * Get total widget count including Pro widgets
 */
function atomicslider_get_total_widget_count() {
    $count = atomicslider_get_widget_count(); // Free widgets
    
    // Add Pro widgets count if Pro plugin is active
    if (class_exists('AtomicSliderPro\Plugin')) {
        $pro_widget_dir = WP_PLUGIN_DIR . '/atomic-slider-pro/includes/widgets/';
        if (is_dir($pro_widget_dir)) {
            $pro_widget_files = glob($pro_widget_dir . '*.php');
            if ($pro_widget_files !== false) {
                $count += count($pro_widget_files);
            }
        }
    }
    
    return $count;
}

function atomicslider_plugin_menu() {
    // Add a top-level menu page
    add_menu_page(
        'Atomic Slider Dashboard', // Page title
        'Atomic Slider',    // Menu title
        'manage_options',   // Capability
        'atomic-slider', // Menu slug
        'atomicslider_dashboard_page', // Function to display the page content
        'dashicons-slides', // Icon (you can change this to any Dashicon)
        30 // Position in the menu (lower number is higher on the menu)
    );

    add_submenu_page(
        'atomic-slider',
        'Dashboard',
        'Dashboard',
        'manage_options',
        'atomic-slider',
        'atomicslider_dashboard_page'
    );

    add_submenu_page(
        'atomic-slider',
        'Widgets',
        'Widgets',
        'manage_options',
        'atomic-slider-widgets',
        'atomicslider_widgets_page'
    );

}

// Function to display the content of the custom admin page
function atomicslider_dashboard_page() {
    // Check if Pro plugin is active
    $is_pro_active = class_exists('AtomicSliderPro\Plugin');
    ?>
<div class="wrap asa-admin-wrap">
    <div>
        <h1></h1>
    </div>
    <div class="asa-admin-inner-wrap">
        <div class="asa-admin-header">
            <div class="asa-admin-branding">
                <h1><?php echo esc_html__('Welcome to Atomic Slider', 'atomic-slider'); ?></h1>
                <p class="asa-admin-subtitle">
                    <?php echo esc_html__('Power up your Elementor experience with our premium widgets', 'atomic-slider'); ?>
                </p>
            </div>
            <div class="asa-admin-actions">
                <a href="<?php echo esc_url(admin_url('admin.php?page=atomic-slider-widgets')); ?>"
                    class="asa-button asa-button-primary">
                    <span class="dashicons dashicons-admin-plugins"></span>
                    <?php echo esc_html__('Browse Widgets', 'atomic-slider'); ?>
                </a>
            </div>
        </div>

        <div class="asa-dashboard-grid">
            <!-- Main Content -->
            <div class="asa-dashboard-main">
                <!-- Stats Section -->
                <div class="asa-stats-section">
                    <div class="asa-stats-grid">
                        <div class="asa-stat-item">
                            <div class="asa-stat-icon">
                                <span class="dashicons dashicons-admin-plugins"></span>
                            </div>
                            <div class="asa-stat-content">
                                <h3><?php echo esc_html__('Active Widgets', 'atomic-slider'); ?></h3>
                                <?php 
                                    $widget_options = get_option('atomic-slider-widgets', []);
                                    $active_count = is_array($widget_options) ? count(array_filter($widget_options)) : 0;
                                    ?>
                                <div class="asa-stat-value"><?php echo esc_html($active_count); ?></div>
                            </div>
                        </div>
                        <div class="asa-stat-item">
                            <div class="asa-stat-icon">
                                <span class="dashicons dashicons-welcome-learn-more"></span>
                            </div>
                            <div class="asa-stat-content">
                                <h3><?php echo esc_html__('Total Available', 'atomic-slider'); ?></h3>
                                <div class="asa-stat-value"><?php echo atomicslider_get_total_widget_count(); ?></div>
                            </div>
                        </div>
                        <div class="asa-stat-item">
                            <div class="asa-stat-icon">
                                <span class="dashicons dashicons-chart-line"></span>
                            </div>
                            <div class="asa-stat-content">
                                <h3><?php echo esc_html__('Coming Soon', 'atomic-slider'); ?></h3>
                                <div class="asa-stat-value">10+</div>
                            </div>
                        </div>
                    </div>
                </div>



                <!-- Quick Links -->
                <div class="asa-quick-links-section">
                    <div class="asa-section-header">
                        <h2 class="asa-section-title"><?php echo esc_html__('Getting Started', 'atomic-slider'); ?></h2>
                    </div>
                    <div class="asa-quick-links-grid">
                        <a href="<?php echo esc_url(admin_url('admin.php?page=atomic-slider-widgets')); ?>"
                            class="asa-quick-link-card">
                            <div class="asa-quick-link-icon">
                                <span class="dashicons dashicons-admin-plugins"></span>
                            </div>
                            <div class="asa-quick-link-content">
                                <h3><?php echo esc_html__('Manage Widgets', 'atomic-slider'); ?></h3>
                                <p><?php echo esc_html__('Enable or disable Atomic Slider widgets', 'atomic-slider'); ?>
                                </p>
                            </div>
                            <div class="asa-quick-link-arrow">
                                <span class="dashicons dashicons-arrow-right-alt2"></span>
                            </div>
                        </a>
                        <a href="https://atomicslider.com/docs" target="_blank" class="asa-quick-link-card">
                            <div class="asa-quick-link-icon">
                                <span class="dashicons dashicons-book-alt"></span>
                            </div>
                            <div class="asa-quick-link-content">
                                <h3><?php echo esc_html__('Documentation', 'atomic-slider'); ?></h3>
                                <p><?php echo esc_html__('Learn how to use Atomic Slider', 'atomic-slider'); ?></p>
                            </div>
                            <div class="asa-quick-link-arrow">
                                <span class="dashicons dashicons-arrow-right-alt2"></span>
                            </div>
                        </a>
                        <a href="https://atomicslider.com/support" target="_blank" class="asa-quick-link-card">
                            <div class="asa-quick-link-icon">
                                <span class="dashicons dashicons-sos"></span>
                            </div>
                            <div class="asa-quick-link-content">
                                <h3><?php echo esc_html__('Get Support', 'atomic-slider'); ?></h3>
                                <p><?php echo esc_html__('Need help? Our support team is here', 'atomic-slider'); ?></p>
                            </div>
                            <div class="asa-quick-link-arrow">
                                <span class="dashicons dashicons-arrow-right-alt2"></span>
                            </div>
                        </a>
                    </div>
                </div>

                <!-- Features Section -->
                <div class="asa-features-section">
                    <div class="asa-section-header">
                        <h2 class="asa-section-title"><?php echo esc_html__('Premium Features', 'atomic-slider'); ?>
                        </h2>
                    </div>
                    <div class="asa-features-grid">
                        <div class="asa-feature-card">
                            <div class="asa-feature-icon">
                                <span class="dashicons dashicons-admin-customizer"></span>
                            </div>
                            <h3><?php echo esc_html__('Post Slider', 'atomic-slider'); ?></h3>
                            <p><?php echo esc_html__('Create beautiful sliders showcasing your blog posts with dynamic content and smooth animations.', 'atomic-slider'); ?></p>
                            <span
                                class="asa-badge asa-badge-soon"><?php echo esc_html__('Coming Soon', 'atomic-slider'); ?></span>
                        </div>
                        <div class="asa-feature-card">
                            <div class="asa-feature-icon">
                                <span class="dashicons dashicons-menu"></span>
                            </div>
                            <h3><?php echo esc_html__('WooCommerce Slider', 'atomic-slider'); ?></h3>
                            <p><?php echo esc_html__('Showcase your products with elegant, conversion-focused sliders designed for online stores.', 'atomic-slider'); ?>
                            </p>
                            <span
                                class="asa-badge asa-badge-soon"><?php echo esc_html__('Coming Soon', 'atomic-slider'); ?></span>
                        </div>
                        <div class="asa-feature-card">
                            <div class="asa-feature-icon">
                                <span class="dashicons dashicons-admin-post"></span>
                            </div>
                            <h3><?php echo esc_html__('Dynamic Content', 'atomic-slider'); ?></h3>
                            <p><?php echo esc_html__('Display dynamic content from your website.', 'atomic-slider'); ?>
                            </p>
                            <span
                                class="asa-badge asa-badge-soon"><?php echo esc_html__('Coming Soon', 'atomic-slider'); ?></span>
                        </div>
                        <div class="asa-feature-card">
                            <div class="asa-feature-icon">
                                <span class="dashicons dashicons-format-video"></span>
                            </div>
                            <h3><?php echo esc_html__('Video Slider', 'atomic-slider'); ?></h3>
                            <p><?php echo esc_html__('Display video slider from your website.', 'atomic-slider'); ?></p>
                            <span
                                class="asa-badge asa-badge-soon"><?php echo esc_html__('Coming Soon', 'atomic-slider'); ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sidebar -->
            <div class="asa-dashboard-sidebar">

                <div class="asa-pro-card">

                    <div class="asa-pro-header">
                        <h2><?php echo esc_html__('Atomic Slider Pro', 'atomic-slider'); ?></h2>
                        <p><?php echo esc_html__('Unlock premium widgets and features', 'atomic-slider'); ?></p>
                    </div>
                    <div class="asa-pro-features">
                        <div class="asa-pro-feature">
                            <span class="dashicons dashicons-yes-alt"></span>
                            <span><?php echo esc_html__('Advanced Widgets', 'atomic-slider'); ?></span>
                        </div>
                        <div class="asa-pro-feature">
                            <span class="dashicons dashicons-yes-alt"></span>
                            <span><?php echo esc_html__('Premium Support', 'atomic-slider'); ?></span>
                        </div>
                        <div class="asa-pro-feature">
                            <span class="dashicons dashicons-yes-alt"></span>
                            <span><?php echo esc_html__('Regular Updates', 'atomic-slider'); ?></span>
                        </div>
                        <div class="asa-pro-feature">
                            <span class="dashicons dashicons-yes-alt"></span>
                            <span><?php echo esc_html__('Priority Support', 'atomic-slider'); ?></span>
                        </div>
                    </div>
                    <a href="https://atomicslider.com/pro" target="_blank" class="asa-pro-button">
                        <?php echo esc_html__('Get Pro Version', 'atomic-slider'); ?>
                    </a>
                </div>

                <div class="asa-help-card">
                    <div class="asa-help-header">
                        <h3><?php echo esc_html__('Need Help?', 'atomic-slider'); ?></h3>
                        <p><?php echo esc_html__('We\'re here to assist you with any questions or issues.', 'atomic-slider'); ?>
                        </p>
                    </div>
                    <a href="https://atomicslider.com/support" target="_blank" class="asa-help-button">
                        <span class="dashicons dashicons-sos"></span>
                        <?php echo esc_html__('Contact Support', 'atomic-slider'); ?>
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
<?php
}

function atomicslider_widgets_page() {
    // Check if Pro plugin is active
    if (function_exists('as_fs') && as_fs()->can_use_premium_code()) {
        $is_pro_active = true;
    } else {
        $is_pro_active = false;
    }
    // $is_pro_active = class_exists('AtomicSliderPro\Plugin');
    
    $widgets = [
        'image-carousel' => [
            'title' => 'Image Carousel',
            'category' => 'content',
            'type' => 'free',
            'icon' => 'dashicons-slides'
        ],

        'super-flow' => [
            'title' => 'Super Flow',
            'category' => 'creative',
            'type' => 'pro',
            'icon' => 'dashicons-images-alt2'
        ],

        'hero-showcase' => [
            'title' => 'Showcase',
            'category' => 'Content',
            'type' => 'free',
            'icon' => 'dashicons-images-alt2'
        ],
        
    ];

    $categories = [
        'all' => 'All Widgets',
        'content' => 'Content',
        'creative' => 'Creative',
        'menu' => 'Menu / Navigation',
        'posts' => 'Posts / Dynamic',
        'woocommerce' => 'WooCommerce',
        'extensions' => 'Extensions / Global',
        'social' => 'Social Elements',
        'forms' => 'Forms / User',
        'special' => 'Special Features',
        'marketing' => 'Marketing'
    ];

    $types = [
        'all' => 'All',
        'free' => 'Free',
        'pro' => 'Pro'
    ];
    ?>
<div class="wrap asa-admin-wrap">
    <div>
        <h1></h1>
    </div>
    <div class="asa-admin-inner-wrap">
        <form method="post" action="options.php" class="asa-widgets-form" id="asa-widgets-form">
            <?php
                settings_fields('atomicslider_widget_options_group');
                do_settings_sections('asa-widget-settings');
                ?>

            <div class="asa-widgets-filters">
                <div class="asa-widgets-filters-left">
                    <div class="asa-widgets-search-wrap">
                        <input type="text" id="asa-widget-search"
                            placeholder="<?php echo esc_attr__('Search widgets...', 'atomic-slider'); ?>">
                    </div>
                    <div class="asa-filter-group">
                        <div class="asa-filter-buttons">
                            <?php foreach ($types as $key => $label): ?>
                            <button type="button" class="asa-filter-button" data-filter="type"
                                data-value="<?php echo esc_attr($key); ?>">
                                <?php echo esc_html($label); ?>
                            </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="asa-filter-group">
                    <div class="asa-widgets-actions">
                        <button type="button" class="button button-primary" id="activate-all">
                            <span class="dashicons dashicons-yes"></span>
                            <?php echo esc_html__('Activate All', 'atomic-slider'); ?>
                        </button>
                        <button type="button" class="button button-secondary" id="deactivate-all">
                            <span class="dashicons dashicons-no"></span>
                            <?php echo esc_html__('Deactivate All', 'atomic-slider'); ?>
                        </button>

                        <button type="submit" class="button button-primary" id="save-widgets">
                            <!-- <span class="dashicons dashicons-saved"></span> -->
                            <?php echo esc_html__('Save Changes', 'atomic-slider'); ?>
                        </button>
                    </div>
                </div>
            </div>

            <div class="asa-widgets-container">
                <div class="asa-category-sidebar">
                    <ul class="asa-category-tabs">
                        <?php foreach ($categories as $key => $label): ?>
                        <li>
                            <a href="#" class="asa-category-tab <?php echo $key === 'all' ? 'active' : ''; ?>"
                                data-category="<?php echo esc_attr($key); ?>">
                                <?php echo esc_html($label); ?>
                                <span class="asa-category-count" data-category="<?php echo esc_attr($key); ?>">0</span>
                            </a>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>

                <div class="asa-widgets-grid-wrap">
                    <div class="asa-widgets-grid">
                        <?php foreach ($widgets as $key => $widget): ?>
                        <?php 
                                $is_pro_widget = $widget['type'] === 'pro';
                                $is_locked = $is_pro_widget && !$is_pro_active;
                                ?>
                        <div class="asa-widget-item <?php echo $is_locked ? 'asa-widget-locked' : ''; ?>"
                            data-type="<?php echo esc_attr($widget['type']); ?>"
                            data-category="<?php echo esc_attr($widget['category']); ?>">
                            <div class="asa-widget-content">
                                <div class="asa-widget-info">
                                    <span class="dashicons <?php echo esc_attr($widget['icon']); ?>"></span>
                                    <div class="asa-widget-title-wrap">
                                        <h3><?php echo esc_html($widget['title']); ?></h3>
                                        <?php if (strpos($widget['type'], 'new') !== false): ?>
                                        <span class="asa-widget-badge asa-widget-badge-new">New</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php if ($is_locked): ?>
                                <div class="asa-widget-lock-overlay">
                                    <span class="dashicons dashicons-lock"></span>
                                </div>
                                <?php else: ?>
                                <label class="asa-switch">
                                    <?php 
                                                $widget_options = get_option('atomic-slider-widgets', []);
                                                $is_checked = isset($widget_options[$key]) && !empty($widget_options[$key]);
                                                ?>
                                    <input type="checkbox" name="atomic-slider-widgets[<?php echo esc_attr($key); ?>]"
                                        value="1" <?php checked($is_checked, true); ?> />
                                    <span class="asa-slider"></span>
                                </label>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </form>

        <div id="asa-notification" class="asa-notification" style="display: none;">
            <span class="asa-notification-message"></span>
        </div>
    </div>
</div>

<?php
}

// Register settings
add_action('admin_init', 'atomicslider_register_settings');

function atomicslider_register_settings() {
    register_setting(
        'atomicslider_widget_options_group',
        'atomic-slider-widgets',
        [
            'sanitize_callback' => 'atomicslider_sanitize_widget_options',
            'default' => []
        ]
    );
}

// Ensure all widgets are active by default
add_action('admin_init', 'atomicslider_ensure_default_widgets');

function atomicslider_ensure_default_widgets() {
    $current_widgets = get_option('atomic-slider-widgets', null);
    
    // Only set defaults if the option doesn't exist at all (not if it's empty)
    if ($current_widgets === null) {
        $widget_keys = [
            'image-carousel',
        ];
        $default_widgets = array_fill_keys($widget_keys, '1');
        update_option('atomic-slider-widgets', $default_widgets);
    }
}

/**
 * Sanitize widget options
 *
 * @param array $input The input array to sanitize
 * @return array Sanitized array
 */
function atomicslider_sanitize_widget_options($input) {
    if (!is_array($input)) {
        return array();
    }
    
    return array_map('sanitize_text_field', $input);
}

// Add AJAX handler for saving widgets
function atomicslider_save_widgets_ajax() {
    // Verify nonce
    if (!isset($_POST['security']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'atomicslider_save_widgets_nonce')) {
        wp_send_json_error(['message' => __('Security check failed.', 'atomic-slider')]);
        return;
    }

    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('You do not have sufficient permissions to access this page.', 'atomic-slider')]);
        return;
    }

    // Get and sanitize widget data
    $widgets = isset($_POST['atomic-slider-widgets']) ? array_map('sanitize_text_field', wp_unslash($_POST['atomic-slider-widgets'])) : [];

    // Always update the option, even if it's empty
    $updated = update_option('atomic-slider-widgets', $widgets);

    // update_option returns false if the value is unchanged or if there was an error
    // We'll treat both as success since the desired state is achieved
    if ($updated !== false) {
        wp_send_json_success(['message' => __('Widget settings saved successfully.', 'atomic-slider')]);
    } else {
        // Check if the option exists and matches what we're trying to save
        $current = get_option('atomic-slider-widgets', []);
        if ($current === $widgets) {
            // Value is already correct, no need to update
            wp_send_json_success(['message' => __('Widget settings saved successfully.', 'atomic-slider')]);
        } else {
            // There was an actual error
            wp_send_json_error(['message' => __('Failed to save settings. Please try again.', 'atomic-slider')]);
        }
    }
}
add_action('wp_ajax_atomicslider_save_widgets', 'atomicslider_save_widgets_ajax');