<?php

namespace _121Digital\Connect\Frontend;

use _121Digital\Connect\Core\Environment;

class Frontend
{
    public function register(): void
    {
        add_action('template_redirect', [$this, 'maybeBlockNetworkRootSiteFrontendAccess']);
        add_action('after_setup_theme', [$this, 'maybeRemoveWPAdminBar']);
    }

    /**
     * Block frontend access to the network root site and redirect to the main site of the network
     * Only applies if the current site is the main site of the network and we are in
     * network mode (multisite)...
     *
     */
    public function maybeBlockNetworkRootSiteFrontendAccess(): void
    {
        // skip if not in multisite node context
        if (!Environment::isMultisiteNode()) {
            return;
        }

        // only block access on the network root site
        if (!is_main_site()) {
            return;
        }

        // Allow access to wp-login.php and wp-signup.php
        $current_url = $_SERVER['REQUEST_URI'];
        if (strpos($current_url, 'wp-login.php') !== false || strpos($current_url, 'wp-signup.php') !== false) {
            return;
        }

        // Prevent redirect loops - check if we're already being redirected
        if (isset($_GET['redirected']) || headers_sent()) {
            return;
        }

        // Redirect to the network login page
        wp_redirect(wp_login_url());
        exit;
    }

    /**
     * This function can be used to remove the WP admin bar on frontend for certain users
     * if the user is loggeed into another site within the network, but visiting a different
     * site..
     *
     */
    public function maybeRemoveWPAdminBar(): void
    {
        if (!Environment::isMultisiteNode()) {
            return;
        }

        if (!is_user_logged_in()) {
            return;
        }

        if (!current_user_can('edit_posts')) {
            show_admin_bar(false);
        }
    }
}
