<?php
/**
 * BlogAura Admin Class.
 *
 * @package BlogAura
 * @since   1.0.0
 */
if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('BlogAura_Admin')):
    /**
     * BlogAura_Admin Class.
     */
    class BlogAura_Admin
    {
        /**
         * Constructor.
         */
        public function __construct()
        {
            add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
            add_action('wp_ajax_install_plugin', array($this, 'handle_plugin_action'));
            add_action('wp_ajax_activate_plugin', array($this, 'handle_plugin_action'));
        }

        /**
         * Handle plugin install/activate AJAX.
         */
        public function handle_plugin_action()
        {
            if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'blogaura_demo_import_nonce')) {
                wp_send_json_error(array('message' => 'Security check failed.'));
            }
            if (!current_user_can('install_plugins')) {
                wp_send_json_error(array('message' => 'You are not allowed to perform this action.'));
            }

            $plugin = sanitize_text_field($_POST['plugin']);
            $plugin_slug = sanitize_text_field($_POST['slug']);

            if (function_exists('blogaura_is_plugin_installed') && blogaura_is_plugin_installed($plugin)) {
                if (is_plugin_active($plugin)) {
                    wp_send_json_success(array('message' => 'Plugin is already activated.'));
                } else {
                    // Activate the plugin
                    $result = activate_plugin($plugin);

                    if (is_wp_error($result)) {
                        wp_send_json_error(array('message' => 'Error activating the plugin.'));
                    } else {
                        wp_send_json_success(array('message' => 'Plugin activated successfully!'));
                    }
                }
            } else {
                // Install and activate the plugin
                include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
                include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

                $api_args = array(
                    'slug' => $plugin_slug,
                    'fields' => array(
                        'short_description' => false,
                        'sections' => false,
                        'requires' => false,
                        'rating' => false,
                        'ratings' => false,
                        'downloaded' => false,
                        'last_updated' => false,
                        'added' => false,
                        'tags' => false,
                        'compatibility' => false,
                        'homepage' => false,
                        'donate_link' => false,
                    ),
                );

                $plugin_info = plugins_api('plugin_information', $api_args);

                // Error check for plugins_api
                if (is_wp_error($plugin_info)) {
                    wp_send_json_error(array('message' => 'Error retrieving plugin information.'));
                }

                $upgrader = new Plugin_Upgrader(new WP_Ajax_Upgrader_Skin());
                $result = $upgrader->install($plugin_info->download_link);

                if (is_wp_error($result)) {
                    wp_send_json_error(array('message' => 'Error installing the plugin.'));
                }

                $result = activate_plugin($plugin);

                if (is_wp_error($result)) {
                    wp_send_json_error(array('message' => 'Error activating the plugin.'));
                } else {
                    wp_send_json_success(array('message' => 'Plugin installed and activated successfully!'));
                }
            }
        }

        /**
         * Localize array for import button AJAX request.
         */
        public function enqueue_scripts()
        {
            $suffix = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? '' : '.min';

            $css_file = is_rtl()
                ? 'admin-rtl' . $suffix . '.css'
                : 'admin' . $suffix . '.css';

            wp_enqueue_style(
                'blogaura-admin-style',
                get_template_directory_uri() . '/inc/admin/dashboard/css/' . $css_file,
                array(),
                BLOGAURA_VERSION
            );

            wp_enqueue_script('blogaura-plugin-install-helper', get_template_directory_uri() . '/inc/admin/dashboard/js/admin.js', array('jquery'), BLOGAURA_VERSION, true);
            $welcome_data = array(
                'uri' => esc_url(admin_url('/themes.php?page=blogaura&tab=starter-templates')),
                'btn_text' => esc_html__('Processing...', 'blogaura'),
                'nonce' => wp_create_nonce('blogaura_demo_import_nonce'),
                'admin_url' => esc_url(admin_url()),
                'ajaxurl' => admin_url('admin-ajax.php'), // Include this line for using admin-ajax.php
            );
            wp_localize_script('blogaura-plugin-install-helper', 'blogauraRedirectDemoPage', $welcome_data);
        }
    }
endif;
return new BlogAura_Admin();