<?php
/**
 * REST controller — vehicle PDF spec sheet.
 *
 * Exposes:
 *   GET /trx-auto-dealer/v1/vehicles/{id}/pdf
 *
 * Renders the pdf-spec-sheet.php template through dompdf and streams the
 * resulting PDF as a download. Templates and fonts are bundled with the
 * dompdf package (vendor/dompdf/dompdf). Images are passed as local paths
 * so dompdf doesn't have to do an HTTP fetch from inside PHP.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\REST;

use ThemeREX\AutoDealer\Vendor\Dompdf\Dompdf;
use ThemeREX\AutoDealer\Vendor\Dompdf\Options as DompdfOptions;
use ThemeREX\AutoDealer\Frontend\TemplateLoader;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;
use WP_Error;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

use function ThemeREX\AutoDealer\getDealerMeta;
use function ThemeREX\AutoDealer\getSettings;
use function ThemeREX\AutoDealer\getVehicleSpecs;

class PdfController extends WP_REST_Controller {

	/** @var string */
	protected $namespace = 'trx-auto-dealer/v1';

	/** @var string */
	protected $rest_base = 'vehicles';

	public function register_routes(): void {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\d]+)/pdf',
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_pdf' ),
					'permission_callback' => '__return_true',
					'args'                => array(
						'id' => array(
							'type'     => 'integer',
							'required' => true,
						),
					),
				),
			)
		);
	}

	/**
	 * GET /vehicles/{id}/pdf — stream a generated spec sheet.
	 *
	 * @param WP_REST_Request $request
	 * @return WP_REST_Response|WP_Error
	 */
	public function get_pdf( $request ) {
		if ( ! class_exists( '\\ThemeREX\\AutoDealer\\Vendor\\Dompdf\\Dompdf' ) ) {
			return new WP_Error(
				'trx_ad_pdf_dompdf_missing',
				__( 'PDF rendering library is not installed.', 'trx-auto-dealer' ),
				array( 'status' => 500 )
			);
		}

		$id   = (int) $request->get_param( 'id' );
		$post = get_post( $id );

		if ( null === $post || VehiclePostType::POST_TYPE !== $post->post_type || 'publish' !== $post->post_status ) {
			return new WP_Error(
				'trx_ad_pdf_not_found',
				__( 'Vehicle not found.', 'trx-auto-dealer' ),
				array( 'status' => 404 )
			);
		}

		$specs = getVehicleSpecs( $id );
		if ( null === $specs ) {
			return new WP_Error(
				'trx_ad_pdf_specs_missing',
				__( 'Vehicle specifications not available.', 'trx-auto-dealer' ),
				array( 'status' => 404 )
			);
		}

		$html = $this->buildHtml( $post, $specs );

		try {
			$options = new DompdfOptions();
			$options->set( 'isRemoteEnabled', false );          // No remote URLs — paths only.
			$options->set( 'isHtml5ParserEnabled', true );
			$options->set( 'defaultFont', 'DejaVu Sans' );

			$dompdf = new Dompdf( $options );
			$dompdf->loadHtml( $html, 'UTF-8' );
			$dompdf->setPaper( 'A4', 'portrait' );
			$dompdf->render();
			$pdf = (string) $dompdf->output();
		} catch ( \Throwable $e ) {
			return new WP_Error(
				'trx_ad_pdf_render_failed',
				$e->getMessage(),
				array( 'status' => 500 )
			);
		}

		nocache_headers();
		header( 'Content-Type: application/pdf' );
		header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( ( $post->post_name ?: 'listing-' . $id ) . '.pdf' ) . '"' );
		header( 'Content-Length: ' . strlen( $pdf ) );
		// Binary application/pdf download stream generated by the bundled
		// (scoped) dompdf library -- not an HTML context, escaping functions
		// would corrupt the file.
		echo $pdf; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary stream, not an HTML context.
		exit;
	}

	/**
	 * Build the HTML the PDF renderer will consume.
	 *
	 * @param \WP_Post             $post
	 * @param array<string, mixed> $specs
	 * @return string
	 */
	private function buildHtml( \WP_Post $post, array $specs ): string {
		$dealer_id = (int) ( $specs['dealer_id'] ?? get_post_meta( $post->ID, '_trx_ad_dealer_id', true ) );
		$dealer    = $dealer_id > 0 ? getDealerMeta( $dealer_id ) : array();

		// Resolve gallery → file paths so dompdf doesn't need HTTP.
		$gallery_meta = get_post_meta( $post->ID, \TRX_AD_PREFIX . 'gallery', true );
		$ids          = array();
		if ( is_string( $gallery_meta ) && '' !== $gallery_meta ) {
			$decoded = json_decode( $gallery_meta, true );
			if ( is_array( $decoded ) ) {
				$ids = array_map( 'intval', $decoded );
			}
		}
		$thumb_id = (int) get_post_thumbnail_id( $post->ID );
		if ( $thumb_id > 0 && ! in_array( $thumb_id, $ids, true ) ) {
			array_unshift( $ids, $thumb_id );
		}

		$images = array();
		foreach ( $ids as $img_id ) {
			$path = (string) get_attached_file( (int) $img_id );
			if ( '' !== $path && file_exists( $path ) ) {
				$images[] = $path;
			}
		}

		$currency     = (string) getSettings( 'currency_symbol', '$' );
		$generated_at = wp_date( get_option( 'date_format', 'F j, Y' ) );

		ob_start();
		$template = TemplateLoader::locateTemplate( 'pdf-spec-sheet.php' );
		if ( '' === $template || ! is_readable( $template ) ) {
			ob_end_clean();
			return '<!doctype html><meta charset="utf-8"><body><p>Template missing.</p>';
		}
		// Variables consumed inside the template.
		include $template;
		return (string) ob_get_clean();
	}
}
