<?php
/**
 * AJAX: Plugin Installation & Activation (Wizard Step 4)
 */

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

/**
 * AJAX: Install a plugin by slug
 */
if ( ! function_exists( 'trstemp_ajax_install_plugin' ) ) {
    add_action( 'wp_ajax_trstemp_install_plugin_ajax', 'trstemp_ajax_install_plugin' );

    function trstemp_ajax_install_plugin() {
        check_ajax_referer( 'trstemp_nonce_action', 'nonce' );

        if ( ! current_user_can( 'install_plugins' ) ) {
            wp_send_json_error( array( 'message' => 'Permission denied' ) );
        }

        $slug = isset( $_POST['slug'] ) ? sanitize_key( wp_unslash( $_POST['slug'] ) ) : '';
        if ( empty( $slug ) ) {
            wp_send_json_error( array( 'message' => 'Invalid plugin slug' ) );
        }

        require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';

        // Silence output during install
        $skin     = new WP_Ajax_Upgrader_Skin();
        $upgrader = new Plugin_Upgrader( $skin );
        $result   = $upgrader->install( 'https://downloads.wordpress.org/plugin/' . $slug . '.latest-stable.zip' );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
        }

        if ( $result === false ) {
            wp_send_json_error( array( 'message' => 'Installation failed' ) );
        }

        // Return the plugin file path so JS can trigger activation next
        $plugin_file = trstemp_find_plugin_file( $slug );

        wp_send_json_success( array(
            'message'     => 'Plugin installed',
            'plugin_file' => $plugin_file,
        ) );
    }
}

/**
 * AJAX: Activate an installed plugin by its file path
 */
if ( ! function_exists( 'trstemp_ajax_activate_plugin_step4' ) ) {
    add_action( 'wp_ajax_trstemp_activate_plugin_step4', 'trstemp_ajax_activate_plugin_step4' );

    function trstemp_ajax_activate_plugin_step4() {
        check_ajax_referer( 'trstemp_nonce_action', 'nonce' );

        if ( ! current_user_can( 'activate_plugins' ) ) {
            wp_send_json_error( array( 'message' => 'Permission denied' ) );
        }

        $plugin_file = isset( $_POST['plugin_file'] ) ? sanitize_text_field( wp_unslash( $_POST['plugin_file'] ) ) : '';
        if ( empty( $plugin_file ) ) {
            wp_send_json_error( array( 'message' => 'Invalid plugin file' ) );
        }

        $result = activate_plugin( $plugin_file );

        if ( is_wp_error( $result ) ) {
            wp_send_json_error( array( 'message' => $result->get_error_message() ) );
        }

        wp_send_json_success( array( 'message' => 'Plugin activated' ) );
    }
}

/**
 * Helper: Find plugin file path from slug after installation
 */
if ( ! function_exists( 'trstemp_find_plugin_file' ) ) {
    function trstemp_find_plugin_file( $slug ) {
        if ( ! function_exists( 'get_plugins' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        $plugins = get_plugins();
        foreach ( array_keys( $plugins ) as $file ) {
            if ( strpos( $file, $slug . '/' ) === 0 ) {
                return $file;
            }
        }
        return $slug . '/' . $slug . '.php';
    }
}

if ( ! function_exists( 'trstemp_ajax_suggest_plugins' ) ) {

    add_action( 'wp_ajax_trstemp_suggest_plugins', 'trstemp_ajax_suggest_plugins' );

    function trstemp_ajax_suggest_plugins() {

        // 🔐 Security check
        check_ajax_referer( 'trstemp_nonce_action', 'nonce' );

        // 🔒 Capability check
        if ( ! current_user_can( 'install_plugins' ) ) {
            wp_send_json_error( 'Permission denied' );
        }

        // 📦 Plugins array
        if ( empty( $_POST['plugins'] ) || ! is_array( $_POST['plugins'] ) ) {
            wp_send_json_success( array( 'message' => 'No plugins to suggest' ) );
        }

        $plugins = array_map(
            'sanitize_text_field',
            wp_unslash( $_POST['plugins'] )
        );

        $suggestions = array();

        foreach ( $plugins as $slug ) {
            $plugin_info = trstemp_get_plugin_info( $slug );
            if ( $plugin_info ) {
                $suggestions[] = $plugin_info;
            }
        }

        wp_send_json_success( array(
            'message' => 'Plugin suggestions prepared',
            'suggestions' => $suggestions
        ) );
    }

    function trstemp_get_plugin_info( $slug ) {
        $plugin_map = array(
            'elementor' => array(
                'name' => 'Elementor',
                'description' => 'The world\'s leading WordPress page builder',
                'install_url' => admin_url( 'plugin-install.php?s=elementor&tab=search&type=term' ),
                'required' => true
            ),
            'turbo-addons-elementor' => array(
                'name' => 'Turbo Addons for Elementor',
                'description' => '80+ premium widgets for Elementor',
                'install_url' => admin_url( 'plugin-install.php?s=turbo-addons-elementor&tab=search&type=term' ),
                'required' => true
            ),
            'header-footer-builder-for-elementor' => array(
                'name' => 'Header Footer Builder for Elementor',
                'description' => 'Create custom headers and footers',
                'install_url' => admin_url( 'plugin-install.php?s=header-footer-builder-for-elementor&tab=search&type=term' ),
                'required' => false
            ),
            'contact-form-7' => array(
                'name' => 'Contact Form 7',
                'description' => 'Simple contact form solution',
                'install_url' => admin_url( 'plugin-install.php?s=contact-form-7&tab=search&type=term' ),
                'required' => false
            ),
            'woocommerce' => array(
                'name' => 'WooCommerce',
                'description' => 'Complete e-commerce solution',
                'install_url' => admin_url( 'plugin-install.php?s=woocommerce&tab=search&type=term' ),
                'required' => false
            ),
            'wordpress-seo' => array(
                'name' => 'Yoast SEO',
                'description' => 'SEO optimization plugin',
                'install_url' => admin_url( 'plugin-install.php?s=wordpress-seo&tab=search&type=term' ),
                'required' => false
            )
        );

        return isset( $plugin_map[ $slug ] ) ? $plugin_map[ $slug ] : null;
    }

    // Backward compatibility - old action name
    add_action( 'wp_ajax_trstemp_install_plugins', 'trstemp_ajax_suggest_plugins' );
}

/**
 * AJAX: Install & activate hello-elementor theme before import
 */
if ( ! function_exists( 'trstemp_ajax_setup_theme' ) ) {
    add_action( 'wp_ajax_trstemp_setup_theme', 'trstemp_ajax_setup_theme' );

    function trstemp_ajax_setup_theme() {
        check_ajax_referer( 'trstemp_nonce_action', 'nonce' );

        if ( ! current_user_can( 'install_themes' ) ) {
            wp_send_json_error( array( 'message' => 'Permission denied' ) );
        }

        $theme_slug = 'hello-elementor';
        $theme      = wp_get_theme( $theme_slug );

        // Install if not present
        if ( ! $theme->exists() ) {
            require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
            require_once ABSPATH . 'wp-admin/includes/theme-install.php';

            $skin     = new WP_Ajax_Upgrader_Skin();
            $upgrader = new Theme_Upgrader( $skin );
            $result   = $upgrader->install( 'https://downloads.wordpress.org/theme/' . $theme_slug . '.latest-stable.zip' );

            if ( is_wp_error( $result ) || ! $result ) {
                wp_send_json_error( array( 'message' => 'Theme installation failed' ) );
            }
        }

        // Activate if not already active
        if ( get_stylesheet() !== $theme_slug ) {
            switch_theme( $theme_slug );
        }

        wp_send_json_success( array( 'message' => 'Theme ready' ) );
    }
}
