<?php
/**
 * wp-config.php protection: toggle DISALLOW_FILE_MODS and DISALLOW_FILE_EDIT.
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class Flavor_Protection {

    private static $constants = [
        'DISALLOW_FILE_MODS',
        'DISALLOW_FILE_EDIT',
    ];

    /**
     * Toggle protection constants in wp-config.php.
     *
     * @param bool $enable  true to add protection, false to remove.
     * @return true|string  True on success, error message on failure.
     */
    public static function toggle( $enable ) {
        $config_path = ABSPATH . 'wp-config.php';

        if ( ! file_exists( $config_path ) ) {
            $config_path = dirname( ABSPATH ) . '/wp-config.php';
        }

        if ( ! file_exists( $config_path ) || ! is_writable( $config_path ) ) {
            return 'wp-config.php not found or not writable';
        }

        $content = file_get_contents( $config_path );
        if ( $content === false ) {
            return 'cannot read wp-config.php';
        }

        foreach ( self::$constants as $const ) {
            $content = preg_replace(
                '/^\s*define\s*\(\s*[\'"]' . preg_quote( $const, '/' ) . '[\'"]\s*,\s*[^)]+\)\s*;\s*$/m',
                '',
                $content
            );
        }

        $content = preg_replace( '/\n{3,}/', "\n\n", $content );

        if ( $enable ) {
            $marker  = "/* That's all, stop editing!";
            $defines = "\n// Flavor protection\n";
            foreach ( self::$constants as $const ) {
                $defines .= "define('{$const}', true);\n";
            }

            $pos = strpos( $content, $marker );
            if ( $pos !== false ) {
                $content = substr_replace( $content, $defines . "\n", $pos, 0 );
            } else {
                $content = preg_replace(
                    '/(require_once\s+ABSPATH\s*\.\s*[\'"]wp-settings\.php[\'"])/i',
                    $defines . "\n$1",
                    $content,
                    1
                );
            }
        }

        $result = file_put_contents( $config_path, $content );
        if ( $result === false ) {
            return 'cannot write wp-config.php';
        }

        return true;
    }
}
