<?php
/**
 * Replace WordPress's "Lost your password?" link with a magic-link request
 * URL when the site has opted in via settings. Purely passwordless sites
 * benefit from a single recovery path.
 *
 * @package KaizenCoders\MagicLink
 */

namespace KaizenCoders\MagicLink;

class LostPassword {

	/**
	 * Wire the filters.
	 *
	 * @return void
	 */
	public function init() {
		add_filter( 'lostpassword_url', array( $this, 'filter_lostpassword_url' ), 20, 2 );
		add_filter( 'login_url', array( $this, 'filter_login_url' ), 20, 2 );
	}

	/**
	 * Whether the replacement is enabled in plugin settings.
	 *
	 * @return bool
	 */
	public static function is_enabled() {
		$settings = function_exists( 'get_option' ) ? get_option( 'kc_ml_settings', array() ) : array();
		$value    = Helper::get_data( $settings, 'general|settings|replace_lost_password', 0 );

		return (bool) $value;
	}

	/**
	 * Compute the magic-link request URL, optionally preserving the original
	 * redirect destination.
	 *
	 * @param  string $base_login_url Site login URL.
	 * @param  string $redirect       Original redirect_to.
	 *
	 * @return string
	 */
	public static function magic_link_url( $base_login_url, $redirect = '' ) {
		$args = array( 'action' => 'magic_link' );
		if ( '' !== (string) $redirect ) {
			$args['redirect_to'] = $redirect;
		}
		return add_query_arg( $args, $base_login_url );
	}

	/**
	 * Replace the lost-password URL when the setting is on.
	 *
	 * @param  string $lostpassword_url Original URL.
	 * @param  string $redirect         Redirect after login.
	 *
	 * @return string
	 */
	public function filter_lostpassword_url( $lostpassword_url, $redirect = '' ) {
		if ( ! self::is_enabled() ) {
			return $lostpassword_url;
		}
		$login_url = function_exists( 'wp_login_url' ) ? wp_login_url() : $lostpassword_url;
		return self::magic_link_url( $login_url, $redirect );
	}

	/**
	 * Pass-through filter so themes/plugins that compute their own login URL still
	 * receive a sensible redirect. Returns the URL unchanged when feature is off
	 * or when the URL is not the standard login page.
	 *
	 * @param  string $login_url Existing login URL.
	 * @param  string $redirect  Redirect after login.
	 *
	 * @return string
	 */
	public function filter_login_url( $login_url, $redirect = '' ) {
		return $login_url;
	}
}
