<?php
declare(strict_types=1);

namespace Bdp\Libs;

class WpConfigEditor extends \WP_Filesystem_Direct
{
    public const WP_CONFIG_FILE = '/wp-config.php';

    public function __construct($arg = null)
    {
        if (!defined('FS_CHMOD_FILE')) {
            define('FS_CHMOD_FILE', (fileperms(ABSPATH . 'index.php') & 0777 | 0644));
        }
    }

    public function readConfig(): string
    {
        if (!$this->exists(ABSPATH . self::WP_CONFIG_FILE)) {
            return '';
        }

        return $this->get_contents(ABSPATH . self::WP_CONFIG_FILE);
    }

    public function writeConfig($value): bool
    {
	    $value = str_replace('<?php', '', $value);
	    $value = str_replace('<?', '', $value);
		$value = str_replace('?>', '', $value);

	    $value = str_replace(PHP_EOL . PHP_EOL, PHP_EOL, $value);

		$value = '<?php' . PHP_EOL . $value;
		$this->put_contents(ABSPATH . self::WP_CONFIG_FILE, $value);
        return true;
    }

    public static function updateConfig($key, $value): bool
    {
        $wfs = new self();
        $configContent = $wfs->readConfig();

        if (null === self::getConfigValue($key)) {
            $configContent .= "define( '$key', $value );" . PHP_EOL;
        }

        preg_match("/define\([ ]?'($key)'\,[ ]?(.*)[ ]?\);/",$configContent, $matches);
        $configContent = str_replace($matches[0], "define( '$key', $value );", $configContent);
        return $wfs->writeConfig($configContent);
    }

    public static function getConfigValue($key): ?string
    {
        $wfs = new self();
        $configContent = $wfs->readConfig();

        preg_match("/define\([ ]?'($key)'\,[ ]?(.*)[ ]?\);/",$configContent, $matches);
        if (count($matches) == 0) {
            return null;
        }

        return trim($matches[2]);
    }

    public static function updateSiteKeys(string $newKeySet)
    {
        foreach (explode(PHP_EOL, trim($newKeySet)) as $currentKeyLine) {
            preg_match("/define\([ ]?'(.*)'\,[ ]?(.*)[ ]?\);/", $currentKeyLine, $matches);
            self::updateConfig($matches[1], trim($matches[2]));
        }

        return true;
    }

    public static function deleteConfigKey($key): bool
    {
        if (null === self::getConfigValue($key)) {
            return true;
        }

        $wfs = new self();
        $configContent = $wfs->readConfig();

        preg_match("/define\([ ]?'($key)'\,[ ]?(.*)[ ]?\);/",$configContent, $matches);
        $configContent = str_replace($matches[0], '', $configContent);
        return $wfs->writeConfig($configContent);
    }
}