<?php
/**
 * Active design management for WooCommerce invoice templates.
 *
 * @package PDFDraft_WooCommerce
 */

namespace PDFDraft\Woocommerce\Core;

use PDFDraft\Traits\Hooks;

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

/**
 * Manages the active WooCommerce invoice design slug via REST API and options.
 */
class ActiveDesign {

	use Hooks;

	/**
	 * Option key for the active design slug.
	 *
	 * @var string
	 */
	private const OPTION_KEY = 'pdfdraft_pdf_invoices_for_woocommerce_active_design_slug';

	/**
	 * Register WordPress hooks for active design management.
	 *
	 * @return void
	 */
	public function initHooks() {
		$this->addFilter( 'pdfdraft_is_woocommerce_invoices_addon_active', array( $this, 'filterIsAddonActive' ) );
		// Must match `pdfdraft_editor_localized_data` in PDFDraft\Editor::enqueueScripts().
		$this->addFilter( 'pdfdraft_editor_localized_data', array( $this, 'addLocalizedData' ) );
		$this->addAction( 'rest_api_init', array( $this, 'registerRestRoute' ) );
		$this->addAction( 'pdfdraft_after_delete_pdf_design', array( $this, 'onAfterDeletePdfDesign' ) );
	}

	/**
	 * Signal to PDFDraft core that this add-on is active (REST guard for invoice designs).
	 *
	 * @param bool $active Previous value.
	 * @return bool
	 */
	public function filterIsAddonActive( bool $active ): bool {
		return true;
	}

	/**
	 * Add WooCommerce plugin data to the PDFDraft editor localization array.
	 *
	 * @param array $data Existing localized data.
	 * @return array Modified localized data.
	 */
	public function addLocalizedData( array $data ) {
		if ( ! isset( $data['pdfdraftPluginsActive'] ) || ! is_array( $data['pdfdraftPluginsActive'] ) ) {
			$data['pdfdraftPluginsActive'] = array();
		}
		if ( ! isset( $data['createFromScratchByFor'] ) || ! is_array( $data['createFromScratchByFor'] ) ) {
			$data['createFromScratchByFor'] = array();
		}
		$data['pdfdraftPluginsActive']['pdfdraft-pdf-invoices-for-woocommerce'] = true;
		$data['createFromScratchByFor']['woo']                 = 'pdfdraft-pdf-invoices-for-woocommerce';
		if ( 'woo' === ( $data['for'] ?? '' ) ) {
			$data['woocommerceActiveDesignSlug'] = get_option( self::OPTION_KEY, '' );
		}
		return $data;
	}

	/**
	 * Register REST API routes for getting and setting the active design.
	 *
	 * @return void
	 */
	public function registerRestRoute() {
		register_rest_route(
			'pdfdraft/v1',
			'/woocommerce/active-design',
			array(
				'methods'             => 'GET',
				'permission_callback' => fn() => current_user_can( 'edit_posts' ),
				'callback'            => function () {
					return rest_ensure_response( array( 'slug' => get_option( self::OPTION_KEY, '' ) ) );
				},
			)
		);
		register_rest_route(
			'pdfdraft/v1',
			'/woocommerce/active-design',
			array(
				'methods'             => 'POST',
				'permission_callback' => fn() => current_user_can( 'edit_posts' ),
				'callback'            => array( $this, 'setActiveDesign' ),
				'args'                => array(
					'slug' => array(
						'required'          => true,
						'type'              => 'string',
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
			)
		);
	}

	/**
	 * Handle the POST request to set the active design slug.
	 *
	 * @param \WP_REST_Request $request REST request object.
	 * @return \WP_REST_Response
	 */
	public function setActiveDesign( \WP_REST_Request $request ) {
		$slug = $request->get_param( 'slug' );
		update_option( self::OPTION_KEY, $slug );
		return rest_ensure_response( array( 'slug' => $slug ) );
	}

	/**
	 * Clear the active design option when a WooCommerce design is deleted.
	 *
	 * @param \WP_REST_Request $request REST request from the delete action.
	 * @return void
	 */
	public function onAfterDeletePdfDesign( $request ) {
		if ( 'woo' !== ( $request->get_param( 'for' ) ?? '' ) ) {
			return;
		}
		delete_option( self::OPTION_KEY );
	}
}
