<?php
/**
 * PDF Generator logic handling form submissions and rendering.
 *
 * @package TextToPDF
 */

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

use Dompdf\Dompdf;
use Dompdf\Options;

/**
 * TextToPDF_Generator Class
 */
class TextToPDF_Generator {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		// Frontend hooks for form submission.
		add_action( 'admin_post_nopriv_texttopdf_generate_from_text', array( $this, 'handle_text_submission' ) );
		add_action( 'admin_post_texttopdf_generate_from_text', array( $this, 'handle_text_submission' ) );

		add_action( 'admin_post_nopriv_texttopdf_generate_from_post', array( $this, 'handle_post_submission' ) );
		add_action( 'admin_post_texttopdf_generate_from_post', array( $this, 'handle_post_submission' ) );
	}

	/**
	 * Handle generation from standard text input.
	 */
	public function handle_text_submission() {
		// Nonce check.
		if ( ! isset( $_POST['texttopdf_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['texttopdf_nonce'] ) ), 'texttopdf_generate_from_text_nonce' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'texttopdfnet-text-web-to-pdf' ) );
		}

		$title   = isset( $_POST['texttopdf_title'] ) ? sanitize_text_field( wp_unslash( $_POST['texttopdf_title'] ) ) : '';
		$content = isset( $_POST['texttopdf_content'] ) ? sanitize_textarea_field( wp_unslash( $_POST['texttopdf_content'] ) ) : '';

		if ( empty( $content ) ) {
			wp_die( esc_html__( 'Text content is required.', 'texttopdfnet-text-web-to-pdf' ) );
		}

		$html = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head><body>';
		$html .= $this->get_watermark_html();
		if ( ! empty( $title ) ) {
			$html .= '<h1>' . esc_html( $title ) . '</h1>';
		}
		
		// Convert text to basic paragraphs.
		$html .= wpautop( esc_html( $content ) );
		$html .= '</body></html>';

		// Generate file name. Safe fallback.
		$file_name = sanitize_file_name( empty( $title ) ? 'document-' . gmdate( 'Y-m-d' ) : $title );

		$this->generate_pdf( $html, $file_name . '.pdf' );
	}

	/**
	 * Handle generation from WordPress post content.
	 */
	public function handle_post_submission() {
		// Nonce check.
		if ( ! isset( $_GET['texttopdf_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['texttopdf_nonce'] ) ), 'texttopdf_generate_from_post_nonce' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'texttopdfnet-text-web-to-pdf' ) );
		}

		$post_id = isset( $_GET['post_id'] ) ? intval( $_GET['post_id'] ) : 0;
		if ( ! $post_id ) {
			wp_die( esc_html__( 'Invalid post.', 'texttopdfnet-text-web-to-pdf' ) );
		}

		$post = get_post( $post_id );
		if ( ! $post ) {
			wp_die( esc_html__( 'Post not found.', 'texttopdfnet-text-web-to-pdf' ) );
		}

		// Settings checks.
		$include_title     = TextToPDF_Settings::get_setting( 'include_title' ) === '1';
		$include_image     = TextToPDF_Settings::get_setting( 'include_featured_image' ) === '1';
		$include_author    = TextToPDF_Settings::get_setting( 'include_author' ) === '1';
		$include_date      = TextToPDF_Settings::get_setting( 'include_date' ) === '1';
		$header_text       = TextToPDF_Settings::get_setting( 'header_text' );
		$footer_text       = TextToPDF_Settings::get_setting( 'footer_text' );
		
		$html = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><style>img { max-width: 100%; height: auto; } .pdf-header { text-align: center; color: #777; margin-bottom: 20px; font-size: 12px; border-bottom: 1px solid #ddd; padding-bottom: 10px; } .pdf-footer { text-align: center; color: #777; margin-top: 30px; font-size: 12px; border-top: 1px solid #ddd; padding-top: 10px; position: fixed; bottom: 0; width: 100%; } .pdf-meta { color: #555; font-size: 12px; margin-bottom: 20px; }</style></head><body>';
		
		$html .= $this->get_watermark_html();
		// Header Text
		if ( ! empty( $header_text ) ) {
			$html .= '<div class="pdf-header">' . esc_html( $header_text ) . '</div>';
		}

		// Title
		if ( $include_title ) {
			$html .= '<h1>' . esc_html( get_the_title( $post ) ) . '</h1>';
		}

		// Meta
		if ( $include_author || $include_date ) {
			$html .= '<div class="pdf-meta">';
			if ( $include_author ) {
				$author_id = $post->post_author;
				$author_name = get_the_author_meta( 'display_name', $author_id );
				$html .= '<span><strong>' . esc_html__( 'Author:', 'texttopdfnet-text-web-to-pdf' ) . '</strong> ' . esc_html( $author_name ) . '</span><br>';
			}
			if ( $include_date ) {
				$html .= '<span><strong>' . esc_html__( 'Date:', 'texttopdfnet-text-web-to-pdf' ) . '</strong> ' . esc_html( get_the_date( '', $post ) ) . '</span>';
			}
			$html .= '</div>';
		}

		// Featured Image
		if ( $include_image && has_post_thumbnail( $post ) ) {
			// Using get_attached_file for local path to prevent remote fetching issues in DomPDF.
			$thumb_id = get_post_thumbnail_id( $post );
			$image_path = get_attached_file( $thumb_id );
			if ( $image_path && file_exists( $image_path ) ) {
				$html .= '<div style="margin-bottom: 20px;"><img src="' . esc_attr( $image_path ) . '" alt="' . esc_attr( get_the_title( $post ) ) . '"/></div>';
			}
		}

		// Content. 
		// Strip shortcodes that might break layout, apply standard content formatting safely.
		$content = strip_shortcodes( $post->post_content );
		$content = wptexturize( $content );
		$content = wpautop( $content );
		$content = shortcode_unautop( $content );
		$content = wp_filter_content_tags( $content );
		$content = str_replace( ']]>', ']]&gt;', $content );
		
		// Using wp_kses_post to clean up scripts, iframes, etc.
		$html .= wp_kses_post( $content );

		// Footer Text
		if ( ! empty( $footer_text ) ) {
			$html .= '<div class="pdf-footer">' . esc_html( $footer_text ) . '</div>';
		}

		$html .= '</body></html>';

		// Metadata: increment download count.
		$count = (int) get_post_meta( $post_id, 'texttopdf_download_count', true );
		update_post_meta( $post_id, 'texttopdf_download_count', $count + 1 );

		// Handle file name generation
		$pattern = TextToPDF_Settings::get_setting( 'file_name_pattern' );
		$file_name_string = str_replace( 
			array( '{title}', '{date}' ), 
			array( get_the_title( $post ), gmdate( 'Y-m-d' ) ), 
			$pattern 
		);
		$file_name = sanitize_file_name( $file_name_string );

		$this->generate_pdf( $html, $file_name . '.pdf' );
	}

	/**
	 * Get watermark HTML.
	 */
	private function get_watermark_html() {
		$text   = TextToPDF_Settings::get_setting( 'watermark_text' );
		$logo   = TextToPDF_Settings::get_setting( 'watermark_logo' );
		$size   = absint( TextToPDF_Settings::get_setting( 'watermark_size' ) );
		$pos    = TextToPDF_Settings::get_setting( 'watermark_position' );

		if ( empty( $text ) && empty( $logo ) ) {
			return '';
		}

		if ( ! $size ) {
			$size = 500;
		}

		$opacity = TextToPDF_Settings::get_setting( 'watermark_opacity' );
		if ( ! $opacity ) {
			$opacity = 30;
		}
		$opacity_decimal = intval( $opacity ) / 100;

		$style = 'position: fixed; opacity: ' . esc_attr( $opacity_decimal ) . '; z-index: -100; text-align: center; ';
		
		if ( 'top-left' === $pos ) {
			$style .= 'top: 20px; left: 20px; text-align: left;';
		} elseif ( 'top-right' === $pos ) {
			$style .= 'top: 20px; right: 20px; text-align: right;';
		} elseif ( 'bottom-left' === $pos ) {
			$style .= 'bottom: 20px; left: 20px; text-align: left;';
		} elseif ( 'bottom-right' === $pos ) {
			$style .= 'bottom: 20px; right: 20px; text-align: right;';
		} elseif ( 'center' === $pos ) {
			$style .= 'top: 35%; width: 100%; text-align: center;';
		}

		$html = '<div id="texttopdf-watermark" style="' . esc_attr( $style ) . '">';
		if ( ! empty( $logo ) ) {
			$attachment_id = attachment_url_to_postid( $logo );
			$src = $logo;
			if ( $attachment_id ) {
				$path = get_attached_file( $attachment_id );
				if ( $path && file_exists( $path ) ) {
					$src = $path;
				}
			}
			$html .= '<img src="' . esc_attr( $src ) . '" style="width: ' . esc_attr( $size ) . 'px; height: auto;" /><br/>';
		}
		if ( ! empty( $text ) ) {
			$html .= '<div style="color: #cccccc; font-family: Helvetica; font-size: 36px; margin-top: 10px; font-weight: bold;">' . esc_html( $text ) . '</div>';
		}
		$html .= '</div>';
		return $html;
	}

	/**
	 * Core PDF Generation Wrapper using Dompdf.
	 *
	 * @param string $html Safe HTML content.
	 * @param string $filename Output file name.
	 */
	private function generate_pdf( $html, $filename ) {
		// Check if Dompdf exists (handles case where user didn't run composer).
		if ( ! class_exists( 'Dompdf\Dompdf' ) ) {
			wp_die( esc_html__( 'PDF generation library (Dompdf) is missing. Please run "composer install --no-dev" in the plugin directory.', 'texttopdfnet-text-web-to-pdf' ) );
		}

		try {
			$options = new Options();
			$options->set( 'defaultFont', 'Helvetica' );
			$options->set( 'isHtml5ParserEnabled', true );
			$options->set( 'isRemoteEnabled', false ); // Security: prevent remote file loading!
			$options->set( 'chroot', ABSPATH ); // Prevent path traversal reading external files.

			$dompdf = new Dompdf( $options );

			$dompdf->loadHtml( $html, 'UTF-8' );

			$page_size = TextToPDF_Settings::get_setting( 'page_size' ) === 'letter' ? 'letter' : 'A4';
			$dompdf->setPaper( $page_size, 'portrait' );

			$dompdf->render();

			// Stream directly down to user memory safely.
			$dompdf->stream( $filename, array( 'Attachment' => 1 ) );
			exit;

		} catch ( Exception $e ) {
			wp_die( esc_html__( 'Failed to generate PDF. Error: ', 'texttopdfnet-text-web-to-pdf' ) . esc_html( $e->getMessage() ) );
		}
	}
}
