<?php

namespace FleekDash\Core;

use WP_REST_Request;
use WP_REST_Response;

/**
 * Debug mode status GET/POST handlers.
 * Extracted from DebugController for S1448 compliance.
 */
class DebugStatusHandler
{
    private const DEBUG_LOGGER_CLASS = 'FleekDash\\Core\\DebugLogger';

    private const MSG_BY_USER_ID = ' by user ID ';

    /** @var DebugLogService */
    private $logService;

    public function __construct(DebugLogService $logService)
    {
        $this->logService = $logService;
    }

    /**
     * @return WP_REST_Response
     */
    public function getDebugStatus()
    {
        try {
            $wpDebug = defined('WP_DEBUG') ? WP_DEBUG : false;
            $wpDebugLog = defined('WP_DEBUG_LOG') ? WP_DEBUG_LOG : false;

            return new WP_REST_Response([
                'success' => true,
                'data' => [
                    'enabled' => (bool) $wpDebug,
                    'wp_debug' => (bool) $wpDebug,
                    'wp_debug_log' => (bool) $wpDebugLog,
                    'source' => 'wp-config',
                    'hide_php_notices' => $this->resolveHidePhpNotices(),
                ],
            ], 200);
        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash Debug: Error in get_debug_status - ' . $e->getMessage());

            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error retrieving debug status: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * @param WP_REST_Request $request
     * @return WP_REST_Response
     */
    public function updateDebugStatus(WP_REST_Request $request)
    {
        try {
            $enabled = $this->parseEnabledParam($request->get_param('enabled'));
            $clearLog = $request->get_param('clear_log') !== false;

            if ($clearLog) {
                $this->logService->clearDebugLog();
            }

            if ($enabled) {
                WpConfigConstantEditor::applyDebugModeConstants(true, true);
                $action = 'enabled (WP_DEBUG and WP_DEBUG_LOG activated, WP_DEBUG_DISPLAY set to false in wp-config.php)';
            } else {
                WpConfigConstantEditor::applyDebugModeConstants(false, false);
                $action = 'disabled (WP_DEBUG and WP_DEBUG_LOG deactivated, WP_DEBUG_DISPLAY set to false in wp-config.php)';
            }

            \delete_option('fleekdash_force_debug');

            fleekdash_log_info('FleekDash Debug: Debug mode ' . ($enabled ? 'enabled' : 'disabled') .
                self::MSG_BY_USER_ID . \get_current_user_id() . ' - ' . $action .
                ($clearLog ? ' (debug.log cleared)' : ''));

            \do_action('fleekdash_debug_mode_changed', !$enabled, $enabled);

            $wpDebug = defined('WP_DEBUG') ? WP_DEBUG : false;
            $wpDebugLog = defined('WP_DEBUG_LOG') ? WP_DEBUG_LOG : false;

            return new WP_REST_Response([
                'success' => true,
                'message' => 'Debug mode ' . ($enabled ? 'enabled' : 'disabled') . ' successfully' .
                    ($clearLog ? ' and debug.log cleared' : ''),
                'data' => [
                    'enabled' => $enabled,
                    'wp_debug' => (bool) $wpDebug,
                    'wp_debug_log' => (bool) $wpDebugLog,
                    'source' => 'wp-config',
                    'log_cleared' => $clearLog,
                ],
            ], 200);
        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash Debug: Error in update_debug_status - ' . $e->getMessage());

            return new WP_REST_Response([
                'success' => false,
                'message' => 'Error updating debug status: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * @param mixed $enabled
     */
    private function parseEnabledParam($enabled)
    {
        if (is_string($enabled)) {
            return $enabled === 'true' || $enabled === '1';
        }

        return (bool) $enabled;
    }

    /**
     * @return bool
     */
    private function resolveHidePhpNotices()
    {
        if (class_exists(self::DEBUG_LOGGER_CLASS)) {
            return DebugLogger::isPhpNoticesSuppressed();
        }

        $option = \get_option('fleekdash_hide_php_notices', true);
        if (is_string($option)) {
            return $option === '1' || $option === 'true';
        }

        return (bool) $option;
    }
}
