<?php

namespace UltraguardPro\modules\login_protect;

if ( ! defined( 'ABSPATH' ) ) { exit; }

use UltraguardPro\Plugin;
use UltraguardPro\modules\core\AbstractModule;

class LoginProtectModule extends AbstractModule {

    public function __construct( Plugin $plugin ) {
        parent::__construct( $plugin );
        $this->plugin->settings->register_module_prefix( 'login_protect_', 'login_protect' );
    }

    public function get_id(): string {
        return 'login_protect';
    }

    protected function requires_pro(): bool {
        return false;
    }

    public function boot(): void {
        // 1. Register DB schema so login_protect_stats table is created/upgraded.
        $db_tables = $this->plugin->modules->get_db_tables();
        if ( $db_tables ) {
            $db_tables->register_schema( new schema\LoginProtectSchema() );
        }

        // 2. AJAX handlers (settings save, stats fetch, path generation).
        ( new ajax\LoginProtectAjax( $this->plugin ) )->register();

        // 3. Admin pages (dashboard + settings).
        add_action( 'ultraguard_register_admin_pages', [ $this, 'register_pages' ], 32, 1 );

        // 4. Admin asset enqueueing.
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );

        // 5. Runtime URL interception — fires at init priority 1 so it runs before
        //    WordPress boots wp-login.php and before the Login Limiter (priority 2).
        if ( $this->option( 'login_protect_enabled', true ) ) {
            add_action( 'init', [ $this, 'intercept_login_url' ], 1 );
            $this->hook_login_url_filters();
        }

        // 6. Log failed login attempts via wp-login.php (separate from lockouts).
        add_action( 'wp_login_failed', [ $this, 'on_login_failed' ] );

        do_action( 'ultraguard_pro/login_protect/booted', $this );
    }

    public function intercept_login_url(): void {
        if ( ! $this->option( 'login_protect_enabled', true ) ) {
            return;
        }
        ( new LoginUrlEngine( $this->plugin ) )->intercept_login_url();
    }

    public function hook_login_url_filters(): void {
        $engine = new LoginUrlEngine( $this->plugin );
        add_filter( 'site_url', [ $this, 'filter_site_login_url' ], 20, 4 );
        add_filter( 'network_site_url', [ $this, 'filter_network_login_url' ], 20, 3 );
        add_filter( 'login_url', [ $engine, 'filter_login_url' ], 20, 2 );
    }

    public function filter_site_login_url( $url, $path, $scheme, $blog_id ) {
        return ( new LoginUrlEngine( $this->plugin ) )->filter_login_url( $url, (string) $path );
    }

    public function filter_network_login_url( $url, $path, $scheme ) {
        return ( new LoginUrlEngine( $this->plugin ) )->filter_login_url( $url, (string) $path );
    }

    public function on_login_failed( string $username ): void {
        ( new LoginUrlEngine( $this->plugin ) )->log_failed_attempt( $username );
    }

    public function register_pages( $admin ): void {
        $admin->register_page( [
            'id'              => 'login-protect',
            'page_title'      => __( 'Login URL Protection', 'ultraguard-security-suite' ),
            'menu_title'      => __( 'Login Protect', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ new pages\LoginProtectDashboard( $this->plugin ), 'get_scheme' ],
            'parent_id'       => '',
            'priority'        => 32,
            'group'           => 'Access Control',
            'icon'            => 'dashicons-lock',
        ] );

        $admin->register_page( [
            'id'              => 'login-protect-settings',
            'page_title'      => __( 'Login Protect Settings', 'ultraguard-security-suite' ),
            'menu_title'      => __( 'Settings', 'ultraguard-security-suite' ),
            'capability'      => 'manage_options',
            'scheme_callback' => [ new pages\LoginProtectSettings( $this->plugin ), 'get_scheme' ],
            'parent_id'       => 'login-protect',
            'priority'        => 33,
            'group'           => 'Access Control',
            'icon'            => 'dashicons-admin-settings',
        ] );
    }

    public function enqueue_assets(): void {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin screen detection.
        $ug_page = sanitize_key( wp_unslash( $_GET['ug_page'] ?? ''  ) );
        if ( ! in_array( $ug_page, [ 'login-protect', 'login-protect-settings' ], true ) ) {
            return;
        }

        $module_url = plugin_dir_url( __FILE__ );
        $version    = defined( 'ULTRAGUARD_PRO_VERSION' ) ? ULTRAGUARD_PRO_VERSION : '1.0.0';

        wp_enqueue_style( 'ultraguard-login-protect-page', $module_url . 'assets/css/login-protect-page.css', [ 'admin-base', 'admin-components' ], $version );
        wp_enqueue_script( 'ultraguard-login-protect-page', $module_url . 'assets/js/login-protect-page.js', [ 'jquery', 'ultraguard-core', 'ultraguard-managers' ], $version, true );
        wp_localize_script( 'ultraguard-login-protect-page', 'ultraguardLoginProtect', [
            'nonce'   => wp_create_nonce( 'ultraguard_admin_nonce' ),
            'ajaxUrl' => self_admin_url( 'admin-ajax.php' ),
        ] );
    }
}
