<?php

namespace WtbFirewall\Admin;

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

/**
 * Hovedklasse for admin grensesnittet.
 */
class AdminMain {

    private $pageHooks = [];

    public function __construct() {
        $this->Start();
    }

    public function Start() {
        require_once 'Includes.php';

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

        //Admin menyen.
        \add_action('admin_menu', [$this, 'createAdminMenu']);

        \add_action('admin_enqueue_scripts', [$this, 'enqueueScripts']);

        //Registrer alle GET/POST actions.
        new GetPostActions();

        //For å vise eventuell tilbake melding fra firewall installert .htaccess
        add_action('admin_notices', [$this, 'firewallStatusMsg']);
    }

    /**
     * Oppretter meny i admin sidebar.
     */
    public function createAdminMenu() {

        //Top level.
        $this->pageHooks[] = \add_menu_page(
                'WTB Firewall', // Page title
                'WTB Firewall', // Menu title
                'manage_options', // Capability
                'wtb-firewall', // Menu slug
                [$this, 'pageFirewall'], // Callback function
                'dashicons-shield-alt', // Icon
        );

        //Firewall side.
        $this->pageHooks[] = \add_submenu_page(
                'wtb-firewall', // Parent slug (same as top-level)
                'Firewall', // Page title
                'Firewall', // Submenu title
                'manage_options', // Capability
                'wtb-firewall', // Slug
                [$this, 'pageFirewall']              // Callback function
        );

        //Denne siden brukes til å legge til/endre og vise firewall regler.
        $this->pageHooks[] = \add_submenu_page(
                'wtb-firewall', // Parent slug (same as top-level)
                'Firewall Rules', // Page title
                'Firewall Rules', // Submenu title
                'manage_options', // Capability
                'wtb-firewall-rules', // Slug
                [$this, 'pageFirewallRules']              // Callback function
        );

        //Blokkering av land siden.
        $this->pageHooks[] = \add_submenu_page(
                'wtb-firewall', // Parent slug (same as top-level)
                'Country Rules', // Page title
                'Country Rules', // Submenu title
                'manage_options', // Capability
                'wtb-firewall-country', // Slug
                [$this, 'pageFirewallCountry']              // Callback function
        );

        //Automatic Protection siden.
        $this->pageHooks[] = \add_submenu_page(
                'wtb-firewall', // Parent slug (same as top-level)
                'Automatic Protection', // Page title
                'Automatic Protection', // Submenu title
                'manage_options', // Capability
                'wtb-firewall-auto-protection', // Slug
                [$this, 'pageAutomaticProtection']              // Callback function
        );

        //Automatic Protection regel listen. Vises ikke i menyen.
        $this->pageHooks[] = \add_submenu_page(
                '',
                'Automatically Added Rules', // Page title
                'Automatically Added Rules', // Submenu title
                'manage_options', // Capability
                'wtb-firewall-auto-protection-rules', // Slug
                [$this, 'pageAutomaticProtectionRules']              // Callback function
        );

        //Log siden.
        $this->pageHooks[] = \add_submenu_page(
                'wtb-firewall', // Parent slug (same as top-level)
                'Firewall Log', // Page title
                'Firewall Log', // Submenu title
                'manage_options', // Capability
                'wtb-firewall-log', // Menu slug (same as parent to override main page)
                [$this, 'pageLog']              // Callback function
        );

        //Traffic Log siden.
        /*        
        $this->pageHooks[] = \add_submenu_page(
                'wtb-firewall', // Parent slug (same as top-level)
                'Traffic Log', // Page title
                'Traffic Log', // Submenu title
                'manage_options', // Capability
                'wtb-firewall-traffic-log', // Slug
                [$this, 'pageTrafficLog']              // Callback function
        );         
        */

        //Quickstart dokumentasjon siden.
        $this->pageHooks[] = \add_submenu_page(
                'wtb-firewall', // Parent slug (same as top-level)
                'QuickStart Guide', // Page title
                'QuickStart Guide', // Submenu title
                'manage_options', // Capability
                'wtb-firewall-quickstart', // Slug
                [$this, 'pageQuickStartDocs']              // Callback function
        );
    }

    public function enqueueScripts($hook) {

        if (!in_array($hook, $this->pageHooks, true)) {
            return;
        }

        wp_enqueue_style('wtb-firewall-admin-css', plugin_dir_url(__FILE__) . 'Styles.css');
    }

    /**
     * Håndterer hovedsiden for Firewall.
     */
    public function pageFirewall() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have permission to access this page.');
        }

        //Sjekk om firewall er installert i .htaccess.
        $firewall = new \WtbFirewall\Firewall\Firewall();

        $vars = array();

        $nonce = wp_create_nonce('wtb_firewall_install');

        //Hent eventuell sucess/error melding.
        $vars['msg'] = $this->GetResultMsg();

        //Lag HTML/text basert på om firewall er installert eller ikke.
        if ($firewall->isInstalled()) {
            //Firewall er installert.
            $vars['firewallStatus'] = '<span class="wtb-status-label wtb-status-active">Installed &amp; Running</span>';

            $uninstallUrl = add_query_arg(
                    array(
                        'action' => 'install_firewall',
                        'install' => '0',
                        'wtb_firewall_nonce' => $nonce,
                    ),
                    admin_url('admin-post.php')
            );

            $vars['firewallInstall'] = '<a href="' . esc_url($uninstallUrl) . '" class="button button-primary">Uninstall firewall.</a>';
        } else {
            //Firewall er ikke installert.
            $vars['firewallStatus'] = '<span class="wtb-status-label wtb-status-inactive">Not Installed</span>';

            $installUrl = add_query_arg(
                    array(
                        'action' => 'install_firewall',
                        'install' => '1',
                        'wtb_firewall_nonce' => $nonce,
                    ),
                    admin_url('admin-post.php')
            );

            $vars['firewallInstall'] = '<a href="' . esc_url($installUrl) . '" class="button button-primary">Install firewall.</a>';
        }

        //Global mode, allow all/deny all.
        $vars['blockMode'] = \WtbFirewall\Config\FirewallConfig::$blockMode;

        //Hvor lenge loggen skal lagres.
        $vars['logDays'] = \WtbFirewall\Config\FirewallConfig::$logDays;

        //Hva som skal skje ved avinstallering av plugin.
        $vars['uninstallBehavior'] = \WtbFirewall\Config\FirewallConfig::$deleteOnUninstall;

        /*
         * Proxy server innstillinger.
         */
        $vars['proxyEnabled'] = \WtbFirewall\Config\FirewallConfig::$proxyServer['enabled'];
        $vars['proxyHeader'] = \WtbFirewall\Config\FirewallConfig::$proxyServer['header'];

        //Listen over proxy servere.
        $vars['proxyList'] = '';

        foreach (\WtbFirewall\Config\FirewallConfig::$proxyServer['proxyListIpv4'] as $ip) {
            $vars['proxyList'] .= \WtbFirewall\Helpers\IpHelper::ipv4BinaryToString($ip) . "\n";
        }

        foreach (\WtbFirewall\Config\FirewallConfig::$proxyServer['proxyListIpv6'] as $ip) {
            $vars['proxyList'] .= \WtbFirewall\Helpers\IpHelper::ipv6BinaryToString($ip['ipv6'], $ip['prefix']) . "\n";
        }

        $render = new \WtbFirewall\Views\Render;
        $render->render(WTB_FIREWALL_PATH . 'Views/FirewallPage.php', $vars);
    }

    /**
     * Denne siden lar bruker legge til, endre og vise eksisterende firewall regler.
     */
    public function pageFirewallRules() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have permission to access this page.');
        }

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

        $vars = array();

        $vars['msg'] = $this->GetResultMsg();

        //Hent ut alle regler lagt manuelt inn av bruker.
        $rules = $firewall->getManualRules();

        if ($rules == null) {
            //Feil ved henting av regler fra database.
            $vars['ruleList'] = '';
        } else if (empty($rules)) {
            //Ingen regler å vise.
            $vars['ruleList'] = '';
        } else {
            $vars['ruleList'] = $this->pageFireWallRulesList($rules, $firewall);
        }


        $render = new \WtbFirewall\Views\Render;

        $render->render(WTB_FIREWALL_PATH . 'Views/FirewallRulesPage.php', $vars);
    }

    /**
     * Sjekker om vi har fått en tilbake melding via GET.
     * Denne meldingen vises som en Success/Error box i wordpress.
     * 
     * GET parmatere: resultMsg=melding, result= 0 (success melding) 1 (error melding)
     * 
     * @return string Meldingen med HTML klar til å settes inn på siden.
     * Tom string '' dersom ingen melding.
     */
    private function GetResultMsg(): string {

        if (empty($_GET['resultMsg'])) {
            //Ingen melding mottatt.
            return '';
        }

        $result = filter_input(INPUT_GET, 'result', FILTER_VALIDATE_INT);

        if ($result === 0) {
            //Success melding.
            $msg = sanitize_text_field($_GET['resultMsg']);
            return '<div class="notice notice-success is-dismissible"><p>' . $msg . '</p></div>';
        } else if ($result === 1) {
            //Error melding.
            $msg = sanitize_text_field($_GET['resultMsg']);
            return '<div class="notice notice-error is-dismissible"><p>' . $msg . '</p></div>';
        } else {
            //Burde egentlig ikke skje ettersom resultMsg ikke var tom.
            return '';
        }
    }

    /**
     * Går gjennom listen over firewall regler og lager JavaScript som settes inn i HMTL template.
     * 
     * @param \WTBFirewall\Firewall\FirewallRule[] $rules Firewall regler som returnert fra databasen.
     * @param firewall Objektet som representerer firewall.
     * 
     * @return string String som kan settes rett inn i HTML template.
     */
    private function pageFireWallRulesList(array $rules, \WtbFirewall\Firewall\Firewall $firewall): string {

        $html = '';

        foreach ($rules as $rule) {

            //Delete URL
            $deleteRuleURL = esc_url(admin_url('admin-post.php?action=wtb_firewall_delete_rule&wtb_firewall_nonce='
                            . wp_create_nonce('wtb_firewall_delete_rule') .
                            '&rule_id=' . $rule['id']));

            //Enable URL
            $enableRuleURL = esc_url(admin_url('admin-post.php?action=wtb_firewall_enable_rule&wtb_firewall_nonce='
                            . wp_create_nonce('wtb_firewall_enable_rule') .
                            '&rule_id=' . $rule['id']));

            //Disable URL
            $disableRuleURL = esc_url(admin_url('admin-post.php?action=wtb_firewall_disable_rule&wtb_firewall_nonce='
                            . wp_create_nonce('wtb_firewall_disable_rule') .
                            '&rule_id=' . $rule['id']));

            //Checkbox kolonne
            $html .= '<tr>';
            $html .= '<th scope="row" class="check-column">';
            $html .= '<input form="firewallBulkAction" type="checkbox" name="rule_ids[]" value="' . $rule['id'] . '" /></th>';

            //IP Addresse + eventuell temporary info.
            $html .= '<td class="column-primary column-ip_range" data-colname="IP / Range"><strong>' . $rule->getIpString() . '</strong>';
            if ($rule->hasExpiration()) {
                $html .= '<div style="margin-top:4px;"><span class="wtb-badge wtb-badge-temp">Temp</span></div>';
            }

            //Delete og Enable/Disable.
            $html .= '<div class="wtb-row-actions">';
            $html .= '<a href="' . $deleteRuleURL . '">Delete</a>';
            if ($rule->isEnabled()) {
                $html .= '<a href="' . $disableRuleURL . '">Disable</a>';
            } else {
                $html .= '<a href="' . $enableRuleURL . '">Enable</a>';
            }

            $html .= '</div>';
            $html .= '<button type="button" class="toggle-row"><span class="screen-reader-text">Show more details</span></button>';
            $html .= '</td>';

            //Action
            $html .= '<td class="column-action" data-colname="Action">';
            if ($rule->isAllowRule()) {
                $html .= '<span class="wtb-badge wtb-badge-allow">Allow</span>';
            } else if ($rule->isBlockRule()) {
                $html .= '<span class="wtb-badge wtb-badge-block">Block</span>';
            }

            $html .= '</td>';

            //Status
            $html .= '<td class="column-status" data-colname="Status">';
            if ($rule->isActive()) {
                $html .= '<span class="wtb-badge wtb-status-active">Active</span>';
            } else {
                $html .= '<span class="wtb-status-disabled">Disabled</span>';
            }

            $html .= '</td>';

            //Added.
            $html .= '<td class="column-added" data-colname="Added">';
            $html .= $rule->getLocalTimeAdded();
            $html .= '<br><span style="color:#777;font-size:11px;">by ' . $rule['created_by'] . '</span>';
            $html .= '</td>';

            //Last Blocked
            $html .= '<td class="column-last_blocked" data-colname="Last Blocked">';
            if ($rule->isBlockRule()) {
                $html .= $rule->getLocalTimeLastHit() ?: ' &mdash; ';
                $html .= '<br><span style="color:#777;font-size:small;">' . $rule['hits'] . ' blocked connections</span>';
            } else if ($rule->isAllowRule()) {
                $html .= ' &mdash; ';
            }

            $html .= '</td>';

            //Expires
            $html .= '<td class="column-expires" data-colname="Expires">';
            if ($rule->isExpired()) {
                $html .= '<span class="wtb-expired">' . $rule->getLocalTimeExpires() . ' (Expired)</span>';
            } else if ($rule->hasExpiration()) {
                $html .= $rule->getLocalTimeExpires();
            } else {
                $html .= ' &mdash; ';
            }

            $html .= '</td>';

            //Note
            $html .= '<td class="column-note" data-colname="Note">';
            $html .= $rule['description'] ?: ' &mdash; ';
            $html .= '</td>';

            $html .= '</tr>';
        }

        return $html;
    }

    /**
     * Sjekker $_GLOBALS['wtb_firewall_messages'] og viser tilbakemelding om nødvendig.
     */
    public function firewallStatusMsg() {
        if (!isset($GLOBALS['wtb_firewall_messages'])) {
            return;
        }

        if (isset($GLOBALS['wtb_firewall_messages']['type']) && $GLOBALS['wtb_firewall_messages']['type'] == 1 && isset($GLOBALS['wtb_firewall_messages']['msg'])) {

            echo '<div class="notice notice-error"><p>' . '<b>WTB Firewall Plugin Error:</b> ' . esc_html($GLOBALS['wtb_firewall_messages']['msg']) . '</p></div>';
        }
    }

    /**
     * Håndterer siden for å blokkere/tillate land.
     */
    public function pageFirewallCountry() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have permission to access this page.');
        }

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

        $countryList = include WTB_FIREWALL_PATH . 'Admin/CountryList.php';

        $vars = array();
        $vars['msg'] = $this->GetResultMsg();

        //Alle firewall regler for land.
        $rules = $firewall->getCountryRules();

        //Lag innholdet for <select> feltet i add country rule.
        $vars['countryList'] = $this->pageFirewallCountryList($countryList, $rules);

        //Lag HTML for listen over eksisterende regler.
        $vars['countryRuleList'] = $this->pageFirewallCountryRuleList($countryList, $rules);

        $render = new \WtbFirewall\Views\Render;

        $render->render(WTB_FIREWALL_PATH . 'Views/FirewallCountry.php', $vars);
    }

    /**
     * Lager HTML for <select> feltet i Add Country Rule boksen.
     * Land som allerede er i regel listen vil ikke vises i select feltet.
     * 
     * @param type $countryList Array med alle landskoder vi støtter.
     * @param type $rules Array med alle nåværende firewall regler for land.
     * @return string HTML
     */
    private function pageFirewallCountryList($countryList, $rules): string {
        $html = '<option value="" disabled selected hidden>Select a country...</option>' . "\n";

        //Fjern land fra listen som allerede har en firewall regel.
        foreach ($rules as $rule) {
            if (array_key_exists($rule['description'], $countryList)) {
                unset($countryList[$rule['description']]);
            }
        }

        foreach ($countryList as $countryCode => $countryName) {
            $html .= '<option value="' . $countryCode . '">' . $countryName . ' (' . $countryCode . ')</option>' . "\n";
        }

        return $html;
    }

    /**
     * Lager HTML som lister opp alle eksisterende regler for land.
     * 
     * @param type $countryList Array med alle landskoder og land.
     * @param type $rules Array med alle nåværende firewall regler for land.
     * @return string HTML
     */
    private function pageFirewallCountryRuleList($countryList, $rules): string {

        /*
         * Tar imot en landskode og returnerer text/html for å vise rett flag.
         */
        $getFlag = function ($countryCode): string {
            $base = 127397;
            $cp1 = $base + ord($countryCode[0]);
            $cp2 = $base + ord($countryCode[1]);

            return '&#' . $cp1 . ';&#' . $cp2 . ';';
        };

        /*
         * Gjør firewall regel datoer om til rett timezone.
         * $time = Dato lagret i databasen. Kan være tom.
         * Return: String med dato+tid i rettt timezone eller null dersom $time ikke er gyldig dato.
         */
        $getLocalTime = function ($time) {
            if (!empty($time) && $time !== '0000-00-00 00:00:00') {
                //Skriv ut dato i rett time zone.                
                $localTimeCreated = new \DateTime($time, new \DateTimeZone('UTC'));
                $localTimeCreated->setTimeZone(\wp_timezone());
                return $localTimeCreated->format('Y-m-d H:i:s');
            } else {
                return null;
            }
        };

        $html = '';

        foreach ($rules as $rule) {
            $html .= '<tr>';
            $html .= '<td class="column-primary column-country" data-colname="Country">' . $getFlag($rule['description']) . '&nbsp;' . $countryList[$rule['description']];
            $html .= '<button type="button" class="toggle-row"><span class="screen-reader-text">Show more details</span></button>';
            $html .= '</td>';

            $html .= '<td class="column-action" data-colname="Action">';
            if ($rule['action'] == 1) {
                $html .= '<span class="wtb-badge wtb-badge-allow">Allow</span></td>';
            } else if ($rule['action'] == 2) {
                $html .= '<span class="wtb-badge wtb-badge-block">Block</span></td>';
            }

            $html .= '<td class="column-status" data-colname="Status">';
            if ($rule['enabled'] == 0) {
                $html .= '<span class="wtb-status-disabled">Disabled</span></td>';
            } else if ($rule['enabled'] == 1) {
                $html .= '<span class="wtb-badge wtb-status-active">Active</span></td>';
            }

            $html .= '<td class="column-blocked_connections" data-colname="Blocked connections">';
            if ($rule['action'] == 1) {
                $html .= '—</td>';
            } else if ($rule['action'] == 2) {
                $html .= $rule['hits'] . '</td>';
            }

            $html .= '<td class="column-last_blocked" data-colname="Last blocked">' . $getLocalTime($rule['date_last_hit']) . '</td>';

            //Delete URL
            $deleteRuleURL = esc_url(admin_url('admin-post.php?action=wtb_firewall_country_delete_rule&wtb_firewall_nonce='
                            . wp_create_nonce('wtb_firewall_delete_country') .
                            '&rule_id=' . $rule['id']));

            //Disable URL
            $disableRuleURL = esc_url(admin_url('admin-post.php?action=wtb_firewall_country_disable_rule&wtb_firewall_nonce='
                            . wp_create_nonce('wtb_firewall_disable_country') .
                            '&rule_id=' . $rule['id']));

            //Enable URL
            $enableRuleURL = esc_url(admin_url('admin-post.php?action=wtb_firewall_country_enable_rule&wtb_firewall_nonce='
                            . wp_create_nonce('wtb_firewall_enable_country') .
                            '&rule_id=' . $rule['id']));

            $html .= '<td class="column-row_actions" data-colname="Actions"><a href="' . $deleteRuleURL . '">Delete</a>&nbsp;&nbsp;';
            if ($rule['enabled'] == 0) {
                $html .= '<a href="' . $enableRuleURL . '">Enable</a></td>';
            } else if ($rule['enabled'] == 1) {
                $html .= '<a href="' . $disableRuleURL . '">Disable</a></td>';
            }

            $html .= '</tr>';
        }

        return $html;
    }

    /**
     * Håndterer siden for å vise loggen.
     * 
     * Tar imot følgende parametere via GET
     * log_page = Hvilken side av loggen som skal vises.
     * num = Antall log entries per side.
     */
    public function pageLog() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have permission to access this page.');
        }

        $log = new \WtbFirewall\Firewall\Log();

        $vars = array();
        $vars['msg'] = $this->GetResultMsg();

        //Default verdier.
        $logPage = 0;
        $vars['num'] = 50;
        $ipv4 = null;
        $ipv6 = null;
        $vars['eventType'] = null;
        $vars['ip'] = '';

        if (isset($_GET['log_page'])) {
            $logPage = absint(wp_unslash($_GET['log_page']));
        }

        if (isset($_GET['num'])) {
            $num = absint(wp_unslash($_GET['num']));
            $allowedNums = array(50, 100, 250, 500);

            if (in_array($num, $allowedNums, true)) {
                $vars['num'] = $num;
            }
        }

        if (isset($_GET['ip'])) {
            $vars['ip'] = trim(sanitize_text_field(wp_unslash((string) $_GET['ip'])));

            if ($vars['ip'] !== '') {
                if (\WtbFirewall\Helpers\IpHelper::isValidIpv4($vars['ip'])) {
                    $ipv4 = ip2long($vars['ip']);
                } elseif (\WtbFirewall\Helpers\IpHelper::isValidIpv6($vars['ip'])) {
                    $ipv6 = inet_pton($vars['ip']);
                    if ($ipv6 === false) {
                        $ipv6 = null;
                        $vars['ip'] = '';
                    }
                } else {
                    $vars['ip'] = '';
                }
            }
        }

        if (isset($_GET['event_type'])) {
            $value = absint(wp_unslash($_GET['event_type']));
            $allowedTypes = \WtbFirewall\Firewall\EventType::values();

            if (in_array($value, $allowedTypes, true)) {
                $vars['eventType'] = $value;
            }
        }

        $logCount = $log->getLogCount($vars['eventType'], $ipv4, $ipv6);

        //Sjekk at $page ikke går forbi innholdet i loggen.
        if (($logPage * $vars['num']) >= $logCount) {
            $logPage = 0;
        }

        //Hent log innholdet.   
        $logEntries = $log->getLogEntries($vars['num'] * $logPage, $vars['num'], $vars['eventType'], $ipv4, $ipv6);

        $vars['log'] = $this->pageLogList($logEntries);

        /**
         * 
         * Lag HTML for PREV/NEXT knappene og mer.
         * 
         */
        $vars['currentPage'] = $logPage + 1;
        $vars['totalPages'] = ceil($logCount / $vars['num']);
        $vars['totalLogEntries'] = $logCount;
        $vars['nextPage'] = '';
        $vars['prevPage'] = '';
        $vars['firstPage'] = '';
        $vars['lastPage'] = '';

        if ($logPage > 0) {
            //Skal ha previous page knapp.
            $prevUrl = add_query_arg(
                    [
                        'log_page' => max(0, $logPage - 1),
                        'num' => $vars['num'],
                        'ip' => $vars['ip'],
                        'event_type' => $vars['eventType'],
                    ],
                    admin_url('admin.php?page=wtb-firewall-log')
            );

            $vars['prevPage'] = '<a class="button" href="' . $prevUrl . '" aria-label="Next page">&lsaquo;</a>';
        }

        if ($logPage < ($vars['totalPages'] - 1)) {
            //Skal ha next page knapp.
            $nextUrl = add_query_arg(
                    [
                        'log_page' => min($vars['totalPages'] - 1, $logPage + 1),
                        'num' => $vars['num'],
                        'ip' => $vars['ip'],
                        'event_type' => $vars['eventType'],
                    ],
                    admin_url('admin.php?page=wtb-firewall-log')
            );

            $vars['nextPage'] = '<a class="button" href="' . $nextUrl . '" aria-label="Last page">&rsaquo;</a>';
        }

        if ($vars['totalPages'] > 1 && $logPage > 0) {
            //Skal ha first page knapp.
            $firstPageUrl = add_query_arg(
                    [
                        'log_page' => 0,
                        'num' => $vars['num'],
                        'ip' => $vars['ip'],
                        'event_type' => $vars['eventType'],
                    ],
                    admin_url('admin.php?page=wtb-firewall-log')
            );

            $vars['firstPage'] = '<a class="button" href="' . $firstPageUrl . '" aria-label="First page">&laquo;</a>';
        }

        if (($vars['totalPages'] > 1 && $logPage < $vars['totalPages'] - 1)) {
            //Skal  ha last page knapp.
            $lastPageUrl = add_query_arg(
                    [
                        'log_page' => $vars['totalPages'] - 1,
                        'num' => $vars['num'],
                        'ip' => $vars['ip'],
                        'event_type' => $vars['eventType'],
                    ],
                    admin_url('admin.php?page=wtb-firewall-log')
            );

            $vars['lastPage'] = '<a class="button" href="' . $lastPageUrl . '" aria-label="First page">&raquo;</a>';
        }


        $render = new \WtbFirewall\Views\Render;

        $render->render(WTB_FIREWALL_PATH . 'Views/FirewallLog.php', $vars);
    }

    /**
     * Lager HTML for log listen.
     * 
     * @param type $logEntries Log innholdet fra databasen.
     * 
     * @return HTML som kan settes rett inn på log siden.
     */
    private function pageLogList($logEntries): string {
        $html = '';

        foreach ($logEntries as $log) {

            //Gjør om tidspunktet til rett tidssone.
            $dt = new \DateTime($log['event_time'], new \DateTimeZone('UTC'));
            $dt->setTimezone(\wp_timezone());

            // Format using WP date format + time format
            $formattedTime = \wp_date(
                    \get_option('date_format') . ' ' . \get_option('time_format'),
                    $dt->getTimestamp(),
                    \wp_timezone()
            );

            $ip = '';
            if (isset($log['ipv4'])) {
                $ip = long2ip($log['ipv4']);
            } else if (is_string($log['ipv6']) && strlen($log['ipv6']) === 16) {
                $ip = inet_ntop($log['ipv6']);
            }

            $event = \WtbFirewall\Firewall\EventType::tryFrom($log['event_type']) ?? \WtbFirewall\Firewall\EventType::UNKNOWN;

            $html .= '<tr>';
            $html .= '<td class="column-event-time"><strong>' . esc_html($formattedTime) . '</strong></td>';
            $html .= '<td class="column-ip"><code>' . $ip . '</code>';
            $html .= '<td class="column-type"><span class="wtb-pill">' . $event->label() . '</span></td>';
            $html .= '<td class="column-details">' . $log['details'] . '</td>';
            $html .= '</tr>';
        }

        return $html;
    }

    /**
     * Håndterer Automatic Protection siden.
     */
    public function pageAutomaticProtection() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have permission to access this page.');
        }

        $vars = array();
        $vars['msg'] = $this->GetResultMsg();

        $vars['authentication'] = \WtbFirewall\Config\FirewallConfig::$autoProtectAuth;
        $vars['rateLimit'] = \WtbFirewall\Config\FirewallConfig::$rateLimit;

        $render = new \WtbFirewall\Views\Render;

        $render->render(WTB_FIREWALL_PATH . 'Views/AutomaticProtection.php', $vars);
    }

    /**
     * Håndterer siden for å vise firewall regler lagt til automatisk.
     */
    public function pageAutomaticProtectionRules() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have permission to access this page.');
        }

        $vars = array();
        $vars['msg'] = $this->GetResultMsg();
        $vars['firewallNonce'] = wp_create_nonce('wtb_firewall_auto_protect_log');

        //HTML for tabellen med reglene.
        $vars['htmlRuleList'] = $this->pageAutomaticProtectionRulesList();

        $render = new \WtbFirewall\Views\Render;

        $render->render(WTB_FIREWALL_PATH . 'Views/AutomaticProtectionRules.php', $vars);
    }

    /**
     * Lager HTML for innholdet i tabellen som viser alle firewall regler lagt til automatisk.
     * 
     * @param string HTML klar til settes inn i HTML template.
     */
    private function pageAutomaticProtectionRulesList(): string {

        /*
         * Gjør firewall regel datoer om til rett timezone.
         * $time = Dato lagret i databasen. Kan være tom.
         * Return: String med dato+tid i rettt timezone eller null dersom $time ikke er gyldig dato.
         */
        $getLocalTime = function ($time) {
            if (!empty($time) && $time !== '0000-00-00 00:00:00') {
                //Skriv ut dato i rett time zone.                
                $localTimeCreated = new \DateTime($time, new \DateTimeZone('UTC'));
                $localTimeCreated->setTimeZone(\wp_timezone());
                return $localTimeCreated->format('Y-m-d H:i:s');
            } else {
                return null;
            }
        };

        $firewall = new \WtbFirewall\Firewall\Firewall;
        $rules = $firewall->getAutoRules();

        if ($rules == null || empty($rules)) {
            return '<tr><td colspan="6"><p>There are no rules to show.</p> </td></tr>';
        }

        $html = '';

        foreach ($rules as $rule) {

            //Delete URL
            $deleteRuleURL = esc_url(admin_url('admin-post.php?action=wtb_firewall_delete_auto_rule&wtb_firewall_nonce='
                            . wp_create_nonce('wtb_firewall_delete_auto_rule') .
                            '&rule_id=' . $rule['id']));

            //Make permanent URL
            $makePermanentURL = esc_url(admin_url('admin-post.php?action=wtb_firewall_permanent_auto_rule&wtb_firewall_nonce='
                            . wp_create_nonce('wtb_firewall_permanent_auto_rule') .
                            '&rule_id=' . $rule['id']));

            //Checkbox kolonne.
            $html .= '<tr>';
            $html .= '<th scope="row" class="check-column">';
            $html .= '<input form="auto-protect-form" type="checkbox" name="rule_ids[]" value="' . $rule['id'] . '" /></th>';

            //IP
            $html .= '<td class="column-primary column-ip" data-colname="IP"><strong>' . $rule->getIpString() . '</strong>';
            $html .= '<div class="wtb-row-actions">';
            $html .= '<a href="' . $deleteRuleURL . '">Delete</a>';
            $html .= '<a href="' . $makePermanentURL . '">Make permanent</a>';
            $html .= '</div>';
            $html .= '<button type="button" class="toggle-row"><span class="screen-reader-text">Show more details</span></button>';
            $html .= '</td>';

            //Dato lagt til.
            $html .= '<td class="column-added" data-colname="Added">' . $getLocalTime($rule['date_created']) . '</td>';

            //Dato utgår.
            $html .= '<td class="column-expires" data-colname="Expires">' . $getLocalTime($rule['date_expires']) . '</td>';

            //Antall ganger blokkert
            $html .= '<td class="column-blocked" data-colname="Blocked">' . $rule['hits'] . '</td>';

            //Notes
            $html .= '<td class="wtb-note column-note" data-colname="Note">' . $rule['description'] . '</td>';
            $html .= '</tr>';
        }

        return $html;
    }

    public function pageQuickStartDocs() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have permission to access this page.');
        }

        $render = new \WtbFirewall\Views\Render;

        $render->render(WTB_FIREWALL_PATH . 'Views/QuickStart.html');
    }

    /**
     * Håndterer traffic log siden.
     */
    public function pageTrafficLog() {
        if (!current_user_can('manage_options')) {
            wp_die('You do not have permission to access this page.');
        }

        $vars = array();
        $vars['msg'] = $this->GetResultMsg();
        $vars['trafficLog'] = \WtbFirewall\Config\FirewallConfig::$trafficLog;

        $render = new \WtbFirewall\Views\Render;

        $render->render(WTB_FIREWALL_PATH . 'Views/TrafficLog.php', $vars);
    }
}
