<?php

namespace Dokan\TryAura\Admin;

use Dokan\TryAura\TryAura;

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

/**
 * Registers and enqueues the Featured Image AI Enhancer UI assets in the editor.
 */
class Enhancer {

	/**
	 * Class constructor.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	/**
	 * Enqueue the enhancer UI only on post edit screens.
	 *
	 * @since 1.0.0
	 *
	 * @param string $hook Current admin page hook suffix.
	 */
	public function enqueue( string $hook ): void {
		// Limit to classic/block editor post screens where the featured image modal is used.
		if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
			return;
		}

		global $post;
		$post_id   = $post ? $post->ID : 0;
		$post_type = $post ? $post->post_type : '';

		$settings    = get_option( 'tryaura_settings', array() );
		$api_key     = isset( $settings['google']['apiKey'] ) ? $settings['google']['apiKey'] : '';
		$image_model = isset( $settings['google']['imageModel'] ) ? $settings['google']['imageModel'] : '';
		$video_model = isset( $settings['google']['videoModel'] ) ? $settings['google']['videoModel'] : '';

		// Pass settings to the enhancer UI (admin-only, requires post editing capability).
		wp_localize_script(
			'tryaura-enhancer',
			'tryAura',
			array(
				'restUrl'         => esc_url_raw( rest_url() ),
				'nonce'           => wp_create_nonce( 'wp_rest' ),
				'apiKey'          => $api_key,
				'imageModel'      => $image_model,
				'videoModel'      => $video_model,
				'postId'          => $post_id,
				'postType'        => $post_type,
				'testMode'        => defined( 'TRYAURA_DEBUG' ) && TRYAURA_DEBUG,
				'testVideo'       => defined( 'TRYAURA_TEST_VIDEO' ) ? TRYAURA_TEST_VIDEO : '',
				'testImage'       => defined( 'TRYAURA_TEST_IMAGE' ) ? TRYAURA_TEST_IMAGE : '',
				'hasPro'          => (bool) TryAura::is_pro_exists(),
				'upgradeToProUrl' => 'https://storepulse.co/tryaura/pricing/',
			)
		);

		wp_enqueue_style( 'tryaura-components' );
		wp_enqueue_style( 'tryaura-enhancer' );
		wp_enqueue_script( 'tryaura-ai-models' );
		wp_enqueue_script( 'tryaura-components' );
		wp_enqueue_script( 'tryaura-enhancer' );

		do_action( 'tryaura_register_enhancer_assets' );
	}
}
