<?php

/**
 * ESSB Add-ons Handler
 * 
 * Handles retrieval and caching of add-ons from the ESSB API
 * 
 * @package EasySocialShareButtons
 * @since 11.0
 */

class ESSB_Addons_Helper {

    public static function get_tmga_addons() {
        $api_list = ESSB_MyAddons_API::get_free_addons_basic();
        $plugins = array();

        foreach ($api_list as $addon) {
            $source = $addon['source'];
            $source = str_replace('{activationKey}', '', $source);
            $source = str_replace('{domain}', esc_url(ESSBActivationManager::getSiteURL()), $source);

            $addon['source'] = $source;
            $plugins[] = $addon;
        }

        return $plugins;
    }
}

function essb_map_addons_to_tmga() {
    $plugins = ESSB_Addons_Helper::get_tmga_addons();

    /*
     * Array of configuration settings. Amend each line as needed.
     *
     * TGMPA will start providing localized text strings soon. If you already have translations of our standard
     * strings available, please help us make TGMPA even better by giving us access to these translations or by
     * sending in a pull-request with .po file(s) with the translations.
     *
     * Only uncomment the strings in the config array if you want to customize the strings.
     */
    $config = array(
        'id'           => 'essb',                 // Unique ID for hashing notices for multiple instances of TGMPA.
        'default_path' => '',                      // Default absolute path to bundled plugins.
        'menu'         => 'essb_redirect_addons', // Menu slug.
        'parent_slug'  => 'essb_options',            // Parent menu slug.
        'capability'   => 'manage_options',    // Capability needed to view plugin install page, should be a capability associated with the parent menu used.
        'has_notices'  => false,                    // Show admin notices or not.
        'dismissable'  => true,                    // If false, a user cannot dismiss the nag message.
        'dismiss_msg'  => '',                      // If 'dismissable' is false, this message will be output at top of nag.
        'is_automatic' => false,                   // Automatically activate plugins after installation or not.
        'message'      => '',                      // Message to output right before the plugins table.
        'strings' => array(
            'page_title' => 'Add-Ons',
            'menu_title' => 'Add-Ons'
        )
        
    );    
    
    essb_tgmpa( $plugins, $config );
}

/**
 * Generate an array of all site plugins
 * @return unknown[][]|NULL[][]
 */
function essb_get_site_plugins() {
    $plugins = get_plugins();
    
    $r = array();
    
    foreach ($plugins as $key => $data) {
        $key_path = explode('/', $key);
        $slug = $key_path[0];
        
        $r[$slug] = array(
            'name' => $data['Name'],
            'version' => $data['Version'],
            'description' => $data['Description'],
            'pluginURL' => $data['PluginURI'],
            'author' => $data['AuthorName'],
            'path' => $key,
            'active' => is_plugin_active( $key )
        );
    }
    
    return $r;
}

/**
 * Map a wizard button slug to the actual API addon slug.
 *
 * @param string $slug The wizard slug (e.g. 'ai-social-booster').
 * @return string The API addon slug (e.g. 'essb-ai-booster').
 */
function essb_addon_wizard_to_api_slug($slug) {
    $map = array(
        'ai-social-booster' => 'essb-ai-booster',
        'shorty'            => 'shorty-essb-addon',
        'social-chat'       => 'essb-social-chat',
    );
    return isset($map[$slug]) ? $map[$slug] : $slug;
}

/**
 * Get the activation state of a known free addon by wizard slug.
 *
 * @param string $slug The wizard addon slug.
 * @return string 'active', 'installed', or 'not_installed'
 */
function essb_addon_get_state($slug) {
    switch ($slug) {
        case 'ai-social-booster':
            $active = defined('ESSB_AI_BOOSTER_VERSION');
            break;
        case 'shorty':
            $active = defined('SHORTY_VERSION');
            break;
        case 'social-chat':
            $active = defined('ESSC_VERSION');
            break;
        default:
            $active = false;
    }

    if ($active) {
        return 'active';
    }

    $api_slug = essb_addon_wizard_to_api_slug($slug);
    if (is_dir(WP_PLUGIN_DIR . '/' . $slug) || is_dir(WP_PLUGIN_DIR . '/' . $api_slug)) {
        return 'installed';
    }

    return 'not_installed';
}

/**
 * AJAX handler: install and activate a free addon from the wizard.
 */
function essb_ajax_install_free_addon() {
    check_ajax_referer('essb_install_free_addon', 'nonce');

    if (!current_user_can('install_plugins')) {
        wp_send_json_error(array('message' => 'You do not have permission to install plugins.'));
    }

    $slug = isset($_POST['slug']) ? sanitize_key($_POST['slug']) : '';
    if (empty($slug)) {
        wp_send_json_error(array('message' => 'No addon slug provided.'));
    }

    $api_slug = essb_addon_wizard_to_api_slug($slug);

    // If already active, return success immediately
    if (essb_addon_get_state($slug) === 'active') {
        wp_send_json_success(array('already_active' => true));
    }

    $plugin_path = '';
    $plugins = get_plugins();
    foreach ($plugins as $path => $data) {
        if (strpos($path, $slug . '/') === 0 || strpos($path, $api_slug . '/') === 0) {
            $plugin_path = $path;
            break;
        }
    }

    // If folder exists on disk but not active, just activate
    if (!empty($plugin_path) || is_dir(WP_PLUGIN_DIR . '/' . $slug) || is_dir(WP_PLUGIN_DIR . '/' . $api_slug)) {
        if (!empty($plugin_path)) {
            $result = activate_plugin($plugin_path);
            if (is_wp_error($result)) {
                wp_send_json_error(array('message' => $result->get_error_message()));
            }
            wp_send_json_success(array('activated' => true));
        }
        wp_send_json_error(array('message' => 'Plugin folder found but cannot determine the main plugin file.'));
    }

    // Fetch addon info from API with fallback URLs
    $source = '';

    if (!class_exists('ESSB_MyAddons_API')) {
        include_once ESSB3_PLUGIN_ROOT . 'lib/classes/admin/class-my-api-addons.php';
    }

    $addon = ESSB_MyAddons_API::get_addon_by_slug($api_slug);
    if ($addon && !empty($addon['download'])) {
        $source = $addon['download'];
    }

    // Fallback URLs if API is unavailable or missing the addon
    if (empty($source)) {
        $fallback_urls = array(
            'shorty-essb-addon' => 'https://get.socialsharingplugin.com/?activationKey={activationKey}&domain={domain}&download=shorty-essb-addon',
            'essb-ai-booster'   => 'https://get.socialsharingplugin.com/?activationKey={activationKey}&domain={domain}&download=essb-ai-booster',
            'essb-social-chat'  => 'https://get.socialsharingplugin.com/?activationKey={activationKey}&domain={domain}&download=essb-social-chat',
        );
        if (isset($fallback_urls[$api_slug])) {
            $source = $fallback_urls[$api_slug];
        }
    }

    if (empty($source)) {
        wp_send_json_error(array('message' => 'Unable to retrieve addon information. Please try the Add-Ons tab.'));
    }

    $source = str_replace('{activationKey}', 'freemius', $source);
    $source = str_replace('{domain}', urlencode(get_site_url()), $source);

    // Include required WP files
    if (!class_exists('Plugin_Upgrader')) {
        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
    }
    if (!function_exists('get_plugins')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }
    require_once ABSPATH . 'wp-admin/includes/file.php';

    // Install
    $skin = new WP_Ajax_Upgrader_Skin();
    $upgrader = new Plugin_Upgrader($skin);
    $result = $upgrader->install($source);

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

    if (!$result) {
        $errors = $skin->get_errors();
        if (!empty($errors)) {
            wp_send_json_error(array('message' => $errors->get_error_message()));
        }
        wp_send_json_error(array('message' => 'Installation failed. Please try the Add-Ons tab.'));
    }

    // Find and activate the newly installed plugin
    $plugins = get_plugins();
    $activated = false;
    foreach ($plugins as $path => $data) {
        if (strpos($path, $slug . '/') === 0 || strpos($path, $api_slug . '/') === 0) {
            $result = activate_plugin($path);
            if (!is_wp_error($result)) {
                $activated = true;
            }
            break;
        }
    }

    if ($activated) {
        wp_send_json_success(array('installed' => true));
    }

    wp_send_json_success(array('installed' => true, 'activate_failed' => true));
}