<?php

namespace RSSSL\Security\WordPress\Passkey;

use RSSSL\Pro\Security\WordPress\Two_Fa\Providers\Rsssl_Two_Factor_Passkey;

/**
 * Class Rsssl_Passkey
 * @package RSSSL\Security\WordPress\Passkey
 */
class Rsssl_Passkey
{
    public const NAMESPACE = 'really-simple-security/v1/two-fa/v2';

    /**
     * Rsssl_Passkey constructor.
     */
    public function __construct()
    {

    }

    /**
     * Run hooks
     * @return void
     */
    public static function run_hooks(): void
    {
        $self = new self();
        add_action('login_enqueue_scripts', array($self, 'enqueue_client_side_scripts'));
        /*
         * Start the controller for the passkey this is needed for all the logic to work.
         */
        Rsssl_Two_Factor_Passkey::start_controller('really-simple-security', 'v1', 'v2');
    }

    /**
     * Enqueue client side scripts
     * @return void
     */
    public function enqueue_client_side_scripts(): void
    {
        $this->enqueue_onboarding_styles();
        $this->enqueue_onboarding_scripts();
    }

    /**
     * Enqueue onboarding styles
     * @return void
     */
    public function enqueue_onboarding_styles(): void
    {
        $uri = trailingslashit(rsssl_url) . 'assets/features/two-fa/styles.css';
        $file_path = trailingslashit(rsssl_path) . 'assets/features/two-fa/styles.css';

        if (file_exists($file_path)) {
            wp_enqueue_style('rsssl-passkey-settings', $uri, array(), filemtime($file_path));
        }
    }

    /**
     * Enqueue onboarding scripts
     * @return void
     */
    public function enqueue_onboarding_scripts(): void
    {
        $uri = trailingslashit(rsssl_url) . 'assets/features/two-fa/assets.min.js';
        $file_path = trailingslashit(rsssl_path) . 'assets/features/two-fa/assets.min.js';
        if (file_exists($file_path)) {

            // The reason this now has a fallback is that the script is loaded as a module script,
            // which is not supported in all browsers. also when using wp_enqueue_script_module it totally broke
            // the login page. So we need to load it as a normal script and then add the type="module" to the script tag.
            $this->fallback_enqueue_script($uri, $file_path);

            add_filter('rsssl_two_factor_translatables', [Rsssl_Two_Factor_Passkey::class, 'translatables']);
            $login_nonce = wp_create_nonce('passkey_nonce');
            wp_localize_script('rsssl-passkey-login', 'rsssl_login', array(
                'nonce' => wp_create_nonce('wp_rest'),
                'origin' => 'passkey',
                'root' => esc_url_raw(rest_url(self::NAMESPACE)),
                'login_nonce' => $login_nonce,
                'redirect_to' => isset($_REQUEST['redirect_to']) ? esc_url_raw(wp_unslash($_REQUEST['redirect_to'])) : admin_url(),
                'translatables' => apply_filters('rsssl_two_factor_translatables', []),
            ));
        }
    }

    /**
     * Fallback enqueue script for browsers that do not support module scripts
     *
     * @param string $uri
     * @param string $file_path
     * @return void
     */
    private function fallback_enqueue_script(string $uri, string $file_path): void
    {
        wp_enqueue_script('rsssl-passkey-login', $uri, array(), filemtime($file_path), true);
        add_filter('script_loader_tag', static function ($tag, $handle) {
            if ($handle !== 'rsssl-passkey-login') {
                return $tag;
            }
            return str_replace(' src', ' type="module" src', $tag);
        }, 10, 2);
    }
}

/**
 * Run hooks for the class TODO: when the integrations rework is done, we should run the hook from the integrations
 */
Rsssl_Passkey::run_hooks();