<?php
/**
 * Optional public footer credit — “Powered by Auranet Builder”.
 *
 * WordPress.org compliance (Guideline 5 / 10):
 * - Credit is opt-in only (default OFF).
 * - Showing/hiding is always free — no license gate.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Frontend;

use AuraBuilder\Globals\SiteGlobals;
use AuraBuilder\Licensing\License;
use AuraBuilder\Support\Assets;

final class BrandCredit {

	/** When '1', show public credit (opt-in). Unique aptb_ prefix. */
	public const OPTION_OPT_IN     = 'aptb_credit_opt_in';
	public const OPTION_TEXT_COLOR = 'aptb_credit_text_color';
	public const OPTION_BG_COLOR   = 'aptb_credit_bg_color';

	public const DEFAULT_TEXT_COLOR = '#4f46e5';
	public const DEFAULT_BG_COLOR   = '#ffffff';

	public static function hooks(): void {
		add_action( 'wp_enqueue_scripts', array( self::class, 'enqueue' ), 30 );
		add_action( 'wp_footer', array( self::class, 'print_credit' ), 9999 );
	}

	/**
	 * Sanitize hex color or transparent keyword.
	 *
	 * @param mixed $value Raw value.
	 */
	public static function sanitize_color( $value, string $fallback = self::DEFAULT_TEXT_COLOR ): string {
		$value = is_string( $value ) ? trim( $value ) : '';
		if ( $value === '' ) {
			return $fallback;
		}
		$lower = strtolower( $value );
		if ( in_array( $lower, array( 'transparent', 'inherit' ), true ) ) {
			return $lower;
		}
		$hex = sanitize_hex_color( $value );
		if ( is_string( $hex ) && $hex !== '' ) {
			return $hex;
		}
		if ( preg_match( '/^#([0-9a-f]{3}|[0-9a-f]{6})$/i', $value ) ) {
			return strtolower( $value );
		}
		return $fallback;
	}

	public static function text_color(): string {
		$chrome = SiteGlobals::get()['chrome'] ?? array();
		$from_g = isset( $chrome['credit_text_color'] ) ? trim( (string) $chrome['credit_text_color'] ) : '';
		$raw    = $from_g !== ''
			? $from_g
			: (string) get_option( self::OPTION_TEXT_COLOR, self::DEFAULT_TEXT_COLOR );
		return (string) apply_filters(
			'aptb_credit_text_color',
			self::sanitize_color( $raw, self::DEFAULT_TEXT_COLOR )
		);
	}

	public static function bg_color(): string {
		$chrome = SiteGlobals::get()['chrome'] ?? array();
		$from_g = isset( $chrome['credit_bg_color'] ) ? trim( (string) $chrome['credit_bg_color'] ) : '';
		$raw    = $from_g !== ''
			? $from_g
			: (string) get_option( self::OPTION_BG_COLOR, self::DEFAULT_BG_COLOR );
		return (string) apply_filters(
			'aptb_credit_bg_color',
			self::sanitize_color( $raw, self::DEFAULT_BG_COLOR )
		);
	}

	public static function save_colors( string $text, string $bg ): void {
		$text = self::sanitize_color( $text, self::DEFAULT_TEXT_COLOR );
		$bg   = self::sanitize_color( $bg, self::DEFAULT_BG_COLOR );
		update_option( self::OPTION_TEXT_COLOR, $text, false );
		update_option( self::OPTION_BG_COLOR, $bg, false );
		$g = SiteGlobals::get();
		if ( ! isset( $g['chrome'] ) || ! is_array( $g['chrome'] ) ) {
			$g['chrome'] = array();
		}
		$g['chrome']['credit_text_color'] = $text;
		$g['chrome']['credit_bg_color']   = $bg;
		SiteGlobals::save( $g );
	}

	/**
	 * Whether the public credit should render.
	 * Free toggle only — never gated by a license key (Guideline 5).
	 */
	public static function should_show(): bool {
		if ( is_admin() ) {
			return false;
		}
		$opt = get_option( self::OPTION_OPT_IN, '0' );
		$on  = ( $opt === '1' || $opt === 1 || $opt === true );
		/**
		 * Filter show brand credit (must remain free to toggle in settings).
		 *
		 * @param bool $on Show.
		 */
		return (bool) apply_filters( 'aptb_show_brand_credit', $on );
	}

	public static function enqueue(): void {
		if ( ! self::should_show() ) {
			return;
		}
		$text = self::text_color();
		$bg   = self::bg_color();
		$css  = '.ab-brand-credit{display:block;text-align:center;padding:10px 16px 14px;font-size:12px;line-height:1.45;'
			. 'font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif;'
			. 'color:' . esc_attr( $text ) . ';background:' . esc_attr( $bg ) . ';}'
			. '.ab-brand-credit a{color:' . esc_attr( $text ) . ';text-decoration:none;font-weight:600;}'
			. '.ab-brand-credit a:hover{text-decoration:underline;opacity:.9;}';
		Assets::inline_style( 'aptb-brand-credit', $css );
	}

	public static function print_credit(): void {
		if ( ! self::should_show() ) {
			return;
		}
		$url  = (string) apply_filters( 'aptb_plugin_url', License::PLUGIN_URL );
		$text = (string) apply_filters(
			'aptb_brand_credit_text',
			__( 'Powered by Auranet Builder', 'auranet-page-theme-builder' )
		);
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped in render_html.
		echo self::render_html( $text, $url );
	}

	public static function render_html( string $text, string $url ): string {
		return sprintf(
			'<div class="ab-brand-credit" data-ab-credit="1" role="contentinfo">'
			. '<a href="%1$s" target="_blank" rel="noopener noreferrer nofollow">%2$s</a>'
			. '</div>' . "\n",
			esc_url( $url ),
			esc_html( $text )
		);
	}
}
