<?php

namespace FleekDash\Core;

/**
 * Shared wp-config.php constant read/write helpers for debug settings.
 * Extracted from DebugController and WpConfigController (DRY).
 */
class WpConfigConstantEditor
{
    /**
     * Update a define() line in wp-config.php content.
     *
     * @param string $content wp-config.php content
     * @param string $constant Constant name (e.g. WP_DEBUG)
     * @param bool $value Constant value
     * @return string Updated content
     */
    public static function updateConstantInConfig($content, $constant, $value)
    {
        $valueStr = $value ? 'true' : 'false';
        $pattern = "/define\s*\(\s*['\"]" . preg_quote($constant, '/') . "['\"]\s*,\s*[^)]+\s*\)\s*;/i";
        $newDefinition = "define('{$constant}', {$valueStr});";
        $stopEditingPattern = "/\/\*\s*That's all, stop editing.*?\*\//i";

        return match (true) {
            (bool) preg_match($pattern, $content) => preg_replace($pattern, $newDefinition, $content),
            (bool) preg_match($stopEditingPattern, $content) => preg_replace(
                $stopEditingPattern,
                $newDefinition . "\n\n/* That's all, stop editing! Happy publishing. */",
                $content,
            ),
            strpos($content, '?>') !== false => str_replace('?>', $newDefinition . "\n?>", $content),
            default => $content . "\n" . $newDefinition . "\n",
        };
    }

    /**
     * Set WP_DEBUG, WP_DEBUG_LOG, and WP_DEBUG_DISPLAY in wp-config.php.
     *
     * @param bool $wpDebugValue Value for WP_DEBUG
     * @param bool $wpDebugLogValue Value for WP_DEBUG_LOG
     * @return bool Success status
     */
    public static function applyDebugModeConstants($wpDebugValue, $wpDebugLogValue)
    {
        try {
            if (!class_exists('FleekDash\\Controllers\\WpConfigController')) {
                require_once FLEEKDASH_PLUGIN_DIR . 'includes/Controllers/WpConfigController.php';
            }

            $wpConfigController = new \FleekDash\Controllers\WpConfigController();

            if (!$wpConfigController->isWpConfigWritable()) {
                fleekdash_log_error('FleekDash Debug: wp-config.php is not writable. Cannot update debug constants.');
                return false;
            }

            $wpConfigPath = ABSPATH . 'wp-config.php';
            $configContent = file_get_contents($wpConfigPath);
            if ($configContent === false) {
                throw new DebugException('Failed to read wp-config.php file.');
            }

            $backupPath = $wpConfigPath . '.backup-' . date('Y-m-d-H-i-s');
            file_put_contents($backupPath, $configContent);

            $configContent = self::updateConstantInConfig($configContent, 'WP_DEBUG', $wpDebugValue);
            $configContent = self::updateConstantInConfig($configContent, 'WP_DEBUG_LOG', $wpDebugLogValue);
            $configContent = self::updateConstantInConfig($configContent, 'WP_DEBUG_DISPLAY', false);

            if (file_put_contents($wpConfigPath, $configContent) === false) {
                throw new DebugException('Failed to write to wp-config.php file.');
            }

            if (function_exists('opcache_invalidate')) {
                opcache_invalidate($wpConfigPath, true);
            }

            return true;
        } catch (\Exception $e) {
            fleekdash_log_error('FleekDash Debug: Error updating wp-config.php constants - ' . $e->getMessage());
            return false;
        }
    }
}
