<?php

declare(strict_types=1);

namespace WPUltimateSecurity\UltimateSecurity\Support\Helpers;

use WP_Error;
use WPUltimateSecurity\UltimateSecurity\Support\Helpers\DateHelper;

class SaltHelper
{
    public static function rewrite_wp_config_keys()
    {
        // Include the required WordPress file for WP_Filesystem
        if (!function_exists('WP_Filesystem')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        // Initialize WP_Filesystem
        global $wp_filesystem;
        if (!WP_Filesystem()) {
            return new WP_Error('filesystem_not_initialized', __('WP_Filesystem could not be initialized.', 'ultimate-security'));
        }

        // Fetch keys from WordPress API or generate offline
        $keys_and_salts = self::ultimate_security_fetch_or_generate_keys();
        $new_salts = explode("\n", $keys_and_salts);


        $salts_array = [
            "'AUTH_KEY'",
            "'SECURE_AUTH_KEY'",
            "'LOGGED_IN_KEY'",
            "'NONCE_KEY'",
            "'AUTH_SALT'",
            "'SECURE_AUTH_SALT'",
            "'LOGGED_IN_SALT'",
            "'NONCE_SALT'",
        ];

        $config_file = ABSPATH . 'wp-config.php';
        $tmp_config_file = ABSPATH . 'wp-config-tmp.php';

        // Read the wp-config.php file
        if (!$wp_filesystem->exists($config_file)) {
            return new WP_Error('config_file_not_found', __('wp-config.php file does not exist.', 'ultimate-security'));
        }

        $config_contents = $wp_filesystem->get_contents($config_file);
        if ($config_contents === false) {
            return new WP_Error('read_failed', __('Failed to read wp-config.php.', 'ultimate-security'));
        }

        // Modify the contents
        $config_lines = explode("\n", $config_contents);
        $new_config_contents = '';

        foreach ($config_lines as $line) {
            $updated = false;
            foreach ($salts_array as $salt_key => $salt_value) {
                if (stristr($line, $salt_value)) {
                    if (isset($new_salts[$salt_key]))
                        $line = $new_salts[$salt_key];
                    else {
                        echo esc_html($salt_key);
                    }
                    $updated = true;
                    break;
                }
            }
            $new_config_contents .= $line . "\n";
        }

        // Write to the temporary wp-config-tmp.php file
        if (!$wp_filesystem->put_contents($tmp_config_file, $new_config_contents, FS_CHMOD_FILE)) {
            return new WP_Error('write_failed', __('Failed to write temporary wp-config file.', 'ultimate-security'));
        }

        // Rename the temporary file to wp-config.php
        if (!$wp_filesystem->move($tmp_config_file, $config_file, true)) {
            return new WP_Error('rename_failed', __('Failed to replace wp-config.php with updated version.', 'ultimate-security'));
        }

        // Update option and delete cookies
        update_option('ultimate_security_rewrite_wp_config_keys_last_date', DateHelper::now());

        self::ultimate_security_delete_cookie("ultimate-security-force-reset-hide");
        self::ultimate_security_delete_cookie("ultimate-security-next-cron-hide");

        return true;
    }

    public static function ultimate_security_delete_cookie($cookie_name)
    {
        if (isset($_COOKIE[$cookie_name])) {
            // Set the cookie's expiration date to a past time
            setcookie($cookie_name, '', time() - 3600, '/'); // The '/' ensures the cookie is deleted site-wide
            unset($_COOKIE[$cookie_name]); // Optional: Unset the cookie from the global $_COOKIE array
        }
    }

    public static function ultimate_security_fetch_or_generate_keys()
    {
        // Try fetching keys from the WordPress API
        $response = wp_remote_get('https://api.wordpress.org/secret-key/1.1/salt/');

        if (
            is_wp_error($response) ||
            wp_remote_retrieve_response_code($response) !== 200 ||
            empty(wp_remote_retrieve_body($response)) ||
            strpos(wp_remote_retrieve_body($response), '404 Not Found') !== false
        ) {
            $response = wp_remote_get(home_url('/wp-json/ultimate-security/v1/salt'));
        }
        return wp_remote_retrieve_body($response);
    }

    /**
     * Write specific salt keys to wp-config.php (used for rollback)
     *
     * @param array $keys Associative array of key name => key value
     * @return bool|WP_Error
     */
    public static function ultimate_security_write_config_keys($keys)
    {
        // Include the required WordPress file for WP_Filesystem
        if (!function_exists('WP_Filesystem')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        // Initialize WP_Filesystem
        global $wp_filesystem;
        if (!WP_Filesystem()) {
            return new WP_Error('filesystem_not_initialized', __('WP_Filesystem could not be initialized.', 'ultimate-security'));
        }

        $config_file = ABSPATH . 'wp-config.php';
        $tmp_config_file = ABSPATH . 'wp-config-tmp.php';

        // Read the wp-config.php file
        if (!$wp_filesystem->exists($config_file)) {
            return new WP_Error('config_file_not_found', __('wp-config.php file does not exist.', 'ultimate-security'));
        }

        $config_contents = $wp_filesystem->get_contents($config_file);
        if ($config_contents === false) {
            return new WP_Error('read_failed', __('Failed to read wp-config.php.', 'ultimate-security'));
        }

        // Replace each key in the config
        foreach ($keys as $key_name => $key_value) {
            // Escape single quotes in the key value
            $escaped_value = str_replace("'", "\\'", $key_value);

            // Pattern to match the define statement for this key
            $pattern = "/define\s*\(\s*['\"]" . preg_quote($key_name, '/') . "['\"]\s*,\s*['\"].*?['\"]\s*\)/";
            $replacement = "define('" . $key_name . "', '" . $escaped_value . "')";

            $config_contents = preg_replace($pattern, $replacement, $config_contents);
        }

        // Write to the temporary wp-config-tmp.php file
        if (!$wp_filesystem->put_contents($tmp_config_file, $config_contents, FS_CHMOD_FILE)) {
            return new WP_Error('write_failed', __('Failed to write temporary wp-config file.', 'ultimate-security'));
        }

        // Rename the temporary file to wp-config.php
        if (!$wp_filesystem->move($tmp_config_file, $config_file, true)) {
            return new WP_Error('rename_failed', __('Failed to replace wp-config.php with updated version.', 'ultimate-security'));
        }

        // Update option
        update_option('ultimate_security_rewrite_wp_config_keys_last_date', DateHelper::now());

        self::ultimate_security_delete_cookie("ultimate-security-force-reset-hide");
        self::ultimate_security_delete_cookie("ultimate-security-next-cron-hide");

        return true;
    }
}