<?php

defined( 'ABSPATH' ) || exit;

/**
 * Login Page Branding module.
 *
 * Kadence Pro styles the front-end and the wp-admin chrome, but leaves
 * wp-login.php as a stock WordPress page. Every Bowden Works client build
 * ends up rebranding that page by hand. This module makes it a configurable
 * pair-up with the existing Core -> Branding tab.
 *
 * What it controls:
 *  - Logo image, width, height (replaces the WordPress wordmark above the form).
 *  - The URL and title-attribute of the logo link (defaults to home URL + blog name).
 *  - Page background colour.
 *  - Form-panel background colour.
 *  - Primary-button background + text colour.
 *  - Toggle to hide the "Back to <site>" link below the form.
 *  - Toggle to hide the "Lost your password?" link below the form.
 *
 * Hooks:
 *  - login_enqueue_scripts : injects a <style> block built from the saved settings.
 *  - login_headerurl       : changes where the logo links to.
 *  - login_headertext      : changes the logo link's title attribute.
 *  - admin_enqueue_scripts : conditional wp.media enqueue for this module's tab.
 *
 * All persisted values default to empty / WP defaults, so enabling the module
 * with no configuration is a no-op.
 *
 * @package BW_Dev
 */

class BW_Dev_Module_Login_Branding implements BW_Dev_Module_Interface {

	const COLOR_REGEX = '/^#[0-9a-fA-F]{3,8}$/';

	public function slug(): string {
		return 'login_branding';
	}

	public function label(): string {
		return __( 'Login Page Branding', 'bw-dev' );
	}

	public function group(): string {
		return 'core';
	}

	public function default_settings(): array {
		return array(
			'logo_url'          => '',
			'logo_width'        => 320,
			'logo_height'       => 80,
			'logo_link_url'     => '',
			'logo_link_text'    => '',
			'bg_color'          => '',
			'form_bg_color'     => '',
			'button_color'      => '',
			'button_text_color' => '',
			'hide_back_link'    => false,
			'hide_lostpassword' => false,
		);
	}

	public function sanitize( array $data ): array {
		$logo_url      = isset( $data['logo_url'] ) ? esc_url_raw( wp_unslash( (string) $data['logo_url'] ) ) : '';
		$logo_link_url = isset( $data['logo_link_url'] ) ? esc_url_raw( wp_unslash( (string) $data['logo_link_url'] ) ) : '';
		$logo_link_txt = isset( $data['logo_link_text'] ) ? sanitize_text_field( wp_unslash( (string) $data['logo_link_text'] ) ) : '';

		$logo_w = isset( $data['logo_width'] ) ? (int) $data['logo_width'] : 320;
		$logo_h = isset( $data['logo_height'] ) ? (int) $data['logo_height'] : 80;
		// Clamp to a sensible range so a typo doesn't blow up the page layout.
		$logo_w = max( 32, min( 600, $logo_w ) );
		$logo_h = max( 32, min( 400, $logo_h ) );

		return array(
			'logo_url'          => $logo_url,
			'logo_width'        => $logo_w,
			'logo_height'       => $logo_h,
			'logo_link_url'     => $logo_link_url,
			'logo_link_text'    => $logo_link_txt,
			'bg_color'          => $this->sanitize_hex( $data['bg_color'] ?? '' ),
			'form_bg_color'     => $this->sanitize_hex( $data['form_bg_color'] ?? '' ),
			'button_color'      => $this->sanitize_hex( $data['button_color'] ?? '' ),
			'button_text_color' => $this->sanitize_hex( $data['button_text_color'] ?? '' ),
			'hide_back_link'    => ! empty( $data['hide_back_link'] ),
			'hide_lostpassword' => ! empty( $data['hide_lostpassword'] ),
		);
	}

	private function sanitize_hex( $value ): string {
		$value = strtolower( trim( (string) $value ) );
		if ( '' === $value ) {
			return '';
		}
		if ( preg_match( self::COLOR_REGEX, $value ) ) {
			return $value;
		}
		return '';
	}

	public function register(): void {
		add_action( 'login_enqueue_scripts', array( $this, 'inject_styles' ) );
		add_filter( 'login_headerurl',       array( $this, 'filter_logo_url' ) );
		add_filter( 'login_headertext',      array( $this, 'filter_logo_text' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_media' ) );
	}

	public function filter_logo_url( $url ) {
		$configured = (string) bw_dev()->settings()->get( $this->slug(), 'logo_link_url', '' );
		return '' !== $configured ? $configured : $url;
	}

	public function filter_logo_text( $text ) {
		$configured = (string) bw_dev()->settings()->get( $this->slug(), 'logo_link_text', '' );
		return '' !== $configured ? $configured : $text;
	}

	public function maybe_enqueue_media( $hook ): void {
		if ( 'settings_page_' . BW_Dev_Admin_Page::MENU_SLUG !== $hook ) {
			return;
		}
		$query = wp_unslash( $_GET ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$tab   = isset( $query['tab'] ) ? sanitize_key( (string) $query['tab'] ) : 'modules';
		if ( $this->slug() !== $tab ) {
			return;
		}
		wp_enqueue_media();
	}

	public function inject_styles(): void {
		$css = $this->build_css();
		if ( '' === $css ) {
			return;
		}
		echo "<style id=\"bw-dev-login-branding\">\n" . $css . "</style>\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS built from sanitized values.
	}

	private function build_css(): string {
		$s = bw_dev()->settings()->get( $this->slug() );
		if ( ! is_array( $s ) ) {
			return '';
		}
		$css = '';

		$logo_url = isset( $s['logo_url'] ) ? (string) $s['logo_url'] : '';
		if ( '' !== $logo_url ) {
			$w        = max( 32, (int) ( $s['logo_width'] ?? 320 ) );
			$h        = max( 32, (int) ( $s['logo_height'] ?? 80 ) );
			$safe_url = esc_url( $logo_url );
			$css .= "#login h1 a, .login h1 a { background-image: url({$safe_url}); background-size: contain; background-position: center; background-repeat: no-repeat; width: {$w}px; height: {$h}px; }\n";
		}

		$bg = isset( $s['bg_color'] ) ? $this->sanitize_hex( $s['bg_color'] ) : '';
		if ( '' !== $bg ) {
			$css .= "body.login { background-color: {$bg}; }\n";
		}

		$form_bg = isset( $s['form_bg_color'] ) ? $this->sanitize_hex( $s['form_bg_color'] ) : '';
		if ( '' !== $form_bg ) {
			$css .= "body.login #loginform, body.login #lostpasswordform, body.login #registerform { background-color: {$form_bg}; }\n";
		}

		$btn = isset( $s['button_color'] ) ? $this->sanitize_hex( $s['button_color'] ) : '';
		if ( '' !== $btn ) {
			$css .= "body.login .wp-core-ui .button-primary, body.login #wp-submit { background: {$btn}; border-color: {$btn}; box-shadow: none; text-shadow: none; }\n";
			$css .= "body.login .wp-core-ui .button-primary:hover, body.login #wp-submit:hover, body.login .wp-core-ui .button-primary:focus, body.login #wp-submit:focus { background: {$btn}; border-color: {$btn}; filter: brightness(0.92); }\n";
		}

		$btn_txt = isset( $s['button_text_color'] ) ? $this->sanitize_hex( $s['button_text_color'] ) : '';
		if ( '' !== $btn_txt ) {
			$css .= "body.login .wp-core-ui .button-primary, body.login #wp-submit { color: {$btn_txt}; }\n";
		}

		if ( ! empty( $s['hide_back_link'] ) ) {
			$css .= "body.login #backtoblog { display: none !important; }\n";
		}
		if ( ! empty( $s['hide_lostpassword'] ) ) {
			$css .= "body.login #nav { display: none !important; }\n";
		}

		return $css;
	}

	public function render_tab(): void {
		$s = bw_dev()->settings()->get( $this->slug() );
		if ( ! is_array( $s ) ) {
			$s = $this->default_settings();
		}

		$base = BW_Dev_Settings::OPTION . '[' . $this->slug() . ']';
		?>
		<p class="description">
			<?php esc_html_e( 'Brand the WordPress login screen at /wp-login.php. Every field is optional — empty values keep WordPress\'s defaults.', 'bw-dev' ); ?>
		</p>

		<h3><?php esc_html_e( 'Logo', 'bw-dev' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><label for="bw-dev-login-branding-logo-url"><?php esc_html_e( 'Logo image', 'bw-dev' ); ?></label></th>
					<td>
						<div style="display:flex;align-items:center;gap:10px;">
							<input type="text" id="bw-dev-login-branding-logo-url" name="<?php echo esc_attr( $base . '[logo_url]' ); ?>" value="<?php echo esc_attr( (string) $s['logo_url'] ); ?>" class="regular-text" placeholder="https://..." />
							<button type="button" id="bw-dev-login-branding-upload" class="button button-secondary"><?php esc_html_e( 'Upload / Select', 'bw-dev' ); ?></button>
							<button type="button" id="bw-dev-login-branding-clear" class="button button-link-delete"><?php esc_html_e( 'Clear', 'bw-dev' ); ?></button>
						</div>
						<div id="bw-dev-login-branding-preview" style="margin-top:14px;">
							<?php if ( '' !== (string) $s['logo_url'] ) : ?>
								<img src="<?php echo esc_url( (string) $s['logo_url'] ); ?>" alt="" style="max-width:320px;max-height:120px;border:1px solid #ccc;padding:5px;background:#fff;" />
							<?php endif; ?>
						</div>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Logo size (px)', 'bw-dev' ); ?></th>
					<td>
						<label><?php esc_html_e( 'Width', 'bw-dev' ); ?>
							<input type="number" min="32" max="600" step="1" name="<?php echo esc_attr( $base . '[logo_width]' ); ?>" value="<?php echo esc_attr( (string) (int) $s['logo_width'] ); ?>" class="small-text" />
						</label>
						&nbsp;
						<label><?php esc_html_e( 'Height', 'bw-dev' ); ?>
							<input type="number" min="32" max="400" step="1" name="<?php echo esc_attr( $base . '[logo_height]' ); ?>" value="<?php echo esc_attr( (string) (int) $s['logo_height'] ); ?>" class="small-text" />
						</label>
						<p class="description"><?php esc_html_e( 'Container size for the logo. The image is scaled to fit (contain), so any aspect ratio works.', 'bw-dev' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw-dev-login-branding-link-url"><?php esc_html_e( 'Logo link URL', 'bw-dev' ); ?></label></th>
					<td>
						<input type="text" id="bw-dev-login-branding-link-url" name="<?php echo esc_attr( $base . '[logo_link_url]' ); ?>" value="<?php echo esc_attr( (string) $s['logo_link_url'] ); ?>" class="regular-text" placeholder="<?php echo esc_attr( home_url( '/' ) ); ?>" />
						<p class="description"><?php esc_html_e( 'Where the logo links to. Empty = home page.', 'bw-dev' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw-dev-login-branding-link-text"><?php esc_html_e( 'Logo link title', 'bw-dev' ); ?></label></th>
					<td>
						<input type="text" id="bw-dev-login-branding-link-text" name="<?php echo esc_attr( $base . '[logo_link_text]' ); ?>" value="<?php echo esc_attr( (string) $s['logo_link_text'] ); ?>" class="regular-text" placeholder="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" />
						<p class="description"><?php esc_html_e( 'The link\'s title attribute (screen-reader label). Empty = site name.', 'bw-dev' ); ?></p>
					</td>
				</tr>
			</tbody>
		</table>

		<h3><?php esc_html_e( 'Colours', 'bw-dev' ); ?></h3>
		<p class="description"><?php esc_html_e( 'Use hex values like #ffffff or #f6f7f7. Empty = WordPress default.', 'bw-dev' ); ?></p>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><label for="bw-dev-login-branding-bg"><?php esc_html_e( 'Page background', 'bw-dev' ); ?></label></th>
					<td>
						<input type="text" id="bw-dev-login-branding-bg" name="<?php echo esc_attr( $base . '[bg_color]' ); ?>" value="<?php echo esc_attr( (string) $s['bg_color'] ); ?>" class="regular-text code" placeholder="#f0f0f1" />
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw-dev-login-branding-form-bg"><?php esc_html_e( 'Form panel background', 'bw-dev' ); ?></label></th>
					<td>
						<input type="text" id="bw-dev-login-branding-form-bg" name="<?php echo esc_attr( $base . '[form_bg_color]' ); ?>" value="<?php echo esc_attr( (string) $s['form_bg_color'] ); ?>" class="regular-text code" placeholder="#ffffff" />
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw-dev-login-branding-btn"><?php esc_html_e( 'Primary button colour', 'bw-dev' ); ?></label></th>
					<td>
						<input type="text" id="bw-dev-login-branding-btn" name="<?php echo esc_attr( $base . '[button_color]' ); ?>" value="<?php echo esc_attr( (string) $s['button_color'] ); ?>" class="regular-text code" placeholder="#2271b1" />
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="bw-dev-login-branding-btn-text"><?php esc_html_e( 'Primary button text', 'bw-dev' ); ?></label></th>
					<td>
						<input type="text" id="bw-dev-login-branding-btn-text" name="<?php echo esc_attr( $base . '[button_text_color]' ); ?>" value="<?php echo esc_attr( (string) $s['button_text_color'] ); ?>" class="regular-text code" placeholder="#ffffff" />
					</td>
				</tr>
			</tbody>
		</table>

		<h3><?php esc_html_e( 'Hide links', 'bw-dev' ); ?></h3>
		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row"><?php esc_html_e( 'Below the form', 'bw-dev' ); ?></th>
					<td>
						<fieldset>
							<label>
								<input type="checkbox" name="<?php echo esc_attr( $base . '[hide_back_link]' ); ?>" value="1" <?php checked( ! empty( $s['hide_back_link'] ) ); ?> />
								<?php esc_html_e( 'Hide "← Back to <site name>"', 'bw-dev' ); ?>
							</label><br />
							<label>
								<input type="checkbox" name="<?php echo esc_attr( $base . '[hide_lostpassword]' ); ?>" value="1" <?php checked( ! empty( $s['hide_lostpassword'] ) ); ?> />
								<?php esc_html_e( 'Hide "Lost your password?" / "Register"', 'bw-dev' ); ?>
							</label>
						</fieldset>
					</td>
				</tr>
			</tbody>
		</table>

		<script>
		(function ($) {
			$(function () {
				var $url     = $('#bw-dev-login-branding-logo-url');
				var $preview = $('#bw-dev-login-branding-preview');
				var frame;

				$('#bw-dev-login-branding-upload').on('click', function (e) {
					e.preventDefault();
					if (frame) { frame.open(); return; }
					frame = wp.media({
						title:    <?php echo wp_json_encode( __( 'Choose login logo', 'bw-dev' ) ); ?>,
						button:   { text: <?php echo wp_json_encode( __( 'Use as login logo', 'bw-dev' ) ); ?> },
						multiple: false
					});
					frame.on('select', function () {
						var attachment = frame.state().get('selection').first().toJSON();
						$url.val(attachment.url).trigger('change');
					});
					frame.open();
				});

				$('#bw-dev-login-branding-clear').on('click', function (e) {
					e.preventDefault();
					$url.val('').trigger('change');
				});

				$url.on('change', function () {
					var val = $url.val();
					if (val) {
						$preview.html('<img src="' + val + '" alt="" style="max-width:320px;max-height:120px;border:1px solid #ccc;padding:5px;background:#fff;" />');
					} else {
						$preview.empty();
					}
				});
			});
		})(jQuery);
		</script>
		<?php
	}

	public function uninstall(): void {
		// Settings live under bw_dev_settings — root option drop covers them.
	}
}
