<?php
if (!defined('ABSPATH')) {
    exit;
}

class Foxblock_CustomLogin
{
    private $custom_slug;
    private $is_enabled;

    public function __construct()
    {
        $this->custom_slug = get_option('foxblock_login_slug', '');
        $this->custom_slug = sanitize_title(trim($this->custom_slug, '/'));

        $this->is_enabled = get_option('foxblock_enable_wp_login_hide', 1);

        if (empty($this->custom_slug)) {
            $this->is_enabled = 0;
        }

        if ($this->is_enabled) {
            add_action('plugins_loaded', array($this, 'setup_hooks'), 99);
        }
    }

    public function setup_hooks()
    {
        add_action('init', array($this, 'intercept_default_login'));
        add_action('template_redirect', array($this, 'process_custom_login'));

        add_filter('site_url', array($this, 'filter_urls'), 10, 4);
        add_filter('network_site_url', array($this, 'filter_urls'), 10, 3);
        add_filter('wp_redirect', array($this, 'filter_wp_redirect'), 10, 2);

        // Remove default WP redirect to wp-login.php
        remove_action('template_redirect', 'wp_redirect_admin_locations', 1000);
    }

    public function intercept_default_login()
    {
        $req_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        $path = untrailingslashit(parse_url($req_uri, PHP_URL_PATH));
        $home_path = untrailingslashit(parse_url(home_url(), PHP_URL_PATH));
        $relative_path = str_replace($home_path, '', $path);

        $php_self = basename(isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '');

        // Intercept direct accesses to wp-login.php
        $is_login_path = ($php_self === 'wp-login.php' || strpos($relative_path, '/wp-login') !== false || strpos($relative_path, '/wp-signup') !== false);

        if ($is_login_path && !is_user_logged_in()) {
            if (defined('DOING_AJAX') && DOING_AJAX)
                return;
            if (defined('DOING_CRON') && DOING_CRON)
                return;
            if (defined('WP_CLI') && WP_CLI)
                return;

            $this->do_404();
        }

        // Block unauthenticated /wp-admin — return 404 silently, never reveal the custom slug
        if (($php_self === 'wp-admin' || strpos($relative_path, '/wp-admin') === 0) && !is_user_logged_in()) {
            if (defined('DOING_AJAX') || defined('DOING_CRON') || defined('WP_CLI'))
                return;

            // Allow admin-ajax and admin-post (needed by some front-end forms)
            if (strpos($req_uri, 'admin-ajax.php') !== false || strpos($req_uri, 'admin-post.php') !== false)
                return;

            // Return silent 404 — do NOT redirect to the custom slug
            $this->do_404();
        }
    }

    public function process_custom_login()
    {
        $req_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        $path = untrailingslashit(parse_url($req_uri, PHP_URL_PATH));
        $home_path = untrailingslashit(parse_url(home_url(), PHP_URL_PATH));
        $relative_path = str_replace($home_path, '', $path);

        $custom_path = '/' . $this->custom_slug;

        // Custom slug matches successfully
        if ($relative_path === $custom_path) {

            // Emulate wp-login.php environment 
            global $pagenow, $error, $interim_login, $action, $user_login;
            $pagenow = 'wp-login.php';
            $_SERVER['PHP_SELF'] = '/wp-login.php';

            status_header(200);

            if (!defined('DONOTCACHEPAGE')) {
                define('DONOTCACHEPAGE', true);
            }

            require_once ABSPATH . 'wp-login.php';
            exit;
        }
    }

    public function filter_urls($url, $path, $scheme, $blog_id = null)
    {
        if (strpos($url, 'wp-login.php') !== false) {
            $url = preg_replace('/wp-login\\.php/', $this->custom_slug, $url, 1);
        }
        return $url;
    }

    public function filter_wp_redirect($location, $status)
    {
        // Only rewrite wp-login.php redirects if the current request is the custom slug
        // (e.g. after a failed login attempt on the custom page).
        // Never expose the custom slug via a redirect triggered by /wp-admin or /wp-login.php visits.
        if (strpos($location, 'wp-login.php') !== false) {
            $req_uri    = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
            $path       = untrailingslashit(parse_url($req_uri, PHP_URL_PATH));
            $home_path  = untrailingslashit(parse_url(home_url(), PHP_URL_PATH));
            $relative   = str_replace($home_path, '', $path);

            // Rewrite only when the request comes from the custom slug itself
            $from_custom_slug = ($relative === '/' . $this->custom_slug);
            if ($from_custom_slug) {
                $location = preg_replace('/wp-login\\.php/', $this->custom_slug, $location, 1);
            } else {
                // All other contexts (wp-admin, wp-login.php etc.) — redirect to homepage
                $location = home_url('/');
            }
        }
        return $location;

    }

    private function do_404()
    {
        global $wp_query;
        if (!isset($wp_query)) {
            status_header(404);
            nocache_headers();
            exit;
        }
        $wp_query->set_404();
        status_header(404);
        nocache_headers();
        require get_404_template();
        exit;
    }
}
