<?php
/**
 * Editor initialization and asset management.
 *
 * @package PDFDraft
 */

namespace PDFDraft;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

use PDFDraft\Services\FontsService;
use PDFDraft\Traits\Hooks;

/**
 * Handles the PDFDraft editor page rendering and scripts.
 */
class Editor {

	use Hooks;

	/**
	 * Fonts service instance.
	 *
	 * @var FontsService
	 */
	private $fontsService;

	/**
	 * Constructor.
	 *
	 * @param FontsService $fontsService Fonts service instance.
	 */
	public function __construct( FontsService $fontsService ) {
		$this->fontsService = $fontsService;
	}

	/**
	 * Initialize the editor page.
	 *
	 * @return void
	 */
	public function init() {
		header( 'Content-Type: ' . get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' ) );

		remove_all_actions( 'wp_head' );
		remove_all_actions( 'wp_print_styles' );
		remove_all_actions( 'wp_print_head_scripts' );
		remove_all_actions( 'wp_footer' );

		add_action( 'wp_head', 'wp_enqueue_scripts', 1 );
		add_action( 'wp_head', 'wp_print_styles', 8 );
		add_action( 'wp_head', 'wp_print_head_scripts', 9 );
		add_action( 'wp_head', 'wp_site_icon' );

		add_action( 'wp_footer', 'wp_print_footer_scripts', 20 );
		add_action( 'wp_footer', 'wp_auth_check_html', 30 );

		remove_all_actions( 'wp_enqueue_scripts' );
		remove_all_actions( 'after_wp_tiny_mce' );

		add_action( 'wp_enqueue_scripts', array( $this, 'enqueueScripts' ), 999999 );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueueStyles' ), 999999 );

		wp_enqueue_media();

		$this->doAction( 'pdfdraft_builder_init' );

		include_once PDFDRAFT_PLUGIN_DIR . '/templates/pdfdraft.php';

		exit;
	}

	/**
	 * Enqueue editor JavaScript files.
	 *
	 * @return void
	 */
	public function enqueueScripts() {
		$this->doAction( 'pdfdraft_editor_before_enqueue_scripts' );
		wp_localize_script(
			'pdfdraft-editor',
			'__PDFDRAFT__',
			$this->applyFilters(
				'pdfdraft_editor_localized_data',
				array(
					/**
					 * When true, pro-gated UI is removed from the DOM entirely
					 * instead of showing a disabled overlay with the Crown badge.
					 * Override via: add_filter( 'pdfdraft_hide_pro_features', '__return_true' );
					 */
					'hidePro'                            => (bool) $this->applyFilters( 'pdfdraft_hide_pro_features', true ),
					'restUrl'                            => rest_url( 'pdfdraft/v1' ),
					'timezone'                           => wp_timezone(),
					'dashboardUrl'                       => admin_url(),
					'allowedMimeTypes'                   => get_allowed_mime_types(),
					'maxUploadSize'                      => wp_max_upload_size() / 1024 / 1024,
					'defaultFont'                        => current( $this->fontsService->getFontById( 'inter' ) ),
					'baseUri'                            => PDFDRAFT_DIST_URI,
					'autosaveInterval'                   => defined( 'AUTOSAVE_INTERVAL' ) ? AUTOSAVE_INTERVAL : false,
					'for'                                => isset( $_GET['for'] ) ? sanitize_text_field( wp_unslash( $_GET['for'] ) ) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
					'pdfdraftPluginsActive'              => array(),
					'createFromScratchByFor'             => array(),
					// Lets the main-app Projects UI lock legacy Woo invoice designs when the add-on is inactive (matches option used by that plugin).
					'wooInvoiceActiveDesignSlugFallback' => (string) get_option( 'pdfdraft_pdf_invoices_for_woocommerce_active_design_slug', '' ),
					/**
					 * Maximum design dimensions in inches (all units are derived from this).
					 * Override via: add_filter( 'pdfdraft_design_dimension_limits_inches', function( $limits ) { ... } );
					 */
					'designDimensionLimitsInches'        => $this->applyFilters(
						'pdfdraft_design_dimension_limits_inches',
						array( 'min' => 0.1, 'max' => 100 )
					),
					'previewDummyData'                   => $this->applyFilters(
						'pdfdraft_editor_preview_dummy_data',
						$this->getDefaultPreviewDummyData()
					),
					'previewDummyItems'                  => $this->applyFilters(
						'pdfdraft_editor_preview_dummy_items',
						$this->getDefaultPreviewDummyItems()
					),
				)
			)
		);
		wp_enqueue_script( 'pdfdraft-editor' );
		$this->doAction( 'pdfdraft_editor_after_enqueue_scripts' );
	}

	/**
	 * Enqueue editor stylesheets.
	 *
	 * @return void
	 */
	public function enqueueStyles() {
		$this->doAction( 'pdfdraft_editor_before_enqueue_styles' );
		wp_enqueue_style( 'pdfdraft-editor' );
		$this->doAction( 'pdfdraft_editor_before_enqueue_styles' );
	}

	/**
	 * Default dummy merge-tag values used by editor preview.
	 *
	 * @return array<string, string>
	 */
	private function getDefaultPreviewDummyData(): array {
		return array(
			'order_id'              => '1042',
			'order_number'          => '1042',
			'invoice_number'        => '1042',
			'order_date'            => 'March 15, 2025',
			'order_status'          => 'Processing',
			'transaction_id'        => 'txn_7f3a9b2c',
			'payment_method'        => 'Credit Card',
			'shipping_method'       => 'Flat Rate',
			'currency'              => 'USD',
			'currency_symbol'       => '$',
			'billing_first_name'    => 'John',
			'billing_last_name'     => 'Doe',
			'billing_company'       => 'Acme Inc.',
			'billing_email'         => 'john@example.com',
			'billing_phone'         => '(555) 123-4567',
			'billing_address_1'     => '123 Main St',
			'billing_address_2'     => 'Suite 100',
			'billing_city'          => 'New York',
			'billing_state'         => 'NY',
			'billing_postcode'      => '10001',
			'billing_country'       => 'US',
			'billing_address_full'  => '123 Main St, Suite 100, New York, NY 10001',
			'shipping_first_name'   => 'John',
			'shipping_last_name'    => 'Doe',
			'shipping_company'      => 'Acme Inc.',
			'shipping_address_1'    => '456 Oak Ave',
			'shipping_address_2'    => '',
			'shipping_city'         => 'New York',
			'shipping_state'        => 'NY',
			'shipping_postcode'     => '10002',
			'shipping_country'      => 'US',
			'shipping_address_full' => '456 Oak Ave, New York, NY 10002',
			'customer_id'           => '25',
			'customer_note'         => 'Please leave at the door.',
			'subtotal'              => '60.00',
			'shipping_total'        => '5.00',
			'total_tax'             => '5.00',
			'total_discount'        => '0.00',
			'grand_total'           => '65.40',
			'total_refunded'        => '0.00',
			'order_total_due'       => '65.40',
			'store_name'            => 'My Store',
			'store_address'         => '789 Market St, San Francisco, CA 94103',
			'store_phone'           => '(555) 987-6543',
			'store_email'           => 'hello@mystore.com',
			'store_logo'            => '',
		);
	}

	/**
	 * Default dummy product-table rows used by editor preview.
	 *
	 * @return array<int, array<string, string>>
	 */
	private function getDefaultPreviewDummyItems(): array {
		return array(
			array(
				'item.product_name'         => 'T-shirt - Color: Blue, Size: Large',
				'item.product_display_name' => 'T-shirt - Color: Blue, Size: Large',
				'item.sku'                  => 'SKU-1',
				'item.quantity'             => '1',
				'item.unit_price'           => '$20.00',
				'item.line_subtotal'        => '$20.00',
				'item.line_total'           => '$20.00',
				'item.product_meta'         => '',
				'item.product_image'        => '',
				'item.variation_data'       => '',
			),
			array(
				'item.product_name'         => 'T-shirt - Color: Black, Size: Medium',
				'item.product_display_name' => 'T-shirt - Color: Black, Size: Medium',
				'item.sku'                  => 'SKU-2',
				'item.quantity'             => '2',
				'item.unit_price'           => '$20.00',
				'item.line_subtotal'        => '$40.00',
				'item.line_total'           => '$40.00',
				'item.product_meta'         => '',
				'item.product_image'        => '',
				'item.variation_data'       => '',
			),
		);
	}
}
