<?php
/**
 * Wizard Step 4: Features & Plugins
 * 
 * @package TurboStarterTemplates
 * @since 1.0.5
 * 
 * phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
 */

// Security: Prevent direct accesss
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Security: Check if get_plugins function exists
if ( ! function_exists( 'get_plugins' ) ) {
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
}

/**
 * Check if plugin is installed
 */
function trstemp_is_plugin_installed( $plugin_path ) {
    $plugin_path = sanitize_text_field( $plugin_path );
    $plugins = get_plugins();
    return isset( $plugins[ $plugin_path ] );
}

/**
 * Get plugin status with multiple path checking
 */
function trstemp_get_plugin_status( $plugin_paths ) {
    // Handle both single path and array of paths
    if ( ! is_array( $plugin_paths ) ) {
        $plugin_paths = array( $plugin_paths );
    }
    
    foreach ( $plugin_paths as $plugin_path ) {
        $plugin_path = sanitize_text_field( $plugin_path );
        if ( is_plugin_active( $plugin_path ) ) {
            return 'active';
        } elseif ( trstemp_is_plugin_installed( $plugin_path ) ) {
            return 'installed';
        }
    }
    return 'missing';
}

// Check plugin statuses with multiple possible paths
$plugins_detailed_status = array(
    'turbo_addons' => trstemp_get_plugin_status( array(
        'turbo-addons-elementor/turbo-addons-elementor.php',
        'turbo-addons/turbo-addons.php'
    ) ),
    'elementor' => trstemp_get_plugin_status( 'elementor/elementor.php' ),
    'header_footer' => trstemp_get_plugin_status( array(
        'header-footer-builder-for-elementor/header-footer-builder-for-elementor.php',
        'header-footer-elementor/header-footer-elementor.php',
        'elementor-header-footer/elementor-header-footer.php'
    ) ),
    'contact_forms' => trstemp_get_plugin_status( array(
        'contact-form-7/wp-contact-form-7.php',
        'contact-form-7/contact-form-7.php'
    ) ),
    'ecommerce' => trstemp_get_plugin_status( 'woocommerce/woocommerce.php' ),
    'seo' => trstemp_get_plugin_status( array(
        'wordpress-seo/wp-seo.php',
        'yoast-seo/wp-seo.php'
    ) )
);

$plugins_status = array();
foreach ( $plugins_detailed_status as $key => $status ) {
    $plugins_status[ $key ] = ( $status === 'active' );
}

// Check for existing content
$existing_pages = get_pages();
$has_existing_content = false;
foreach ( $existing_pages as $page ) {
    if ( ! in_array( $page->post_name, array( 'sample-page', 'privacy-policy' ) ) ) {
        $has_existing_content = true;
        break;
    }
}

wp_register_script( 'trstemp-step4-js', '', array( 'jquery' ), '1.0.5', true );
wp_enqueue_script( 'trstemp-step4-js' );

$step4_vars = array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'nonce'   => wp_create_nonce( 'trstemp_nonce_action' ),
);

$inline_script_step4 = '(function($) {
    "use strict";
    var cfg = ' . wp_json_encode( $step4_vars ) . ';

    function setBtn(btn, text, disabled) {
        btn.textContent = text;
        btn.disabled = disabled;
    }

    function markInstalled(card) {
        var badge = card.querySelector(".feature-badge");
        if (badge) {
            badge.className = "feature-badge installed-badge";
            badge.textContent = "Installed";
        }
        var actions = card.querySelector(".plugin-actions");
        if (actions) actions.style.display = "none";
    }

    function activatePlugin(btn, pluginFile, card) {
        setBtn(btn, "Activating...", true);
        $.post(cfg.ajaxurl, {
            action: "trstemp_activate_plugin_step4",
            nonce: cfg.nonce,
            plugin_file: pluginFile
        }).done(function(res) {
            if (res.success) {
                markInstalled(card);
            } else {
                setBtn(btn, "Activate", false);
                alert(res.data && res.data.message ? res.data.message : "Activation failed");
            }
        }).fail(function() {
            setBtn(btn, "Activate", false);
            alert("Request failed. Please try again.");
        });
    }

    $(document).on("click", ".trstemp-install-btn", function() {
        var btn  = this;
        var card = btn.closest(".feature-card");
        var slug = btn.dataset.slug;
        setBtn(btn, "Installing...", true);
        $.post(cfg.ajaxurl, {
            action: "trstemp_install_plugin_ajax",
            nonce: cfg.nonce,
            slug: slug
        }).done(function(res) {
            if (res.success) {
                var pluginFile = res.data.plugin_file;
                setBtn(btn, "Activate", false);
                btn.className = btn.className.replace("trstemp-install-btn", "trstemp-activate-btn");
                btn.dataset.pluginFile = pluginFile;
            } else {
                setBtn(btn, "Install Plugin", false);
                alert(res.data && res.data.message ? res.data.message : "Installation failed");
            }
        }).fail(function() {
            setBtn(btn, "Install Plugin", false);
            alert("Request failed. Please try again.");
        });
    });

    $(document).on("click", ".trstemp-activate-btn", function() {
        var btn  = this;
        var card = btn.closest(".feature-card");
        activatePlugin(btn, btn.dataset.pluginFile, card);
    });

})(jQuery);';

wp_add_inline_script( 'trstemp-step4-js', $inline_script_step4 );
?>

<div class="trstemp-features-step">
    <div class="step-header">
        <h2><?php echo esc_html__( 'Recommended Plugins for Your Website', 'turbo-templates-library-for-elementor' ); ?></h2>
        <p><?php echo esc_html__( 'These plugins are recommended for the best experience. You can install them manually from the WordPress plugin directory.', 'turbo-templates-library-for-elementor' ); ?></p>
    </div>
    
    <div class="features-grid">
        <div class="feature-card <?php echo $plugins_status['turbo_addons'] ? 'installed' : 'required'; ?>" data-feature="turbo_addons">
            <div class="feature-header">
                <div class="feature-icon">🧩</div>
                <div class="feature-badge <?php echo $plugins_status['turbo_addons'] ? 'installed-badge' : 'required-badge'; ?>">
                    <?php echo $plugins_status['turbo_addons'] ? esc_html__( 'Installed', 'turbo-templates-library-for-elementor' ) : esc_html__( 'Required', 'turbo-templates-library-for-elementor' ); ?>
                </div>
            </div>
            <h3><?php echo esc_html__( 'Turbo Addons for Elementor', 'turbo-templates-library-for-elementor' ); ?></h3>
             <?php echo esc_html__('90+ Advanced Elementor Widgets with Drag & Drop Functionality','turbo-templates-library-for-elementor'); ?>
            <div class="feature-details">
                <?php if ( $plugins_detailed_status['turbo_addons'] !== 'active' ): ?>
                    <div class="plugin-actions">
                        <?php if ( $plugins_detailed_status['turbo_addons'] === 'installed' ): ?>
                            <button class="button button-primary trstemp-activate-btn" data-plugin-file="turbo-addons-elementor/turbo-addons-elementor.php"><?php echo esc_html__( 'Activate', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php else: ?>
                            <button class="button button-primary trstemp-install-btn" data-slug="turbo-addons-elementor"><?php echo esc_html__( 'Install Plugin', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="feature-card <?php echo $plugins_status['elementor'] ? 'installed' : 'required'; ?>" data-feature="elementor">
            <div class="feature-header">
                <div class="feature-icon">🎨</div>
                <div class="feature-badge <?php echo $plugins_status['elementor'] ? 'installed-badge' : 'required-badge'; ?>">
                    <?php echo $plugins_status['elementor'] ? esc_html__( 'Installed', 'turbo-templates-library-for-elementor' ) : esc_html__( 'Required', 'turbo-templates-library-for-elementor' ); ?>
                </div>
            </div>
            <h3><?php echo esc_html__( 'Elementor Page Builder', 'turbo-templates-library-for-elementor' ); ?></h3>
            <?php echo esc_html__('The world\'s leading WordPress page builder with drag & drop editor', 'turbo-templates-library-for-elementor' ); ?>
            <div class="feature-details">
                <?php if ( $plugins_detailed_status['elementor'] !== 'active' ): ?>
                    <div class="plugin-actions">
                        <?php if ( $plugins_detailed_status['elementor'] === 'installed' ): ?>
                            <button class="button button-primary trstemp-activate-btn" data-plugin-file="elementor/elementor.php"><?php echo esc_html__( 'Activate', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php else: ?>
                            <button class="button button-primary trstemp-install-btn" data-slug="elementor"><?php echo esc_html__( 'Install Plugin', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="feature-card"
        data-plugin-slug="header-footer-builder-for-elementor"
        data-plugin-status="<?php echo esc_attr( $plugins_detailed_status['header_footer'] ); ?>">
            <div class="feature-header">
                <div class="feature-icon">📄</div>
                <div class="feature-badge <?php echo $plugins_status['header_footer'] ? 'installed-badge' : 'optional-badge'; ?>">
                    <?php echo $plugins_status['header_footer'] ? esc_html__( 'Installed', 'turbo-templates-library-for-elementor' ) : esc_html__( 'Optional', 'turbo-templates-library-for-elementor' ); ?>
                </div>
            </div>
            <h3><?php echo esc_html__( 'Header Footer Elementor', 'turbo-templates-library-for-elementor' ); ?></h3>
            <p><?php echo esc_html__( 'Create custom headers and footers with Elementor', 'turbo-templates-library-for-elementor' ); ?></p>
            <div class="feature-details">
                <?php if ( $plugins_detailed_status['header_footer'] !== 'active' ): ?>
                    <div class="plugin-actions">
                        <?php if ( $plugins_detailed_status['header_footer'] === 'installed' ): ?>
                            <button class="button button-secondary trstemp-activate-btn" data-plugin-file="header-footer-builder-for-elementor/header-footer-builder-for-elementor.php"><?php echo esc_html__( 'Activate', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php else: ?>
                            <button class="button button-secondary trstemp-install-btn" data-slug="header-footer-builder-for-elementor"><?php echo esc_html__( 'Install Plugin', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <div class="feature-card optional"
        data-plugin-slug="contact-form-7"
        data-plugin-status="<?php echo esc_attr( $plugins_detailed_status['contact_forms'] ); ?>">
            <div class="feature-header">
                <div class="feature-icon">📧</div>
                <div class="feature-badge <?php echo $plugins_status['contact_forms'] ? 'installed-badge' : 'optional-badge'; ?>">
                    <?php echo $plugins_status['contact_forms'] ? esc_html__( 'Installed', 'turbo-templates-library-for-elementor' ) : esc_html__( 'Optional', 'turbo-templates-library-for-elementor' ); ?>
                </div>
            </div>
            <h3><?php echo esc_html__( 'Contact Form 7', 'turbo-templates-library-for-elementor' ); ?></h3>
            <p><?php echo esc_html__( 'Simple and flexible contact form solution', 'turbo-templates-library-for-elementor' ); ?></p>
            <div class="feature-details">

                <?php if ( $plugins_detailed_status['contact_forms'] !== 'active' ): ?>
                    <div class="plugin-actions">
                        <?php if ( $plugins_detailed_status['contact_forms'] === 'installed' ): ?>
                            <button class="button button-secondary trstemp-activate-btn" data-plugin-file="contact-form-7/wp-contact-form-7.php"><?php echo esc_html__( 'Activate', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php else: ?>
                            <button class="button button-secondary trstemp-install-btn" data-slug="contact-form-7"><?php echo esc_html__( 'Install Plugin', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="feature-card optional"
     data-plugin-slug="woocommerce"
     data-plugin-status="<?php echo esc_attr( $plugins_detailed_status['ecommerce'] ); ?>">
            <div class="feature-header">
                <div class="feature-icon">🛒</div>
                <div class="feature-badge <?php echo $plugins_status['ecommerce'] ? 'installed-badge' : 'optional-badge'; ?>">
                    <?php echo $plugins_status['ecommerce'] ? esc_html__( 'Installed', 'turbo-templates-library-for-elementor' ) : esc_html__( 'Optional', 'turbo-templates-library-for-elementor' ); ?>
                </div>
            </div>
            <h3><?php echo esc_html__( 'WooCommerce', 'turbo-templates-library-for-elementor' ); ?></h3>
            <p><?php echo esc_html__( 'Complete e-commerce solution for WordPress', 'turbo-templates-library-for-elementor' ); ?></p>
            <div class="feature-details">
                
                <?php if ( $plugins_detailed_status['ecommerce'] !== 'active' ): ?>
                    <div class="plugin-actions">
                        <?php if ( $plugins_detailed_status['ecommerce'] === 'installed' ): ?>
                            <button class="button button-secondary trstemp-activate-btn" data-plugin-file="woocommerce/woocommerce.php"><?php echo esc_html__( 'Activate', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php else: ?>
                            <button class="button button-secondary trstemp-install-btn" data-slug="woocommerce"><?php echo esc_html__( 'Install Plugin', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="feature-card optional"
     data-plugin-slug="wordpress-seo"
     data-plugin-status="<?php echo esc_attr( $plugins_detailed_status['seo'] ); ?>">
            <div class="feature-header">
                <div class="feature-icon">🔍</div>
                <div class="feature-badge <?php echo $plugins_status['seo'] ? 'installed-badge' : 'optional-badge'; ?>">
                    <?php echo $plugins_status['seo'] ? esc_html__( 'Installed', 'turbo-templates-library-for-elementor' ) : esc_html__( 'Optional', 'turbo-templates-library-for-elementor' ); ?>
                </div>
            </div>
            <h3><?php echo esc_html__( 'Yoast SEO', 'turbo-templates-library-for-elementor' ); ?></h3>
            <p><?php echo esc_html__( 'Optimize your website for search engines', 'turbo-templates-library-for-elementor' ); ?></p>
            <div class="feature-details">
             
                <?php if ( $plugins_detailed_status['seo'] !== 'active' ): ?>
                    <div class="plugin-actions">
                        <?php if ( $plugins_detailed_status['seo'] === 'installed' ): ?>
                            <button class="button button-secondary trstemp-activate-btn" data-plugin-file="wordpress-seo/wp-seo.php"><?php echo esc_html__( 'Activate', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php else: ?>
                            <button class="button button-secondary trstemp-install-btn" data-slug="wordpress-seo"><?php echo esc_html__( 'Install Plugin', 'turbo-templates-library-for-elementor' ); ?></button>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <div class="plugin-status-summary">
        <h3><?php echo esc_html__( 'Plugin Status Summary', 'turbo-templates-library-for-elementor' ); ?></h3>
        <div class="status-grid">
            <div class="status-item">
                <span class="status-label"><?php echo esc_html__( 'Turbo Addons:', 'turbo-templates-library-for-elementor' ); ?></span>
                <span class="status-value <?php echo esc_attr($plugins_detailed_status['turbo_addons']); ?>">
                    <?php echo esc_html(ucfirst($plugins_detailed_status['turbo_addons'])); ?>
                </span>
            </div>
            <div class="status-item">
                <span class="status-label"><?php echo esc_html__( 'Elementor:', 'turbo-templates-library-for-elementor' ); ?></span>
                <span class="status-value <?php echo esc_attr($plugins_detailed_status['elementor']); ?>">
                    <?php echo esc_html(ucfirst($plugins_detailed_status['elementor'])); ?>
                </span>
            </div>
            <div class="status-item">
                <span class="status-label"><?php echo esc_html__( 'Header Footer:', 'turbo-templates-library-for-elementor' ); ?></span>
                <span class="status-value <?php echo esc_attr($plugins_detailed_status['header_footer']); ?>">
                    <?php echo esc_html(ucfirst($plugins_detailed_status['header_footer'])); ?>
                </span>
            </div>
            <div class="status-item">
                <span class="status-label"><?php echo esc_html__( 'Contact Form 7:', 'turbo-templates-library-for-elementor' ); ?></span>
                <span class="status-value <?php echo esc_attr($plugins_detailed_status['contact_forms']); ?>">
                    <?php echo esc_html(ucfirst($plugins_detailed_status['contact_forms'])); ?>
                </span>
            </div>
            <div class="status-item">
                <span class="status-label"><?php echo esc_html__( 'WooCommerce:', 'turbo-templates-library-for-elementor' ); ?></span>
                <span class="status-value <?php echo esc_attr($plugins_detailed_status['ecommerce']); ?>">
                    <?php echo esc_html(ucfirst($plugins_detailed_status['ecommerce'])); ?>
                </span>
            </div>
            <div class="status-item">
                <span class="status-label"><?php echo esc_html__( 'Yoast SEO:', 'turbo-templates-library-for-elementor' ); ?></span>
                <span class="status-value <?php echo esc_attr($plugins_detailed_status['seo']); ?>">
                    <?php echo esc_html(ucfirst($plugins_detailed_status['seo'])); ?>
                </span>
            </div>
        </div>
    </div>
</div>