<?php

namespace Bdp\Modules\LimitLoginAttempts\Controllers;

class OptionsPage
{
    public function __construct()
    {
        add_options_page(
	        __('Login-Protection', BDP_LV_PLUGIN_SLUG),
            __('Login-Protection', BDP_LV_PLUGIN_SLUG),
            'manage_options',
            BDP_LV_PLUGIN_SLUG . '-limit-login-attempts',
            [$this, 'limit_login_option_page'],2048);
    }

    public function releaseIp($ip)
    {
        $allIps = get_option('kompass_limit_login_lockouts', []);
        unset($allIps[$ip]);
        update_option('kompass_limit_login_lockouts', $allIps);
    }

	public static function addToBlocklist(string $ip)
	{
		$blockedIps = get_option('kompass_limit_login_blocklist', []);
		$blockedIps[] = $ip;
		update_option('kompass_limit_login_blocklist', $blockedIps);
	}

    public static function addToAllowlist(string $ip)
    {
        $allowedIps = get_option('kompass_limit_login_allowlist', []);
        $allowedIps[] = $ip;
        update_option('kompass_limit_login_allowlist', $allowedIps);
        self::releaseIp($ip);
    }

    public function removeFromList(string $listType, string $ip){
        update_option(
                'kompass_limit_login_' . $listType,
                array_diff(get_option('kompass_limit_login_' . $listType, []), [$ip])
        );
    }


    public function getBlockedIps()
    {
	    bdp_kompass_load_plugin_textdomain();
        $ips = '';
        foreach (get_option('kompass_limit_login_lockouts', []) as $ip => $blockedUntil) {
            $ips .= '<tr style="vertical-align: top;">' .
                '<td style="padding-right: 50px;">' . $ip . '</td>';
            if (in_array($ip, get_option('protect_login_limit_login_blocklist', []))) {
                $ips .= '<td style="padding-right: 50px;">Dauerhaft blockiert</td>' .
                    '<td>' .
                    'Keine Aktion möglich' .
                    '</td></tr>';
            } else {
                $ips .= '<td style="padding-right: 50px;">' . date('d.m.Y', $blockedUntil) . '<br />' . date('H:i', $blockedUntil) . ' Uhr</td>' .
                    '<td>
                                         <a href="admin.php?page=bdp-kompass-limit-login-attempts&tab=tab4&action=release&ip=' .
                    base64_encode($ip) . '">' . __('Release ip address', BDP_LV_PLUGIN_SLUG) . '</a><br />
                                        <a href="admin.php?page=bdp-kompass-limit-login-attempts&tab=tab4&action=toBlock&ip=' .
                    base64_encode($ip) . '">' . __('Add ip address to blocklist', BDP_LV_PLUGIN_SLUG) . '</a><br />
                                        <a href="admin.php?page=bdp-kompass-limit-login-attempts&tab=tab4&action=toAllow&ip=' .
                    base64_encode($ip) . '">' . __('Add ip address to allowlist and release', BDP_LV_PLUGIN_SLUG) . '</a><br /> ' .
                            '</td></tr>';
            };
        }
        return $ips;
    }

    public function limit_login_option_page() {
        global $errors;
	    bdp_kompass_load_plugin_textdomain();
        $showMessage = null;

        if (isset($_POST['update_options'])) {
            update_settings($_POST);
            $showMessage = __('The settings were saved.', BDP_LV_PLUGIN_SLUG);
        }
        if (isset($_GET['action']) && $_GET['action'] == 'release') {
            $showMessage = __('The ip address was released.', BDP_LV_PLUGIN_SLUG);
        }

        if(isset($_POST['save_kompass_balist_list_type'])) {
            $showMessage = __('The list was saved.', BDP_LV_PLUGIN_SLUG);
        }

        if (null !== $showMessage && $errors === false) {
            echo '<div class="notice notice-success" style="padding: 5px 10px;">';
            echo $showMessage;
            echo '</div>';
        }

        if ($errors) {
            echo '<div class="notice notice-error" style="padding: 5px 10px;">';
            echo __('An error occured.', BDP_LV_PLUGIN_SLUG);
            echo '</div>';
        }

        $tab = isset($_GET['tab']) ? $_GET['tab'] : 'tab1';

        if (isset($_GET['action']) && $_GET['action'] == 'removeFromList') {
            $this->removeFromList($_GET['list'], base64_decode($_GET['ip']));
            if ($_GET['list'] == 'blocklist') {
                $tab = 'tab2';
            } else {
                $tab = 'tab3';
            }
        }
	    bdp_kompass_load_plugin_textdomain();

        ?>

        <div class="wrap">
            <h1 class="wp-heading-inline">
                <?= __('Login-Protection', BDP_LV_PLUGIN_SLUG); ?> - <?= __('Settings', BDP_LV_PLUGIN_SLUG); ?></h1>
            <hr class="wp-header-end">
            <?= kompass_print_tab_header($tab); ?>

            <div class="tab-content">
                <?php
                switch ($tab) {
                    case 'tab1':
                        echo '<form action="admin.php?page=bdp-kompass-limit-login-attempts&tab=tab1" method="post">';
                        do_settings_sections(BDP_LV_PLUGIN_SLUG . '-limit-login-attempts');
                        submit_button();
                        echo '</form>';
                        break;
                    case 'tab2':
                        echo '<h2>Blocklist</h2>';
                        echo '<form action="admin.php?page=bdp-kompass-limit-login-attempts&tab=tab2" method="post">';
                        kompass_print_block_allow_form('blocklist');
                        submit_button();
                        echo '</form>';
                        break;
                    case 'tab3':
                        echo '<h2>Allowlist</h2>';
                        echo '<form action="admin.php?page=bdp-kompass-limit-login-attempts&tab=tab3" method="post">';
                        kompass_print_block_allow_form('allowlist');
                        submit_button();
                        echo '</form>';
                        break;
                    case 'tab4':
                        if (isset($_GET['action']) && $_GET['action'] == 'release') {
                            $this->releaseIp(base64_decode($_GET['ip']));
                        }

                        if (isset($_GET['action']) && $_GET['action'] == 'toBlock') {
                            $this->addToBlocklist(base64_decode($_GET['ip']));
                        }

                        if (isset($_GET['action']) && $_GET['action'] == 'toAllow') {
                            $this->addToAllowlist(base64_decode($_GET['ip']));
                        }
                        $blockedIps = $this->getBlockedIps();
                        echo '<h2>'. __('Blocked IP addresses', BDP_LV_PLUGIN_SLUG) .'</h2>';

                            if (strlen($blockedIps) == 0) {
                                echo '<div class="bdp-kompass-no-blocked-ips">';
                                echo __('There are no ip addresses blocked.', BDP_LV_PLUGIN_SLUG);
                                echo '</div>';
                            } else { ?>
                                    <p style="width: 100%; text-align: right">
                                        <input type="text" id="searchInput"
                                               onkeyup="searchTable('myTable', this)"
                                               placeholder="<?=__('Search for ip address', BDP_LV_PLUGIN_SLUG); ?>">
                                    </p>

                                <table class="wp-list-table widefat fixed striped table-view-list" id="myTable">
                                    <thead>
                                        <tr>
                                            <th scope="col" class="manage-column column-name"><?= __('IP address', BDP_LV_PLUGIN_SLUG); ?></th>
                                            <th class="manage-column column-name"><?= __('Blocked until', BDP_LV_PLUGIN_SLUG); ?></th>
                                            <th class="manage-column column-name"><?= __('Actions', BDP_LV_PLUGIN_SLUG); ?></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?= $blockedIps ?>
                                    </tbody>
                                </table>
                            <?php
                            }
                    break;
                }
                ?>
            </div>
        </div>
        <?php
    }
}