<?php

namespace WtbFirewall\Admin;

// Prevent direct access.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Denne klassen holder metoder for å håndtere alle GET/POST request i admin grensenittet.
 */
class GetPostActions {

    public function __construct() {
        // Register the handler for the admin-post action
        add_action('admin_post_install_firewall', [$this, 'InstallFirewall']);
        add_action('admin_post_firewall_mode', [$this, 'FirewallMode']);
        add_action('admin_post_firewall_log', [$this, 'FirewallLog']);
        add_action('admin_post_firewall_uninstall_setting', [$this, 'FirewallUninstallSetting']);
        add_action('admin_post_firewall_manually_write_rules', [$this, 'FirewallManuallyWriteRules']);
        add_action('admin_post_firewall_proxy_settings', [$this, 'FirewallProxySettings']);
        add_action('admin_post_wtb_firewall_add_rule', [$this, 'FirewallAddRule']);
        add_action('admin_post_wtb_firewall_delete_rule', [$this, 'FirewallDeleteRule']);
        add_action('admin_post_wtb_firewall_enable_rule', [$this, 'FirewallEnableRule']);
        add_action('admin_post_wtb_firewall_disable_rule', [$this, 'FirewallDisableRule']);
        add_action('admin_post_wtb_firewall_bulk_action', [$this, 'FirewallBulkAction']);
        add_action('admin_post_wtb_firewall_add_country_rule', [$this, 'FirewallAddCountryRule']);
        add_action('admin_post_wtb_firewall_country_delete_rule', [$this, 'FirewallCountryDeleteRule']);
        add_action('admin_post_wtb_firewall_country_disable_rule', [$this, 'FirewallCountryDisableRule']);
        add_action('admin_post_wtb_firewall_country_enable_rule', [$this, 'FirewallCountryEnableRule']);
        add_action('admin_post_wtb_auto_protect_block_authentication', [$this, 'AutoProtectBlockAuthentication']);
        add_action('admin_post_wtb_firewall_delete_auto_rule', [$this, 'AutoProtectDeleteRule']);
        add_action('admin_post_wtb_firewall_permanent_auto_rule', [$this, 'AutoProtectPermanentRule']);
        add_action('admin_post_wtb_firewall_bulk_auto_protect_rules', [$this, 'AutoProtectBulkEdit']);
        add_action('admin_post_wtb_firewall_rate_limit', [$this, 'RateLimit']);
        add_action('admin_post_wtb_traffic_log', [$this, 'TrafficLog']);
    }

    /**
     * Sender redirect til oppgitt side sammen med resultatet.
     * 
     * @param type $result Resultat kode for standard tilbakemelding til bruker.
     * @param type $resultMsg Resultat melding for standard tilbakemelding til bruker.
     * @param type $slug Slug for siden vi skal sende redirect til.
     */
    private function sendRedirect(int $result, string $resultMsg, string $slug) {
        $url = add_query_arg(
                array(
                    'page' => $slug,
                    'result' => $result,
                    'resultMsg' => $resultMsg,
                ),
                admin_url('admin.php')
        );

        //Redirect til resultat siden.
        wp_redirect($url);
        exit;
    }

    /**
     * Håndterer GET request "install_firewall"
     */
    public function InstallFirewall() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_install', 'wtb_firewall_nonce');

        // Unslash + validate install (only allow 0 or 1)
        $installRaw = isset($_GET['install']) ? wp_unslash($_GET['install']) : null;
        $install = is_scalar($installRaw) ? (int) $installRaw : -1;

        if (!in_array($install, [0, 1], true)) {
            $this->sendRedirect(1, 'Invalid request.', 'wtb-firewall');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        if ($install === 1) {
            //Installer firewall            
            if ($firewall->installFirewall()) {
                $this->sendRedirect(0, 'The firewall was succesfully installed. It may take a few minutes for the firewall to start blocking/allowing connections.', 'wtb-firewall');
            } else {
                $this->sendRedirect(1, 'There was a problem installing the firewall.', 'wtb-firewall');
            }
        } else if ($install === 0) {
            //Avinstaller firewall            
            if ($firewall->removeFirewall()) {
                $this->sendRedirect(0, 'The firewall was succesfully uninstalled.', 'wtb-firewall');
            } else {
                $this->sendRedirect(1, 'There was a problem uninstalling the firewall.', 'wtb-firewall');
            }
        }
    }

    /**
     * Håndterer POST request for "firewall_mode".
     */
    public function FirewallMode() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_mode', 'wtb_firewall_nonce');

        $blockModeRaw = isset($_POST['block_mode']) ? wp_unslash($_POST['block_mode']) : null;
        $blockMode = is_scalar($blockModeRaw) ? (int) $blockModeRaw : 0;

        // Whitelist allowed values only
        if (!in_array($blockMode, [1, 2], true)) {
            $this->sendRedirect(1, 'Invalid firewall mode selected.', 'wtb-firewall');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall;

        \WtbFirewall\Config\FirewallConfig::$blockMode = $blockMode;
        \WtbFirewall\Config\FirewallConfig::saveOptions();
        $firewall->writeFirewallConfig();

        $msg = ($blockMode === 1) ? 'Block mode has been switched to ALLOW ALL.' : 'Block mode has been switched to DENY ALL.';

        $this->sendRedirect(0, $msg, 'wtb-firewall');
    }

    /**
     * Håndterer POST request for "firewall_log"
     */
    public function FirewallLog() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_log_time', 'wtb_firewall_nonce');

        $logDays = 30; //Default verdi.

        if (isset($_POST['log_days'])) {
            $raw = wp_unslash($_POST['log_days']);

            if (is_scalar($raw)) {
                $value = (int) $raw;

                $allowed = [0, 7, 14, 30, 90];

                if (in_array($value, $allowed, true)) {
                    $logDays = $value;
                }
            }
        }

        $log = new \WtbFirewall\Firewall\Log();
        $log->deleteLogEntries($logDays);

        \WtbFirewall\Config\FirewallConfig::$logDays = $logDays;
        \WtbFirewall\Config\FirewallConfig::saveOptions();

        $this->sendRedirect(0, 'Firewall log settings has been updated.', 'wtb-firewall');
    }

    /**
     * Håndterer POST request for å sette innstilling for hva som skal gjøre ved avinstallering.
     */
    public function FirewallUninstallSetting() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_uninstall_behavior', 'wtb_firewall_nonce');

        if (!isset($_POST['uninstall_mode'])) {
            $this->sendRedirect(1, 'Invalid firewall setting provided.', 'wtb-firewall');
            return;
        }

        $raw = wp_unslash($_POST['uninstall_mode']);
        $mode = is_scalar($raw) ? (int) $raw : 0;

        if (!in_array($mode, [1, 2], true)) {
            $this->sendRedirect(1, 'Invalid firewall setting provided.', 'wtb-firewall');
            return;
        }

        \WtbFirewall\Config\FirewallConfig::$deleteOnUninstall = ($mode === 1); // 1=delete all, 2=do not delete
        \WtbFirewall\Config\FirewallConfig::saveOptions();

        $this->sendRedirect(0, 'Firewall uninstall settings has been updated.', 'wtb-firewall');
    }

    /**
     * Håndterer POST request for å skrive alle firewall regler til fil.
     */
    public function FirewallManuallyWriteRules() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_write_rules', 'wtb_firewall_nonce');

        $firewall = new \WtbFirewall\Firewall\Firewall();

        $result = $firewall->writeManualRulesToFile() && $firewall->writeCountryRulesToFile() && $firewall->writeAutoRulesToFile();

        if ($result) {
            $this->sendRedirect(0, 'Success! Firewall rules were written to file.', 'wtb-firewall');
        } else {
            $this->sendRedirect(1, 'Error! Could not write rules to file.', 'wtb-firewall');
        }
    }

    /**
     * Håndterer POST request for å legge inn en ny firewall regel.
     */
    public function FirewallAddRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_add_rule', 'wtb_firewall_nonce');

        //Sanitize data fra form.
        $form = array();
        $form['ruleAction'] = isset($_POST['rule_action']) ? sanitize_text_field(wp_unslash($_POST['rule_action'])) : '';
        $form['ipInput'] = isset($_POST['ip_input']) ? sanitize_text_field(wp_unslash($_POST['ip_input'])) : '';
        $form['ruleScope'] = isset($_POST['rule_scope']) ? sanitize_text_field(wp_unslash($_POST['rule_scope'])) : '';
        $form['ruleDuration'] = isset($_POST['rule_duration']) ? sanitize_text_field(wp_unslash($_POST['rule_duration'])) : '';
        $form['ruleNote'] = isset($_POST['rule_note']) ? sanitize_textarea_field(wp_unslash($_POST['rule_note'])) : '';
        $form['ruleEnabled'] = isset($_POST['rule_enabled']) ? 1 : 0;

        //Sjekk at oppgitt regel handling er gyldig.
        if ($form['ruleAction'] != 'allow' && $form['ruleAction'] != 'block') {
            //Hverken block eller allow. Burde egentlig ikke skje.
            $this->sendRedirect(1, 'Firewall rule was not saved due to an unexpected error. Error code 01.', 'wtb-firewall-rules');
        }

        //Sjekk at oppgitt IP for regel er gyldig.
        $firewall = new \WtbFirewall\Firewall\Firewall();
        $ip = $firewall->parseIpv4Input($form['ipInput']);

        if (is_string($ip)) {
            //Oppgitt IP er ikke IPv4, prøv IPv6.
            $ip = $firewall->parseIpv6Input($form['ipInput']);
            if (is_string($ip)) {
                //Hverken IPv4 eller IPv6.
                $this->sendRedirect(1, 'Invalid IP address format.', 'wtb-firewall-rules');
            }
        }

        //Dersom varighet er midlertidig sjekk at dato/varighet for regel er gyldig.
        if ($form['ruleScope'] == 'temporary') {
            $time = $firewall->validateRuleDuration($form['ruleDuration']);
            if ($time === null || !is_string($time)) {
                //Oppgitt varighet er ugyldig.
                $this->sendRedirect(1, 'Invalid rule duration! Accepted format is 15m OR 24h OR 7d.', 'wtb-firewall-rules');
            }
        } else if ($form['ruleScope'] == 'permanent') {
            //Dersom regel er permanent skal det ikke være noe utløpsdato.
            $time = null;
        } else {
            //Regel er hverken 'permanent' eller 'temporary', dette er feil. Burde egentlig ikke kunne skje.
            $this->sendRedirect(1, 'Firewall rule was not saved due to an unexpected error. Error code 02.', 'wtb-firewall-rules');
        }

        //Sjekk at ruleEnabled er satt til gyldig verdi.
        if ($form['ruleEnabled'] != 1 && $form['ruleEnabled'] != 0) {
            //Ugyldig verdi. Burde egentlig ikke kunne skje.
            $this->sendRedirect(1, 'Firewall rule was not saved due to an unexpected error. Error code 03.', 'wtb-firewall-rules');
        }

        //Sjekk at evetuelt note er gyldig. Dvs ikke over 255 tegn. Truncate i så fall.
        if (mb_strlen($form['ruleNote'], 'UTF-8') > 255) {
            $form['ruleNote'] = mb_substr($form['ruleNote'], 0, 255, 'UTF-8');
        }

        //Lagre regelen i databasen.
        if (isset($ip['ipv6'])) {
            //IPv6 regel.
            if (!$firewall->saveIpv6Rule($ip, $form['ruleAction'], $form['ruleNote'], $form['ruleEnabled'], $time)) {
                $this->sendRedirect(1, 'Rule not saved! There was a problem saving the rule to the database.', 'wtb-firewall-rules');
            }
        } else {
            //IPv4 regel.
            if (!$firewall->saveIpv4Rule($ip, $form['ruleAction'], $form['ruleNote'], $form['ruleEnabled'], $time)) {
                $this->sendRedirect(1, 'Rule not saved! There was a problem saving the rule to the database.', 'wtb-firewall-rules');
            }
        }


        if ($firewall->writeManualRulesToFile()) {
            $this->sendRedirect(0, 'Rule added. The firewall rule was saved successfully.', 'wtb-firewall-rules');
        } else {
            $this->sendRedirect(1, 'There was a problem writing the rules to file.', 'wtb-firewall-rules');
        }
    }

    /**
     * Håndterer GET request for å slette en firewall regel.
     * 
     */
    public function FirewallDeleteRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_delete_rule', 'wtb_firewall_nonce');

        $ruleID = 0;
        if (isset($_GET['rule_id'])) {
            $ruleID = absint(wp_unslash($_GET['rule_id']));
        }

        if ($ruleID <= 0) {
            $this->sendRedirect(1, 'Rule not deleted! Invalid ID provided.', 'wtb-firewall-rules');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        if (!$firewall->deleteFirewallRule($ruleID)) {
            $this->sendRedirect(1, 'Rule not deleted! There was a problem deleting the firewall rule.', 'wtb-firewall-rules');
        }

        if ($firewall->writeManualRulesToFile()) {
            $this->sendRedirect(0, 'Rule deleted! The firewall rule was successfully deleted.', 'wtb-firewall-rules');
        } else {
            $this->sendRedirect(1, 'Rule deleted from database. But there was a problem writing the updated rules to file.', 'wtb-firewall-rules');
        }
    }

    /**
     * Håndterer GET request for å aktivere en firewall regel.
     * 
     */
    public function FirewallEnableRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_enable_rule', 'wtb_firewall_nonce');

        $ruleID = 0;
        if (isset($_GET['rule_id'])) {
            $ruleID = absint(wp_unslash($_GET['rule_id']));
        }

        if ($ruleID <= 0) {
            $this->sendRedirect(1, 'Rule not enabled! Invalid ID provided.', 'wtb-firewall-rules');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        if (!$firewall->enableDisableFirewallRule($ruleID, 1)) {
            $this->sendRedirect(1, 'Rule not enabled! There was a problem enabling the firewall rule.', 'wtb-firewall-rules');
        }

        if ($firewall->writeManualRulesToFile()) {
            $this->sendRedirect(0, 'Rule enabled! The firewall rule was successfully enabled.', 'wtb-firewall-rules');
        } else {
            $this->sendRedirect(1, 'There was a problem writing the updated firewall rule to disk.', 'wtb-firewall-rules');
        }
    }

    /**
     * Håndterer GET request for å deaktivere en firewall regel.
     * 
     */
    public function FirewallDisableRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_disable_rule', 'wtb_firewall_nonce');

        $ruleID = 0;
        if (isset($_GET['rule_id'])) {
            $ruleID = absint(wp_unslash($_GET['rule_id']));
        }

        if ($ruleID <= 0) {
            $this->sendRedirect(1, 'Rule not disabled! Invalid ID provided.', 'wtb-firewall-rules');
            return;
        }


        $firewall = new \WtbFirewall\Firewall\Firewall();

        if (!$firewall->enableDisableFirewallRule($ruleID, 0)) {
            $this->sendRedirect(1, 'Rule not disabled! There was a problem disabling the firewall rule.', 'wtb-firewall-rules');
        }

        if ($firewall->writeManualRulesToFile()) {
            $this->sendRedirect(0, 'Rule disabled! The firewall rule was successfully disabled.', 'wtb-firewall-rules');
        } else {
            $this->sendRedirect(1, 'There was a problem writing the updated firewall rule to disk.', 'wtb-firewall-rules');
        }
    }

    /**
     * Håndterer POST request for å utføre bulk actions.
     * 
     */
    public function FirewallBulkAction() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_bulk_action', 'wtb_firewall_nonce');

        $bulkAction = '';
        if (isset($_POST['bulk_action'])) {
            $bulkAction = sanitize_key(wp_unslash((string) $_POST['bulk_action']));
        }

        $allowedBulkActions = array('enable', 'disable', 'delete');
        if (!in_array($bulkAction, $allowedBulkActions, true)) {
            $this->sendRedirect(1, 'Bulk action not performed. Invalid action selected.', 'wtb-firewall-rules');
            return;
        }

        $ruleIDsRaw = array();
        if (isset($_POST['rule_ids'])) {
            $ruleIDsRaw = (array) wp_unslash($_POST['rule_ids']);
        }

        $ruleIDs = array_values(array_filter(
                        array_map('absint', $ruleIDsRaw),
                        static function (int $id): bool {
                            return $id > 0;
                        }
                ));

        if (empty($ruleIDs)) {
            $this->sendRedirect(1, 'Bulk action not performed. No rules selected.', 'wtb-firewall-rules');
            return;
        }

        $ruleCount = 0;
        $firewall = new \WtbFirewall\Firewall\Firewall();

        foreach ($ruleIDs as $rule) {
            $ruleCount++;

            switch ($bulkAction) {
                case 'delete':
                    $firewall->deleteFirewallRule($rule);
                    break;
                case 'enable':
                    $firewall->enableDisableFirewallRule($rule, true);
                    break;
                case 'disable':
                    $firewall->enableDisableFirewallRule($rule, false);
                    break;

                default:
                    $this->sendRedirect(1, 'Invalid bulk action.', 'wtb-firewall-rules');
            }
        }

        $firewall->writeManualRulesToFile();

        $this->sendRedirect(0, 'Bulk action performed, ' . $ruleCount . ' rules affected.', 'wtb-firewall-rules');
    }

    /**
     * Håndterer POST request for å legge til ny regel for et land.
     */
    public function FirewallAddCountryRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_add_country_rule', 'wtb_firewall_nonce');

        //Sanitize data fra form.
        $form = array();
        $form['ruleAction'] = isset($_POST['rule_action']) ? sanitize_text_field(wp_unslash($_POST['rule_action'])) : '';
        $form['country'] = isset($_POST['country']) ? sanitize_text_field(wp_unslash($_POST['country'])) : '';

        $countryList = include WTB_FIREWALL_PATH . 'Admin/CountryList.php';
        if (!isset($countryList[$form['country']])) {
            $this->sendRedirect(1, 'Invalid country code selected: ' . $form['country'], 'wtb-firewall-country');
        }

        if ($form['ruleAction'] != 'allow' && $form['ruleAction'] != 'block') {
            $this->sendRedirect(1, 'Invalid action selected: ' . $form['ruleAction'], 'wtb-firewall-country');
        }


        $firewall = new \WtbFirewall\Firewall\Firewall();
        $countryRules = $firewall->getCountryRules();

        //Sjekk at vi ikke allerede har en regel for dette landet.
        if ($countryRules === null) {
            $this->sendRedirect(1, 'New firewall rule not saved. There was a problem accessing the database.', 'wtb-firewall-country');
        }

        foreach ($countryRules as $rule) {
            if ($rule['description'] == $form['country']) {
                $this->sendRedirect(1, 'A firewall rule already exists for the chosen country.', 'wtb-firewall-country');
            }
        }

        //Lagre ny regel i databasen.
        if (!$firewall->saveCountryRule($form['country'], $form['ruleAction'])) {
            $this->sendRedirect(1, 'The firewall rule not saved. There was a problem writing to the database.', 'wtb-firewall-country');
        }

        $firewall->countryRulesScheduling();
        $this->sendRedirect(0, 'New firewall rule has been saved for country ' . $form['country'] . '.', 'wtb-firewall-country');
    }

    /**
     * Håndterer GET request for å slette firewall regel for et land.
     */
    public function FirewallCountryDeleteRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_delete_country', 'wtb_firewall_nonce');

        $ruleID = 0;
        if (isset($_GET['rule_id'])) {
            $ruleID = absint(wp_unslash($_GET['rule_id']));
        }

        if ($ruleID <= 0) {
            $this->sendRedirect(1, 'Rule not deleted! Invalid ID provided.', 'wtb-firewall-country');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        if (!$firewall->deleteFirewallRule($ruleID)) {
            $this->sendRedirect(1, 'Rule not deleted! There was a problem deleting the country rule.', 'wtb-firewall-country');
        }

        $firewall->countryRulesScheduling();
        $this->sendRedirect(0, 'Rule deleted! The country rule was successfully deleted.', 'wtb-firewall-country');
    }

    /**
     * Håndterer GET request for å deaktivere en regel for et land.
     */
    public function FirewallCountryDisableRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_disable_country', 'wtb_firewall_nonce');

        $ruleID = 0;
        if (isset($_GET['rule_id'])) {
            $ruleID = absint(wp_unslash($_GET['rule_id']));
        }

        if ($ruleID <= 0) {
            $this->sendRedirect(1, 'Rule not disabled! Invalid ID provided.', 'wtb-firewall-country');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        if (!$firewall->enableDisableFirewallRule($ruleID, false)) {
            $this->sendRedirect(1, 'Rule not disabled! There was a problem disabling the country rule.', 'wtb-firewall-country');
        }

        $firewall->countryRulesScheduling();
        $this->sendRedirect(0, 'Rule disabled! The country rule was successfully disabled.', 'wtb-firewall-country');
    }

    /**
     * Håndterer GET request for å aktivere en regel for et land.
     */
    public function FirewallCountryEnableRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_enable_country', 'wtb_firewall_nonce');

        $ruleID = 0;
        if (isset($_GET['rule_id'])) {
            $ruleID = absint(wp_unslash($_GET['rule_id']));
        }

        if ($ruleID <= 0) {
            $this->sendRedirect(1, 'Rule not enabled! Invalid ID provided.', 'wtb-firewall-country');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        if (!$firewall->enableDisableFirewallRule($ruleID, true)) {
            $this->sendRedirect(1, 'Rule not enabled! There was a problem enabling the country rule.', 'wtb-firewall-country');
        }

        $firewall->countryRulesScheduling();
        $this->sendRedirect(0, 'Rule enabled! The country rule was successfully enabled.', 'wtb-firewall-country');
    }

    /**
     * Håndterer GET request for oppdatering av settings for auto blokkering ved mislykkete autentiserings forsøk.
     */
    public function AutoProtectBlockAuthentication() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_auto_protect', 'wtb_firewall_nonce');

        \WtbFirewall\Config\FirewallConfig::$autoProtectAuth['enabled'] = (
                isset($_POST['auth_auto_block_enabled']) &&
                (string) wp_unslash($_POST['auth_auto_block_enabled']) === '1'
        );

        \WtbFirewall\Config\FirewallConfig::$autoProtectAuth['wpLogin'] = (
                isset($_POST['auth_auto_block_wp_login']) &&
                (string) wp_unslash($_POST['auth_auto_block_wp_login']) === '1'
        );

        \WtbFirewall\Config\FirewallConfig::$autoProtectAuth['XMLRPC'] = (
                isset($_POST['auth_auto_block_xmlrpc']) &&
                (string) wp_unslash($_POST['auth_auto_block_xmlrpc']) === '1'
        );

        $attempts = isset($_POST['auth_auto_block_threshold']) ? absint(wp_unslash($_POST['auth_auto_block_threshold'])) : 0;
        \WtbFirewall\Config\FirewallConfig::$autoProtectAuth['attempts'] = ($attempts >= 1) ? $attempts : 15;

        $timeSpan = isset($_POST['auth_time_span']) ? absint(wp_unslash($_POST['auth_time_span'])) : 0;
        \WtbFirewall\Config\FirewallConfig::$autoProtectAuth['timeSpan'] = ($timeSpan >= 1) ? $timeSpan : 60;

        $blockTime = isset($_POST['auth_auto_block_duration']) ? absint(wp_unslash($_POST['auth_auto_block_duration'])) : 0;
        \WtbFirewall\Config\FirewallConfig::$autoProtectAuth['blockTime'] = ($blockTime >= 1) ? $blockTime : 12;

        $timeSpanUnit = isset($_POST['time_span_unit']) ? sanitize_key(wp_unslash((string) $_POST['time_span_unit'])) : '';
        \WtbFirewall\Config\FirewallConfig::$autoProtectAuth['timeSpanUnit'] = in_array(
                        $timeSpanUnit,
                        array('minutes', 'hours', 'days'),
                        true
                ) ? $timeSpanUnit : 'minutes';

        $blockTimeUnit = isset($_POST['block_time_unit']) ? sanitize_key(wp_unslash((string) $_POST['block_time_unit'])) : '';
        \WtbFirewall\Config\FirewallConfig::$autoProtectAuth['blockTimeUnit'] = in_array(
                        $blockTimeUnit,
                        array('minutes', 'hours', 'days'),
                        true
                ) ? $blockTimeUnit : 'hours';

        \WtbFirewall\Config\FirewallConfig::saveOptions();

        $this->sendRedirect(0, 'Authentication settings successfully updated!', 'wtb-firewall-auto-protection');
    }

    /**
     * Håndterer GET request for å slette en automatisk regel.
     */
    public function AutoProtectDeleteRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_delete_auto_rule', 'wtb_firewall_nonce');

        $ruleID = isset($_GET['rule_id']) ? absint(wp_unslash($_GET['rule_id'])) : 0;

        if ($ruleID <= 0) {
            $this->sendRedirect(1, 'Rule not deleted! Invalid ID provided.', 'wtb-firewall-auto-protection-rules');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        if (!$firewall->deleteFirewallRule($ruleID)) {
            $this->sendRedirect(1, 'Rule not deleted! There was a problem deleting the firewall rule.', 'wtb-firewall-auto-protection-rules');
        }

        //Ettersom vi har endret reglene lag regel filen på nytt.
        $firewall->autoRulesScheduling();

        $this->sendRedirect(0, 'Rule deleted! The firewall rule was successfully deleted.', 'wtb-firewall-auto-protection-rules');
    }

    /**
     * Håndterer GET request for å gjøre en automatisk regel permanent.
     */
    public function AutoProtectPermanentRule() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_permanent_auto_rule', 'wtb_firewall_nonce');

        $ruleID = isset($_GET['rule_id']) ? absint(wp_unslash($_GET['rule_id'])) : 0;

        if ($ruleID <= 0) {
            $this->sendRedirect(1, 'Rule not updated! Invalid ID provided.', 'wtb-firewall-auto-protection-rules');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        $rule = $firewall->getRule($ruleID);

        if ($rule == null) {
            $this->sendRedirect(1, 'Rule not updated! Invalid ID provided.', 'wtb-firewall-auto-protection-rules');
        }

        //Oppdater regel slik at den blir til en permanent manuel regel.
        if (!$firewall->makeTempRulePermanent($rule)) {
            $this->sendRedirect(1, 'Rule not updated! There was a problem making the rule permanent.', 'wtb-firewall-auto-protection-rules');
        }

        //Skriv regel filene på nytt.
        $firewall->writeManualRulesToFile();
        $firewall->autoRulesScheduling();

        $this->sendRedirect(0, 'Success! The rule was made permanent.', 'wtb-firewall-auto-protection-rules');
    }

    /**
     * Håndter POST request for bulk edit av automatiske firewall regler.
     */
    public function AutoProtectBulkEdit() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_bulk_auto_protect_rules', 'wtb_firewall_nonce');

        //Sanitize bulk action
        $bulkAction = isset($_POST['bulk_action']) ? sanitize_key(wp_unslash((string) $_POST['bulk_action'])) : '';

        $allowedActions = array(
            'bulk_delete',
            'bulk_make_permanent',
        );

        if (!in_array($bulkAction, $allowedActions, true)) {
            $this->sendRedirect(1, 'Invalid bulk action selected.', 'wtb-firewall-auto-protection-rules');
            return;
        }

        // Sanitize IDs
        $ruleIdsRaw = (array) wp_unslash($_POST['rule_ids'] ?? array());

        $ruleIds = array_values(array_filter(
                        array_map('absint', $ruleIdsRaw),
                        static function (int $id): bool {
                            return $id > 0;
                        }
                ));

        if (!$ruleIds) {
            $this->sendRedirect(1, 'No rules selected for bulk editing.', 'wtb-firewall-auto-protection-rules');
            return;
        }

        $firewall = new \WtbFirewall\Firewall\Firewall();

        foreach ($ruleIds as $ruleId) {

            switch ($bulkAction) {

                case 'bulk_delete':
                    $firewall->deleteFirewallRule($ruleId);
                    break;

                case 'bulk_make_permanent':
                    $rule = $firewall->getRule($ruleId);

                    if ($rule != null) {
                        $firewall->makeTempRulePermanent($rule);
                    }
                    break;
            }
        }

        //Skriv regel filene på nytt.
        $firewall->writeManualRulesToFile();
        $firewall->autoRulesScheduling();

        $this->sendRedirect(0, 'Success! The selected bulk action was performed.', 'wtb-firewall-auto-protection-rules');
    }

    /**
     * Håndterer POST request for oppdatere proxy innstillingene.
     */
    public function FirewallProxySettings() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_proxy_support', 'wtb_firewall_nonce');

        //Enabled        
        $proxyEnabledRaw = isset($_POST['proxy_enabled']) ? wp_unslash($_POST['proxy_enabled']) : '';
        $proxyEnabled = is_scalar($proxyEnabledRaw) && (string) $proxyEnabledRaw === '1';

        $allowedHeaders = array(
            'auto',
            'x_forwarded_for',
            'x_real_ip',
            'forwarded',
            'cf_connecting_ip',
            'true_client_ip',
            'x_client_ip',
        );

        //Proxy Header
        $proxyHeader = isset($_POST['proxy_header']) ? sanitize_key((string) $_POST['proxy_header']) : 'x_forwarded_for';
        if (!in_array($proxyHeader, $allowedHeaders, true)) {
            $proxyHeader = 'x_forwarded_for';
        }

        $rawList = isset($_POST['trusted_proxies']) ? (string) $_POST['trusted_proxies'] : '';
        $rawList = str_replace(array("\r\n", "\r"), "\n", $rawList);

        $trustedRaw = isset($_POST['trusted_proxies']) ? wp_unslash($_POST['trusted_proxies']) : '';
        $rawList = is_scalar($trustedRaw) ? sanitize_textarea_field((string) $trustedRaw) : '';
        $rawList = str_replace(["\r\n", "\r"], "\n", $rawList);

        //Liste over alle tillatte proxy servere.
        $proxyList = array_filter(array_map('trim', explode("\n", $rawList)));

        //Gå gjennom $proxyList.
        //Validerer og "gjør om" alle proxy IP.
        $firewall = new \WtbFirewall\Firewall\Firewall();
        $proxyIpv4 = [];
        $proxyIpv6 = [];

        foreach ($proxyList as $proxyServer) {

            $proxy = $firewall->parseIpv4Input($proxyServer);
            if (is_array($proxy)) {
                //IPv4 proxy.
                $proxyIpv4[] = $proxy;
            } else {
                $proxy = $firewall->parseIpv6Input($proxyServer);
                if (is_array($proxy)) {
                    //IPv6 proxy.
                    $proxyIpv6[] = $proxy;
                } else {
                    //Ugyldig proxy server IP
                    $this->sendRedirect(1, 'Invalid proxy server IP: ' . $proxyServer, 'wtb-firewall');
                }
            }
        }

        \WtbFirewall\Config\FirewallConfig::$proxyServer['enabled'] = $proxyEnabled;
        \WtbFirewall\Config\FirewallConfig::$proxyServer['header'] = $proxyHeader;
        \WtbFirewall\Config\FirewallConfig::$proxyServer['proxyListIpv4'] = $proxyIpv4;
        \WtbFirewall\Config\FirewallConfig::$proxyServer['proxyListIpv6'] = $proxyIpv6;

        \WtbFirewall\Config\FirewallConfig::saveOptions();

        $firewall->writeFirewallConfig();

        $this->sendRedirect(0, 'Proxy server setttings updated.', 'wtb-firewall');
    }

    /**
     * Håndterer POST request for sette rate limiting og 404 monitor innstillinger.
     */
    public function RateLimit() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_rate_limit', 'wtb_firewall_nonce');

        \WtbFirewall\Config\FirewallConfig::$rateLimit['enabled'] = (
                isset($_POST['rate_limit_enabled']) &&
                (string) wp_unslash($_POST['rate_limit_enabled']) === '1'
        );

        \WtbFirewall\Config\FirewallConfig::$rateLimit['errors404Enabled'] = (
                isset($_POST['rate_limit_404_enabled']) &&
                (string) wp_unslash($_POST['rate_limit_404_enabled']) === '1'
        );

        $requestsPerMinute = isset($_POST['rate_limit_requests_per_minute']) ? absint(wp_unslash($_POST['rate_limit_requests_per_minute'])) : 0;
        \WtbFirewall\Config\FirewallConfig::$rateLimit['requestsPerMinute'] = ($requestsPerMinute >= 1) ? $requestsPerMinute : 120;

        $blockMinutes = isset($_POST['rate_limit_block_minutes']) ? absint(wp_unslash($_POST['rate_limit_block_minutes'])) : 0;
        \WtbFirewall\Config\FirewallConfig::$rateLimit['blockMinutes'] = ($blockMinutes >= 1) ? $blockMinutes : 10;

        $errors404PerMinute = isset($_POST['rate_limit_404_per_minute']) ? absint(wp_unslash($_POST['rate_limit_404_per_minute'])) : 0;
        \WtbFirewall\Config\FirewallConfig::$rateLimit['errors404PerMinute'] = ($errors404PerMinute >= 1) ? $errors404PerMinute : 20;

        $errors404BlockMinutes = isset($_POST['rate_limit_404_block_minutes']) ? absint(wp_unslash($_POST['rate_limit_404_block_minutes'])) : 0;
        \WtbFirewall\Config\FirewallConfig::$rateLimit['errors404BlockMinutes'] = ($errors404BlockMinutes >= 1) ? $errors404BlockMinutes : 15;

        \WtbFirewall\Config\FirewallConfig::saveOptions();

        $this->sendRedirect(0, 'Rate limit settings successfully updated!', 'wtb-firewall-auto-protection');
    }

    /**
     * Håndterer POST request for å konfigurere Traffic Log innstillinger.
     */
    public function TrafficLog() {
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        check_admin_referer('wtb_firewall_traffic_log', 'wtb_firewall_nonce');

        \WtbFirewall\Config\FirewallConfig::$trafficLog['enabled'] = (
                isset($_POST['traffic_log_enabled']) &&
                (string) wp_unslash($_POST['traffic_log_enabled']) === '1'
        );

        \WtbFirewall\Config\FirewallConfig::$trafficLog['ignoreUsers'] = (
                isset($_POST['ignore_users']) &&
                (string) wp_unslash($_POST['ignore_users']) === '1'
        );

        \WtbFirewall\Config\FirewallConfig::$trafficLog['ignoreDashboard'] = (
                isset($_POST['ignore_dashboard']) &&
                (string) wp_unslash($_POST['ignore_dashboard']) === '1'
        );

        $logDays = isset($_POST['log_days']) ? absint(wp_unslash($_POST['log_days'])) : 0;
        \WtbFirewall\Config\FirewallConfig::$trafficLog['logDays'] = ($logDays >= 1) ? $logDays : 30;

        \WtbFirewall\Config\FirewallConfig::saveOptions();

        $this->sendRedirect(0, 'Traffic Log settings successfully updated!', 'wtb-firewall-traffic-log');
    }
}
