<?php

namespace FleekDash\Core;

use FleekDash\Core\DebugException;
use WP_REST_Request;
use WP_REST_Response;

/**
 * Handles debug utility endpoints: MU cleanup, activation runner, PHP notices.
 * Extracted from DebugController for S1448 compliance (method count).
 */
class DebugUtilityHandler
{
    private const DEBUG_LOGGER_CLASS = 'FleekDash\\Core\\DebugLogger';

    private const MSG_BY_USER_ID = ' by user ID ';

    /**
     * Get legacy MU plugin cleanup status
     *
     * @return WP_REST_Response
     */
    public function getMuCleanupStatus()
    {
        try {
            if (!class_exists('FleekDash\\Core\\LegacyMUPluginCleaner')) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/LegacyMUPluginCleaner.php';
            }

            $status = \FleekDash\Core\LegacyMUPluginCleaner::get_status();

            return new WP_REST_Response([
                'success' => true,
                'data' => $status,
            ], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error getting MU cleanup status - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to get cleanup status: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Run legacy MU plugin cleanup
     *
     * @return WP_REST_Response
     */
    public function runMuCleanup()
    {
        try {
            if (!class_exists('FleekDash\\Core\\LegacyMUPluginCleaner')) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/LegacyMUPluginCleaner.php';
            }

            $result = \FleekDash\Core\LegacyMUPluginCleaner::force_cleanup();

            return new WP_REST_Response([
                'success' => true,
                'message' => sprintf(
                    'Cleanup completed: %d file(s) and %d directory(ies) removed',
                    count($result['files'] ?? []),
                    count($result['directories'] ?? [])
                ),
                'data' => $result,
            ], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error running MU cleanup - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to run cleanup: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get activation pipeline status
     *
     * @return WP_REST_Response
     */
    public function getActivationStatus()
    {
        try {
            if (!class_exists('FleekDash\\Core\\ActivationRunner')) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/ActivationRunner.php';
            }

            $status = \FleekDash\Core\ActivationRunner::getStatus();

            return new WP_REST_Response([
                'success' => true,
                'data' => $status,
            ], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error getting activation status - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to get activation status: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Manually trigger activation runner
     *
     * @return WP_REST_Response
     */
    public function triggerActivationRunner()
    {
        try {
            if (!class_exists('FleekDash\\Core\\ActivationRunner')) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/ActivationRunner.php';
            }

            $status = \FleekDash\Core\ActivationRunner::triggerManually();

            return new WP_REST_Response([
                'success' => true,
                'message' => 'Activation runner triggered manually',
                'data' => $status,
            ], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error triggering activation runner - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to trigger activation runner: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get PHP notices suppression settings
     *
     * @return WP_REST_Response
     */
    public function getPhpNoticesSettings()
    {
        try {
            if (!class_exists(self::DEBUG_LOGGER_CLASS)) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/DebugLogger.php';
            }

            $hide_notices = \FleekDash\Core\DebugLogger::isPhpNoticesSuppressed();

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'hide_php_notices' => $hide_notices,
                    'description' => 'Reduces routine diagnostic noise in debug.log when enabled.',
                    'suppressed_types' => [
                        'E_DEPRECATED' => 'PHP deprecation warnings',
                        'E_USER_DEPRECATED' => 'User-generated deprecation warnings',
                        'E_NOTICE' => 'Run-time notices (undefined variables, etc.)',
                        'E_USER_NOTICE' => 'User-generated notice messages',
                    ],
                ],
            ], 200);
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error getting PHP notices settings - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to get PHP notices settings: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Update PHP notices suppression settings
     *
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function updatePhpNoticesSettings(WP_REST_Request $request)
    {
        try {
            if (!class_exists(self::DEBUG_LOGGER_CLASS)) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/DebugLogger.php';
            }

            $hide_notices = $request->get_param('hide_php_notices');

            if (is_string($hide_notices)) {
                $hide_notices = $hide_notices === 'true' || $hide_notices === '1';
            } else {
                $hide_notices = (bool) $hide_notices;
            }

            $success = \FleekDash\Core\DebugLogger::setPhpNoticesSuppression($hide_notices);

            if ($success) {
                if (function_exists('fleekdash_log_info')) {
                    fleekdash_log_info('FleekDash Debug: PHP notices suppression ' .
                        ($hide_notices ? 'enabled' : 'disabled') .
                        self::MSG_BY_USER_ID . \get_current_user_id());
                }
                return new WP_REST_Response([
                    'success' => true,
                    'message' => 'PHP notices suppression ' . ($hide_notices ? 'enabled' : 'disabled') . ' successfully',
                    'data' => [
                        'hide_php_notices' => $hide_notices,
                    ],
                ], 200);
            }
            throw new DebugException('Failed to save setting');
        } catch (\Exception $e) {
            if (function_exists('fleekdash_log_error')) {
                fleekdash_log_error('FleekDash Debug: Error updating PHP notices settings - ' . $e->getMessage());
            }
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Failed to update PHP notices settings: ' . $e->getMessage(),
            ], 500);
        }
    }
}
