<?php

/**
 * Maneja la intercepción de URLs y la reescritura de enlaces.
 */
class Wporlogin_Public_Hide_Login {

    private $plugin_name;
    private $version;
    private $login_slug;
    private $register_slug;
    private $recovery_slug;

    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version     = $version;

        $this->login_slug    = get_option('wporlogin_hide_login_slug');
        $this->register_slug = get_option('wporlogin_hide_register_slug');
        $this->recovery_slug = get_option('wporlogin_hide_recovery_slug');
    }

    public function init() {
        if ( empty($this->login_slug) && empty($this->register_slug) && empty($this->recovery_slug) ) {
            return;
        }

        // 1. INTERCEPTOR (Carga la página correcta)
        add_action( 'wp_loaded', array( $this, 'intercept_login_page' ) );

        // 2. FILTROS GENÉRICOS (Limpia URLs en redirecciones y correos)
        add_filter( 'site_url', array( $this, 'filter_site_url' ), 10, 4 );
        add_filter( 'network_site_url', array( $this, 'filter_site_url' ), 10, 3 );
        add_filter( 'wp_redirect', array( $this, 'filter_wp_redirect' ), 10, 2 );

        // 3. FILTRO VISUAL (El que soluciona tu problema del enlace "¿Olvidaste contraseña?")
        add_filter( 'lostpassword_url', array( $this, 'filter_lostpassword_url' ), 10, 2 );

        // 4. SEGURIDAD (Bloqueo)
        add_action( 'init', array( $this, 'block_wp_login' ) );
    }

/**
     * Lógica Híbrida para "¿Has olvidado tu contraseña?"
     * Garantiza que siempre devuelva una URL válida.
     */
    public function filter_lostpassword_url( $url, $redirect = '' ) {
        
        // 1. Prioridad: ¿El usuario configuró un slug específico (ej: 'recuperar')?
        if ( !empty($this->recovery_slug) ) {
            $new_url = home_url( '/' . $this->recovery_slug );
            
            // Si había una redirección pendiente, la mantenemos
            if ( !empty($redirect) ) {
                $new_url = add_query_arg( 'redirect_to', urlencode($redirect), $new_url );
            }
            return $new_url;
        }

        // 2. Respaldo Híbrido: Si está vacío, usamos el slug de Login + parametro.
        // Construimos la URL desde cero para evitar errores de reemplazo.
        if ( !empty($this->login_slug) ) {
            // Resultado: tudominio.com/acceso
            $new_url = home_url( '/' . $this->login_slug );
            // Agregamos el parámetro: tudominio.com/acceso?action=lostpassword
            $new_url = add_query_arg( 'action', 'lostpassword', $new_url );

            if ( !empty($redirect) ) {
                $new_url = add_query_arg( 'redirect_to', urlencode($redirect), $new_url );
            }
            return $new_url;
        }

        // 3. Si todo falla, devolvemos la original
        return $url;
    }

    /**
     * Interceptor: Carga wp-login.php con la acción correcta.
     */
    public function intercept_login_page() {
        $request_uri = $_SERVER['REQUEST_URI'];
        $path = parse_url($request_uri, PHP_URL_PATH);
        $base_path = parse_url(home_url(), PHP_URL_PATH);
        
        if ( $base_path && $base_path !== '/' ) {
            $path = str_replace($base_path, '', $path);
        }
        $path = trim($path, '/');

        $is_login    = ( !empty($this->login_slug) && $path === $this->login_slug );
        $is_register = ( !empty($this->register_slug) && $path === $this->register_slug );
        $is_recovery = ( !empty($this->recovery_slug) && $path === $this->recovery_slug );

        if ( $is_login || $is_register || $is_recovery ) {
            global $error, $interim_login, $action, $user_login;
            
            if ( $is_register ) {
                $action = 'register';
                $_GET['action'] = 'register';
                if ( ! isset( $_GET['key'] ) ) $_REQUEST['action'] = 'register';
            } elseif ( $is_recovery ) {
                $action = 'lostpassword';
                $_GET['action'] = 'lostpassword';
                $_REQUEST['action'] = 'lostpassword';
                // Protección para el enlace del email (resetpass)
                if ( isset($_GET['action']) && in_array($_GET['action'], array('rp', 'resetpass')) ) {
                    $action = $_GET['action'];
                }
            } else {
                if ( isset($_GET['action']) ) $action = $_GET['action'];
            }

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

    /**
     * Filtro Site URL (Mantiene la lógica híbrida para el email)
     */
    public function replace_login_url( $url, $scheme = null ) {
        if ( strpos( $url, 'wp-login.php' ) !== false ) {
            
            // Registro
            if ( strpos( $url, 'action=register' ) !== false || strpos( $url, 'registration=disabled' ) !== false ) {
                if ( !empty($this->register_slug) ) return home_url( '/' . $this->register_slug );
                if ( !empty($this->login_slug) ) return str_replace( 'wp-login.php', $this->login_slug, $url );
            }

            // Recuperar
            if ( strpos( $url, 'action=lostpassword' ) !== false ) {
                if ( !empty($this->recovery_slug) ) return home_url( '/' . $this->recovery_slug );
                if ( !empty($this->login_slug) ) return str_replace( 'wp-login.php', $this->login_slug, $url );
            }

            // Email Link (Reset Password) -> Forzamos al Login Slug
            if ( strpos( $url, 'action=rp' ) !== false || strpos( $url, 'action=resetpass' ) !== false ) {
                if ( !empty($this->login_slug) ) return str_replace( 'wp-login.php', $this->login_slug, $url );
                return $url; 
            }

            // Login General
            if ( !empty($this->login_slug) ) {
                return str_replace( 'wp-login.php', $this->login_slug, $url );
            }
        }
        return $url;
    }

    // Wrappers
    public function filter_site_url( $url, $path, $scheme, $blog_id = null ) {
        return $this->replace_login_url( $url, $scheme );
    }
    public function filter_wp_redirect( $location, $status ) {
        return $this->replace_login_url( $location );
    }

    /**
     * Bloqueo de wp-login.php original
     */
    public function block_wp_login() {
        if ( empty($this->login_slug) ) return;
        $request_uri = $_SERVER['REQUEST_URI'];
        
        if ( strpos( $request_uri, 'wp-login.php' ) !== false ) {
            if ( strpos( $request_uri, $this->login_slug ) !== false ) return;
            if ( isset( $_GET['action'] ) && ( $_GET['action'] === 'logout' || $_GET['action'] === 'postpass' ) ) return;
            if ( is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) return;
            if ( isset( $_GET['action'] ) && ( $_GET['action'] === 'rp' || $_GET['action'] === 'resetpass' ) ) return;

            global $wp_query;
            $wp_query->set_404();
            status_header(404);
            get_template_part(404);
            exit();
        }
    }
}