<?php

namespace Waypoint\Agent\Admin;

use Waypoint\Agent\Base\Thing;

class Login_Logo extends Thing {

	const CUSTOMIZE_SETTING = 'waypoint_login_logo';

	public function attach_hooks(): void {
		add_action( 'customize_register',    [ $this, 'register_customizer_control' ] );
		add_action( 'login_enqueue_scripts', [ $this, 'enqueue_logo_css' ] );
		add_filter( 'login_headerurl',       [ $this, 'logo_url' ] );
		add_filter( 'login_headertext',      [ $this, 'logo_title' ] );
		add_action( 'login_footer',          [ $this, 'powered_by_footer' ] );
	}

	public function logo_url(): string {
		return home_url();
	}

	public function logo_title(): string {
		return get_bloginfo( 'name' );
	}

	public function powered_by_footer(): void {
		echo '<p class="waypoint-powered-by" style="text-align:center;color:#50575e;font-size:13px;margin-top:16px;">'
			. 'Powered by <a href="https://waypointagency.com" target="_blank" rel="noopener" style="color:#50575e;text-decoration:underline;">Waypoint</a>'
			. '</p>';
	}

	public function register_customizer_control( \WP_Customize_Manager $wp_customize ): void {
		$wp_customize->add_setting(
			self::CUSTOMIZE_SETTING,
			[
				'type'              => 'option',
				'capability'        => 'manage_options',
				'sanitize_callback' => 'absint',
				'transport'         => 'refresh',
			]
		);

		$wp_customize->add_control(
			new \WP_Customize_Media_Control(
				$wp_customize,
				self::CUSTOMIZE_SETTING,
				[
					'label'       => __( 'Login Page Logo', 'waypoint-agent' ),
					'description' => __( 'Replaces the WordPress logo on the login page. Falls back to Site Icon, then the Waypoint logo.', 'waypoint-agent' ),
					'section'     => 'title_tagline',
					'mime_type'   => 'image',
					'priority'    => 70,
				]
			)
		);
	}

	public function enqueue_logo_css(): void {
		$attachment_id = (int) get_option( self::CUSTOMIZE_SETTING, 0 );

		if ( $attachment_id ) {
			$url = wp_get_attachment_image_url( $attachment_id, 'full' );
		}

		// Fallback: Site Icon.
		if ( empty( $url ) ) {
			$url = get_site_icon_url( 84 );
		}

		if ( empty( $url ) ) {
			$url = plugins_url( 'assets/images/normal-mode.svg', WAYPOINT_AGENT_FILE );
		}

		$css = $this->single_image_css( esc_url( $url ) );

		wp_add_inline_style( 'login', $css );
	}

	private function single_image_css( string $url ): string {
		return "
.login h1 a {
	background-image: url({$url});
	background-size: contain;
	background-repeat: no-repeat;
	background-position: center top;
	width: 84px;
	height: 84px;
}";
	}

}
