<?php
/**
 * Front-end & banner logic.
 *
 * @package CookieJar
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class CookieJar {

	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend' ) );
		add_action( 'wp_footer', array( $this, 'render_banner' ), 20 );
	}

	public function enqueue_frontend() {
		if ( cookiejar_has_consent() ) {
			return;
		}

		wp_enqueue_style(
			'cookiejar',
			COOKIEJAR_PLUGIN_URL . 'assets/css/cookiejar.css',
			array(),
			COOKIEJAR_VERSION
		);

		wp_enqueue_script(
			'cookiejar',
			COOKIEJAR_PLUGIN_URL . 'assets/js/cookiejar.js',
			array(),
			COOKIEJAR_VERSION,
			true
		);

		$settings = $this->get_public_settings();
		$settings = apply_filters( 'cookiejar_public_settings', $settings );

		wp_localize_script(
			'cookiejar',
			'CookieJarData',
			array(
				'settings'      => $settings,
				'consentCookie' => cookiejar_consent_cookie_name(),
			)
		);
	}

	private function get_public_settings(): array {
		$s = cookiejar_get_settings();
		return array(
			'message'         => wp_kses_post( $s['message'] ?? '' ),
			'policy_url'      => esc_url( $s['policy_url'] ?? '' ),
			'dismiss_text'    => sanitize_text_field( $s['dismiss_text'] ?? '' ),
			'learn_more_text' => sanitize_text_field( $s['learn_more_text'] ?? '' ),
			'position'        => in_array( $s['position'] ?? 'bottom', array( 'top', 'bottom' ), true ) ? $s['position'] : 'bottom',
			'theme'           => in_array( $s['theme'] ?? 'light', array( 'light', 'dark' ), true ) ? $s['theme'] : 'light',
			'expiration_days' => absint( $s['expiration_days'] ?? 180 ),
		);
	}

	public function render_banner() {
		if ( cookiejar_has_consent() ) {
			return;
		}
		$s = $this->get_public_settings();

		do_action( 'cookiejar_banner_before', $s );
		?>
		<div id="cookiejar-banner"
			class="cookiejar-banner theme-<?php echo esc_attr( $s['theme'] ); ?> pos-<?php echo esc_attr( $s['position'] ); ?>"
			role="dialog"
			aria-live="polite"
			aria-label="<?php esc_attr_e( 'Cookie consent notice', 'cookiejar' ); ?>">
			<div class="cookiejar-message">
				<?php
				echo wp_kses_post( wpautop( $s['message'] ) );
				if ( $s['policy_url'] ) :
					?>
					<a class="cookiejar-policy" href="<?php echo esc_url( $s['policy_url'] ); ?>" target="_blank" rel="noopener nofollow">
						<?php echo esc_html( $s['learn_more_text'] ); ?>
					</a>
				<?php endif; ?>
			</div>
			<button type="button"
				class="cookiejar-accept"
				aria-label="<?php esc_attr_e( 'Accept cookies', 'cookiejar' ); ?>">
				<?php echo esc_html( $s['dismiss_text'] ); ?>
			</button>
		</div>
		<?php
		do_action( 'cookiejar_banner_after', $s );
	}
}

new CookieJar();