<?php
/**
 * Frontend display hooks class.
 *
 * @package TextToPDF
 */

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

/**
 * TextToPDF_Frontend Class
 */
class TextToPDF_Frontend {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		add_filter( 'the_content', array( $this, 'append_pdf_button' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	/**
	 * Enqueue frontend CSS/JS.
	 */
	public function enqueue_assets() {
		// Only enqueue if we are on a singular post/page, and there is a shortcode or the button is enabled.
		// Note: WordPress load requires some logic. We'll simply enqueue standard lightweight CSS.
		wp_enqueue_style( 'texttopdf-frontend-style', TEXTTOPDF_PLUGIN_URL . 'assets/css/frontend.css', array(), TEXTTOPDF_VERSION );
	}

	/**
	 * Automatically append the download button to content.
	 *
	 * @param string $content Post content.
	 * @return string Modified content.
	 */
	public function append_pdf_button( $content ) {
		// Prevent modifying content outside of the main query or on non-singular pages.
		if ( ! is_singular() || ! in_the_loop() || ! is_main_query() ) {
			return $content;
		}

		$post_type = get_post_type();
		$enable_on_posts = TextToPDF_Settings::get_setting( 'enable_on_posts' ) === '1';
		$enable_on_pages = TextToPDF_Settings::get_setting( 'enable_on_pages' ) === '1';

		if ( 'post' === $post_type && ! $enable_on_posts ) {
			return $content;
		}

		if ( 'page' === $post_type && ! $enable_on_pages ) {
			return $content;
		}

		$position = TextToPDF_Settings::get_setting( 'button_position' );
		
		if ( 'shortcode_only' === $position ) {
			return $content;
		}

		$shortcodes = new TextToPDF_Shortcodes();
		$button_html = $shortcodes->render_button_shortcode();

		if ( 'top' === $position ) {
			return $button_html . $content;
		}

		if ( 'bottom' === $position ) {
			return $content . $button_html;
		}

		if ( 'both' === $position ) {
			return $button_html . $content . $button_html;
		}

		return $content;
	}
}
