<?php

namespace ProudNerds\Admin;

use ProudNerds\Helpers\Env;
use ProudNerds\Helpers\Ip;
use ProudNerds\Trait\Initializable;
use WP_Error;
use WP_User;

/**
 * Alter login functionality
 */
class Login
{
    use Initializable;

    private function __construct()
    {
        // Add filters for non-production environments
        if (Env::isNot(Env::PRODUCTION)) {
            add_filter('admin_title', [$this, 'prependEnvToTitle']);
            add_filter('wpseo_title', [$this, 'prependEnvToTitle']);
            add_filter('wp_title', [$this, 'prependEnvToTitle']);
            add_action('pre_option_blog_public', '__return_zero');
        }

        // Redirect to login page when not in production or development
        if (Env::isNot(Env::PRODUCTION) && Env::isNot(Env::DEVELOPMENT)) {
            $this->redirect();
        }

        // Add filter for testing environment
        if (Env::is(Env::TESTING)) {
            add_filter('authenticate', [$this, 'blockNonProudNerdsUsers'], 40, 1);
        }
    }

    /**
     * Prepend the environment to the title
     *
     * @param string $title
     * @return string
     */
    public function prependEnvToTitle($title): string
    {
        switch (Env::get()) {
            case Env::ACCEPTANCE:
                $env = 'acc';
                break;
            case Env::TESTING:
                $env = 'test';
                break;
            default:
                $env = 'dev';
        }

        return sprintf('[%s] %s', $env, $title);
    }

    /**
     * Block access for non-Proud Nerds users
     *
     * @param null|WP_User|WP_Error $user
     * @return null|WP_User|WP_Error
     */
    public function blockNonProudNerdsUsers(null|WP_User|WP_Error $user): null|WP_User|WP_Error
    {
        if ($user instanceof WP_User) {
            if (str_contains($user->user_email, '@proudnerds.com')) {
                return $user;
            }

            return null;
        }

        return $user;
    }

    /**
     * Redirect to login page
     *
     * @return void
     */
    private function redirect()
    {
        if (Ip::isAllowedIp()) {
            return;
        }

        if (php_sapi_name() !== 'cli' && !defined('DONT_FORCE_STAGING_LOGIN') && !is_user_logged_in()) {
            $requestUri = $_SERVER['REQUEST_URI'];
            $fullRequestUrl = ((isset($_SERVER['HTTPS'])) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $requestUri; // NOSONAR
            $loginUrl = wp_login_url();

            if (!array_key_exists('sig', $_POST) && !str_contains($fullRequestUrl, $loginUrl)) {
                $redirectUrl = $loginUrl . '?' . http_build_query(['redirect_to' => $requestUri]);
                wp_redirect($redirectUrl);
                exit;
            }
        }
    }
}
