<?php
/**
 * AJAX handler for plugin-related functionality.
 *
 * @package SEO_Pro_Stack
 * @subpackage SEO_Pro_Stack/Admin/Settings/AJAX
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * AJAX handler for plugins.
 */
class SEOProStack_AJAX_Plugins {

    /**
     * Get list of installed plugins.
     */
    public function get_plugins() {
        // Check nonce
        if (!check_ajax_referer('seoprostack-nonce', 'nonce', false)) {
            wp_send_json_error('Invalid security token sent.');
            return;
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error('You do not have permission to view plugins.');
            return;
        }

        $installed_plugins = get_plugins();
        $active_plugins = get_option('active_plugins');
        $plugin_list = array();

        // Create the plugins array
        foreach ($installed_plugins as $path => $plugin) {
            // Skip the SEO Pro Stack plugin
            if (strpos($path, 'wp-seoprostack-plugin') !== false) {
                continue;
            }

            $is_active = in_array($path, $active_plugins);
            $plugin_slug = explode('/', $path)[0];

            $plugin_list[] = array(
                'name' => $plugin['Name'],
                'slug' => $plugin_slug,
                'version' => $plugin['Version'],
                'active' => $is_active,
                'path' => $path
            );
        }

        // Sort plugins alphabetically
        usort($plugin_list, function ($a, $b) {
            return strcasecmp($a['name'], $b['name']);
        });

        wp_send_json_success($plugin_list);
    }
}