<?php

namespace FleekDash\Core;

/**
 * Class Redirects
 *
 * Handles all redirects for FleekDash V2
 */
class Redirects
{
    /**
     * Initialize the redirects
     */
    public function init()
    {
        // Redirect after login
        \add_filter('login_redirect', [$this, 'redirectAfterLogin'], 10, 3);

        // Redirect default admin pages
        \add_action('admin_init', [$this, 'redirectDefaultAdminPage'], 0);
    }

    /**
     * Redirect after successful login
     */
    public function redirectAfterLogin(string $redirect_to, string $requested_redirect_to, ?object $user): string
    {
        $target_redirect = $redirect_to;
        $has_valid_user = $user && !is_wp_error($user);
        if ($has_valid_user) {
            // Respect classic mode if active (query param or session cookie)
            $is_classic_mode = class_exists('\FleekDash\Core\ClassicModeHandler')
                && \FleekDash\Core\ClassicModeHandler::isTemporarilyDisabled();
            if ($is_classic_mode) {
                $target_redirect = !empty($requested_redirect_to)
                    ? $requested_redirect_to
                    : \admin_url('index.php');
            } elseif (!empty($requested_redirect_to) && \user_can($user, 'manage_options')) {
                // If a specific redirect was requested and user has permissions, honor it
                $target_redirect = $requested_redirect_to;
            } else {
                // Otherwise, redirect to our dashboard
                $target_redirect = \admin_url('admin.php?page=fleekdash#/dashboard');
            }
        }

        return $target_redirect;
    }

    /**
     * Redirect default admin pages (wp-admin/index.php and wp-admin/admin.php) to our dashboard
     *
     * @deprecated Disabled to preserve native wp-admin navigation.
     */
    public function redirectDefaultAdminPage(): void
    {
        // No-op: aggressive redirects broke core admin flows.

        /* Original redirect logic (disabled):
        global $pagenow;

        // Skip redirect when already inside FleekDash
        if (isset($_GET['page']) && $_GET['page'] === 'fleekdash') {
            return;
        }

        // Entry screens that redirected to FleekDash when opened with no query args
        $redirect_pages = ['index.php', 'admin.php'];

        // Check if we're on any of the default admin pages without parameters
        if (in_array($pagenow, $redirect_pages) && empty($_GET)) {
            wp_safe_redirect(\admin_url('admin.php?page=fleekdash#/dashboard'));
            exit;
        }
        */
    }
}
