<?php

namespace WPD_Platform;

/**
 * Class EarlyLoad
 *
 * Handles early loading functionality for the platform, including plugin disabling
 * for specific actions and Login.
 *
 * @since 1.0.0
 */
class EarlyLoad
{
    /**
     * Run early loading checks and actions.
     *
     * This method checks for specific conditions that require disabling plugins
     * and filters the active plugins list accordingly.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public static function run()
    {
        $disable_plugins = false;

        // Check for platform-specific actions
        if (! empty($_GET['wpd-platform'])) {
            // Get request body
            $raw_json = file_get_contents('php://input');
            $body = json_decode($raw_json);

            // Disable plugins for specific actions
            if (isset($body->action) && in_array($body->action, ['login_token', 'export_db'])) {
                $disable_plugins = true;
            }
        }

        // Check for Login token
        if (isset($_GET['s5token'])) {
            $disable_plugins = true;
        }

        // If no need to disable plugins, return early
        if (! $disable_plugins) {
            return;
        }

        // Filter active plugins to only include essential platform plugins
        add_filter('option_active_plugins', function ($plugins) {
            // List of essential platform plugins that should remain active
            $platform_plugins = [
                'platform/platform.php',
                'advanced-custom-fields/acf.php',
                'advanced-custom-fields-pro/acf.php',
            ];

            // Filter plugins to only include platform essentials
            $final_plugins = [];
            foreach ($plugins as $plugin) {
                if (in_array($plugin, $platform_plugins)) {
                    $final_plugins[] = $plugin;
                }
            }

            return $final_plugins;
        });
    }
}
