<?php

/**
 * Extension class for GS Jet Forms Google Sheet Connector Pro extensions operations
 * @since 1.0.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * GS_Extension Class
 * @since 1.0.0
 */

class GSHFJF_JetForm_Extensions
{

    /**
     *  Set things up.
     *
     *  @since 1.0.0
     */

    public function __construct()
    {
        // Install Jet Forms plugin
        add_action('wp_ajax_gshfjf_install_plugin', array($this, 'gshfjf_install_plugin'));

        // Activate Jet Forms plugin
        add_action('wp_ajax_gshfjf_activate_plugin', array($this, 'gshfjf_activate_plugin'));

        // Deactivate Jet Forms plugin
        add_action('wp_ajax_gshfjf_deactivate_plugin', array($this, 'gshfjf_deactivate_plugin'));
    }

    /**
     * Deactivate Jet Forms plugin
     *
     * @since 1.0.0
     */

    function gshfjf_deactivate_plugin()
    {
        // nonce check
        check_ajax_referer('gshfjf-ajax-nonce', 'security');

        if (!current_user_can('activate_plugins')) {
            wp_send_json_error('You do not have permission to deactivate plugins.');
        }

        if (!isset($_POST['plugin_slug'])) {
            wp_send_json_error('Plugin slug is missing.');
        }

        $plugin_slug = sanitize_text_field(wp_unslash($_POST['plugin_slug']));

        if (empty($plugin_slug)) {
            wp_send_json_error('Invalid plugin.');
        }

        // Ensure plugin exists before attempting to deactivate
        if (!file_exists(WP_PLUGIN_DIR . '/' . $plugin_slug)) {
            wp_send_json_error('Plugin not found.');
        }

        deactivate_plugins($plugin_slug);

        if (is_plugin_active($plugin_slug)) {
            wp_send_json_error('Failed to deactivate plugin.');
        }

        wp_send_json_success('Plugin deactivated successfully.');
    }

    /**
     * Installs or upgrades a plugin via AJAX using provided slug and download URL.
     *
     * @access public
     * @since 1.0.0
     */

    public function gshfjf_install_plugin()
    {

        if (! check_ajax_referer('gshfjf-ajax-nonce', 'security', false)) {
            wp_send_json_error([
                'message' => __('Invalid security token', 'gsheetconnector-for-jetform')
            ]);
        }

        if (! current_user_can('install_plugins')) {
            wp_send_json_error([
                'message' => __('You do not have permission to install plugin', 'gsheetconnector-for-jetform')
            ]);
        }

        if (empty($_POST['plugin_slug']) || empty($_POST['download_url'])) {
            wp_send_json_error([
                'message' => __('Missing required parameters', 'gsheetconnector-for-jetform')
            ]);
        }

        $plugin_slug  = sanitize_text_field(wp_unslash($_POST['plugin_slug']));
        $download_url = esc_url_raw(wp_unslash($_POST['download_url']));

        if (empty($plugin_slug) || empty($download_url)) {
            wp_send_json_error([
                'message' => __('Invalid plugin data', 'gsheetconnector-for-jetform')
            ]);
        }

        // Required files
        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/update.php';
        require_once ABSPATH . 'wp-admin/includes/plugin.php';

        $upgrader = new Plugin_Upgrader(new WP_Ajax_Upgrader_Skin());

        $installed_plugins = get_plugins();
        $plugin_path = '';

        foreach ($installed_plugins as $path => $details) {
            if (strpos($path, $plugin_slug . '/') === 0) {
                $plugin_path = $path;
                break;
            }
        }

        if ($plugin_path) {

            $update_plugins = get_site_transient('update_plugins');

            if (isset($update_plugins->response[$plugin_path])) {

                $result = $upgrader->upgrade($plugin_path);

                if (is_wp_error($result)) {
                    wp_send_json_error([
                        'message' => __('Upgrade failed: ', 'gsheetconnector-for-jetform') . $result->get_error_message()
                    ]);
                }

                wp_send_json_success([
                    'message' => __('Plugin upgraded successfully', 'gsheetconnector-for-jetform')
                ]);
            } else {

                wp_send_json_success([
                    'message' => __('Plugin already installed and up to date', 'gsheetconnector-for-jetform')
                ]);
            }
        }

        $result = $upgrader->install($download_url);

        if (is_wp_error($result)) {
            wp_send_json_error([
                'message' => __('Installation failed: ', 'gsheetconnector-for-jetform') . $result->get_error_message()
            ]);
        }

        wp_send_json_success([
            'message' => __('Plugin installed successfully', 'gsheetconnector-for-jetform')
        ]);
    }

    /**
     * Activates a plugin via AJAX using the provided plugin slug.
     *
     * @access public
     * @since 1.0.0
     */

    public function gshfjf_activate_plugin()
    {
        if (! check_ajax_referer('gshfjf-ajax-nonce', 'security', false)) {
            wp_send_json_error(array(
                'message' => __('Invalid security token', 'gsheetconnector-for-jetform')
            ));
        }

        if (! current_user_can('activate_plugins')) {
            wp_send_json_error(array(
                'message' => __('You do not have permission to activate plugin', 'gsheetconnector-for-jetform')
            ));
        }

        if (empty($_POST['plugin_slug'])) {
            wp_send_json_error(array(
                'message' => __('Plugin slug is missing', 'gsheetconnector-for-jetform')
            ));
        }

        $plugin_slug = sanitize_text_field(wp_unslash($_POST['plugin_slug']));
        if (! function_exists('activate_plugin')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        if (is_plugin_active($plugin_slug)) {
            wp_send_json_success(array(
                'message' => __('Plugin is already activated', 'gsheetconnector-for-jetform')
            ));
        }

        $result = activate_plugin($plugin_slug);

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

        wp_send_json_success(array(
            'message' => __('Plugin activated successfully', 'gsheetconnector-for-jetform')
        ));
    }
}
$GSHFJF_JetForm_Extensions = new GSHFJF_JetForm_Extensions();
