<?php
/**
 * Pendid Image v1.2 WordPress workspace.
 *
 * @package Pendid_AI_Studio
 */

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

/**
 * Replaces only the Create Image screen with a client of the canonical Studio image contract.
 */
class Pendid_AI_Studio_Image_Workspace {

	private $settings;
	private $api;
	private $page_hook = '';

	public function __construct( Pendid_AI_Studio_Settings $settings, Pendid_AI_Studio_Image_API $api ) {
		$this->settings = $settings;
		$this->api      = $api;
	}

	public function run() {
		add_action( 'admin_menu', array( $this, 'replace_create_page' ), 30 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ), 30 );
		add_action( 'admin_post_pendid_ai_studio_v12_generate', array( $this, 'handle_generate' ) );
		add_action( 'admin_post_pendid_ai_studio_v12_new_image', array( $this, 'handle_new_image' ) );
	}

	public function replace_create_page() {
		remove_submenu_page( 'pendid-ai-studio', 'pendid-ai-studio-create-image' );
		$this->page_hook = add_submenu_page(
			'pendid-ai-studio',
			__( 'Create Image', 'pendid-ai-studio' ),
			__( 'Create Image', 'pendid-ai-studio' ),
			'manage_options',
			'pendid-ai-studio-create-image',
			array( $this, 'render' )
		);
	}

	public function enqueue_assets( $hook_suffix ) {
		if ( ! $this->page_hook || $hook_suffix !== $this->page_hook ) {
			return;
		}
		wp_enqueue_style(
			'pendid-ai-studio-image-v12',
			PENDID_AI_STUDIO_URL . 'assets/image-workspace.css',
			array( 'pendid-ai-studio-admin' ),
			PENDID_AI_STUDIO_VERSION
		);
		wp_enqueue_script(
			'pendid-ai-studio-image-v12',
			PENDID_AI_STUDIO_URL . 'assets/image-workspace.js',
			array( 'pendid-ai-studio-admin' ),
			PENDID_AI_STUDIO_VERSION,
			true
		);
		wp_localize_script(
			'pendid-ai-studio-image-v12',
			'pendidImageWorkspace',
			array(
				'loadingTitle'    => __( 'Pendid is creating your image', 'pendid-ai-studio' ),
				'loadingMessages' => array(
					__( 'Preparing your request...', 'pendid-ai-studio' ),
					__( 'Building the composition...', 'pendid-ai-studio' ),
					__( 'Refining the visual details...', 'pendid-ai-studio' ),
					__( 'Getting the result ready for WordPress...', 'pendid-ai-studio' ),
				),
			)
		);
		wp_enqueue_script(
			'pendid-ai-studio-image-v12-loading',
			PENDID_AI_STUDIO_URL . 'assets/image-workspace-loading.js',
			array( 'pendid-ai-studio-image-v12' ),
			PENDID_AI_STUDIO_VERSION,
			true
		);
	}

	public function render() {
		$this->require_admin();
		$is_connected = $this->settings->is_connected();
		$config       = $is_connected ? $this->api->get_config( $this->settings->get_access_token() ) : array();
		$result       = $is_connected ? $this->get_result() : array();
		$has_result   = ! empty( $result['url'] );
		?>
		<div class="wrap pendid-ai-studio-wrap pendid-v12-wrap">
			<header class="pendid-ai-studio-page-header">
				<div class="pendid-ai-studio-brand">
					<span class="pendid-ai-studio-brand-mark"><img class="pendid-ai-studio-brand-logo" src="<?php echo esc_url( PENDID_AI_STUDIO_URL . 'assets/images/pendid-logo.png' ); ?>" alt="" width="48" height="48"></span>
					<div><p class="pendid-ai-studio-product-name"><?php echo esc_html__( 'Pendid AI Studio', 'pendid-ai-studio' ); ?></p><h1><?php echo esc_html__( 'Create Image', 'pendid-ai-studio' ); ?></h1><p><?php echo esc_html__( 'Create with the same Pendid Image engine while keeping the workflow inside WordPress.', 'pendid-ai-studio' ); ?></p></div>
				</div>
				<?php if ( $is_connected ) : ?><span class="pendid-ai-studio-connection-badge"><span aria-hidden="true"></span><?php echo esc_html__( 'Connected', 'pendid-ai-studio' ); ?></span><?php endif; ?>
			</header>

			<?php if ( ! $is_connected ) : ?>
				<section class="pendid-ai-studio-panel pendid-v12-message"><h2><?php echo esc_html__( 'Connect Pendid first', 'pendid-ai-studio' ); ?></h2><p><?php echo esc_html__( 'Open Pendid Settings and connect this WordPress site before creating images.', 'pendid-ai-studio' ); ?></p><a class="button button-primary" href="<?php echo esc_url( admin_url( 'admin.php?page=pendid-ai-studio-settings' ) ); ?>"><?php echo esc_html__( 'Open Settings', 'pendid-ai-studio' ); ?></a></section>
			<?php elseif ( empty( $config['ok'] ) || empty( $config['image'] ) || ! is_array( $config['image'] ) ) : ?>
				<section class="pendid-ai-studio-panel pendid-v12-message"><h2><?php echo esc_html__( 'Image settings could not be loaded', 'pendid-ai-studio' ); ?></h2><p><?php echo esc_html__( 'The editor is paused instead of using local fallback prices. Reload the page after Pendid Studio is available.', 'pendid-ai-studio' ); ?></p><a class="button button-secondary" href="<?php echo esc_url( admin_url( 'admin.php?page=pendid-ai-studio-create-image' ) ); ?>"><?php echo esc_html__( 'Reload', 'pendid-ai-studio' ); ?></a></section>
			<?php else : ?>
				<?php $this->render_workspace( $config, $result, $has_result ); ?>
			<?php endif; ?>
		</div>
		<?php
	}

	private function render_workspace( $config, $result, $has_result ) {
		$image                      = $config['image'];
		$account                    = isset( $config['account'] ) && is_array( $config['account'] ) ? $config['account'] : array();
		$output_sizes               = isset( $image['output_sizes'] ) && is_array( $image['output_sizes'] ) ? $image['output_sizes'] : array();
		$tones                      = isset( $image['tones'] ) && is_array( $image['tones'] ) ? $image['tones'] : array();
		$model_tiers                = isset( $image['model_tiers'] ) && is_array( $image['model_tiers'] ) ? $image['model_tiers'] : array( 'standard' );
		$access                     = isset( $image['access'] ) && is_array( $image['access'] ) ? $image['access'] : array();
		$pricing                    = isset( $image['pricing'] ) && is_array( $image['pricing'] ) ? $image['pricing'] : array();
		$surcharges                 = isset( $image['size_surcharges'] ) && is_array( $image['size_surcharges'] ) ? $image['size_surcharges'] : array();
		$max_inputs                 = max( 1, (int) ( isset( $access['max_input_images'] ) ? $access['max_input_images'] : 1 ) );
		$professional_sizes_allowed = ! empty( $access['professional_sizes_allowed'] );
		$pricing_bundle             = array( 'pricing' => $pricing, 'surcharges' => $surcharges );
		?>
		<div class="pendid-v12-accountbar">
			<span><strong><?php echo esc_html( isset( $account['ai_plan_title'] ) ? $account['ai_plan_title'] : __( 'Pendid AI', 'pendid-ai-studio' ) ); ?></strong></span>
			<span><?php echo esc_html__( 'Remaining:', 'pendid-ai-studio' ); ?> <strong><?php echo esc_html( number_format_i18n( (float) ( isset( $account['ai_remaining'] ) ? $account['ai_remaining'] : 0 ) ) ); ?></strong></span>
		</div>
		<div class="pendid-ai-studio-create-workspace<?php echo $has_result ? ' has-result' : ''; ?> pendid-v12-workspace">
			<section class="pendid-ai-studio-panel pendid-ai-studio-preview-panel">
				<div class="pendid-ai-studio-workspace-heading"><div><p class="pendid-ai-studio-eyebrow"><?php echo esc_html__( 'Result', 'pendid-ai-studio' ); ?></p><h2><?php echo esc_html__( 'Image preview', 'pendid-ai-studio' ); ?></h2></div></div>
				<div class="pendid-ai-studio-preview-stage">
					<?php if ( $has_result ) : ?>
						<img src="<?php echo esc_url( ! empty( $result['attachment_url'] ) ? $result['attachment_url'] : $result['url'] ); ?>" alt="<?php echo esc_attr( isset( $result['prompt'] ) ? $result['prompt'] : '' ); ?>">
					<?php else : ?>
						<div class="pendid-ai-studio-preview-empty"><span class="pendid-ai-studio-preview-symbol"><span class="dashicons dashicons-format-image" aria-hidden="true"></span></span><h3><?php echo esc_html__( 'Your generated image will appear here', 'pendid-ai-studio' ); ?></h3><p><?php echo esc_html__( 'Choose a model, size, mood and optional references. Pendid handles the generation and WordPress saves the result.', 'pendid-ai-studio' ); ?></p></div>
					<?php endif; ?>
				</div>
				<?php if ( $has_result ) : ?>
					<div class="pendid-ai-studio-preview-actions"><form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"><input type="hidden" name="action" value="pendid_ai_studio_v12_new_image"><?php wp_nonce_field( 'pendid_ai_studio_v12_new_image', 'pendid_v12_nonce' ); ?><button class="button button-primary" type="submit"><?php echo esc_html__( 'Create new image', 'pendid-ai-studio' ); ?></button></form><?php if ( ! empty( $result['attachment_url'] ) ) : ?><a class="button button-secondary" target="_blank" rel="noopener noreferrer" href="<?php echo esc_url( $result['attachment_url'] ); ?>"><?php echo esc_html__( 'Open image', 'pendid-ai-studio' ); ?></a><?php endif; ?></div>
				<?php endif; ?>
				<div class="pendid-ai-studio-storage-notes"><div class="pendid-ai-studio-storage-note"><span class="dashicons dashicons-admin-media" aria-hidden="true"></span><p><strong><?php echo esc_html__( 'Automatic WordPress saving', 'pendid-ai-studio' ); ?></strong><small><?php echo esc_html__( 'Every successful result is saved to the Media Library.', 'pendid-ai-studio' ); ?></small></p></div><div class="pendid-ai-studio-storage-note"><span class="dashicons dashicons-backup" aria-hidden="true"></span><p><strong><?php echo esc_html__( 'Pendid account copy', 'pendid-ai-studio' ); ?></strong><small><?php echo esc_html__( 'The generated asset is also registered in Pendid Studio.', 'pendid-ai-studio' ); ?></small></p></div></div>
			</section>

			<aside class="pendid-ai-studio-panel pendid-ai-studio-controls-panel pendid-v12-controls">
				<?php if ( $has_result ) : ?>
					<?php $this->render_edit_form( $result, $model_tiers, $pricing_bundle ); ?>
				<?php else : ?>
					<?php $this->render_generate_form( $output_sizes, $tones, $model_tiers, $max_inputs, $professional_sizes_allowed, $access, $pricing_bundle ); ?>
				<?php endif; ?>
			</aside>
		</div>
		<?php
	}

	private function render_generate_form( $sizes, $tones, $tiers, $max_inputs, $professional_sizes_allowed, $access, $pricing_bundle ) {
		$purposes = $this->purposes();
		?>
		<div class="pendid-ai-studio-workspace-heading"><div><p class="pendid-ai-studio-eyebrow"><?php echo esc_html__( 'Pendid Image', 'pendid-ai-studio' ); ?></p><h2><?php echo esc_html__( 'Generation settings', 'pendid-ai-studio' ); ?></h2></div></div>
		<form class="pendid-ai-studio-generation-form pendid-v12-form" method="post" enctype="multipart/form-data" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" data-pendid-v12-form data-pendid-price-config="<?php echo esc_attr( wp_json_encode( $pricing_bundle ) ); ?>">
			<input type="hidden" name="action" value="pendid_ai_studio_v12_generate"><input type="hidden" name="pendid_mode" value="generate"><?php wp_nonce_field( 'pendid_ai_studio_v12_generate', 'pendid_v12_nonce' ); ?>

			<div class="pendid-v12-compact-row"><div class="pendid-ai-studio-field"><label><?php echo esc_html__( 'Model', 'pendid-ai-studio' ); ?></label><div class="pendid-v12-segmented"><?php foreach ( $tiers as $tier ) : $tier = sanitize_key( (string) $tier ); ?><label><input type="radio" name="pendid_model_tier" value="<?php echo esc_attr( $tier ); ?>" <?php checked( 'standard', $tier ); ?>><span><?php echo esc_html( 'advanced' === $tier ? __( 'Advanced', 'pendid-ai-studio' ) : __( 'Standard', 'pendid-ai-studio' ) ); ?></span></label><?php endforeach; ?></div></div><div class="pendid-ai-studio-field"><label for="pendid-v12-format"><?php echo esc_html__( 'File format', 'pendid-ai-studio' ); ?></label><select id="pendid-v12-format" name="pendid_output_format"><option value="png">PNG</option><option value="jpeg">JPEG</option><option value="webp">WebP</option></select></div></div>

			<fieldset class="pendid-ai-studio-purpose-fieldset"><legend><?php echo esc_html__( 'Website image purpose', 'pendid-ai-studio' ); ?></legend><div class="pendid-ai-studio-purpose-grid"><?php foreach ( $purposes as $id => $item ) : ?><label class="pendid-ai-studio-purpose-option"><input type="radio" name="pendid_image_purpose" value="<?php echo esc_attr( $id ); ?>" <?php checked( 'featured-image', $id ); ?>><span><strong><?php echo esc_html( $item['title'] ); ?></strong><small><?php echo esc_html( $item['helper'] ); ?></small></span></label><?php endforeach; ?></div></fieldset>

			<fieldset class="pendid-ai-studio-ratio-fieldset"><legend><?php echo esc_html__( 'Image size', 'pendid-ai-studio' ); ?></legend><div class="pendid-v12-size-grid"><?php foreach ( $sizes as $size ) : if ( empty( $size['primary'] ) ) { continue; } ?><label class="pendid-v12-size-option"><input type="radio" name="pendid_output_size" value="<?php echo esc_attr( $size['modelvalue'] ); ?>" data-size-id="<?php echo esc_attr( $size['id'] ); ?>" <?php checked( '1:1', $size['modelvalue'] ); ?>><span><strong><?php echo esc_html( $size['title'] ); ?></strong><small><?php echo esc_html( $size['ratio'] ); ?></small></span></label><?php endforeach; ?></div></fieldset>

			<details class="pendid-v12-details"><summary><?php echo esc_html__( 'More sizes and options', 'pendid-ai-studio' ); ?></summary><div class="pendid-v12-details-body"><div class="pendid-ai-studio-field"><label for="pendid-v12-professional-size"><?php echo esc_html__( 'Professional size', 'pendid-ai-studio' ); ?></label><select id="pendid-v12-professional-size" data-pendid-professional-size <?php disabled( ! $professional_sizes_allowed ); ?>><option value=""><?php echo esc_html__( 'Use selected standard size', 'pendid-ai-studio' ); ?></option><?php foreach ( $sizes as $size ) : if ( ! empty( $size['primary'] ) ) { continue; } ?><option value="<?php echo esc_attr( $size['modelvalue'] ); ?>" data-size-id="<?php echo esc_attr( $size['id'] ); ?>"><?php echo esc_html( $size['title'] . ' · ' . $size['ratio'] ); ?></option><?php endforeach; ?></select><?php if ( ! $professional_sizes_allowed ) : ?><small><?php
			if ( ! empty( $access['required_plan_title'] ) ) {
				/* translators: %s: Minimum Pendid service plan name returned by the server for professional image sizes. */
				echo esc_html( sprintf( __( 'Professional sizes require %s or higher.', 'pendid-ai-studio' ), $access['required_plan_title'] ) );
			} else {
				echo esc_html__( 'Professional sizes are not available for your current Pendid plan.', 'pendid-ai-studio' );
			}
		?></small><?php endif; ?></div><label class="pendid-v12-switch"><input type="checkbox" name="pendid_brand_kit" value="1"><span><strong><?php echo esc_html__( 'Use my Pendid Brand Kit', 'pendid-ai-studio' ); ?></strong><small><?php echo esc_html__( 'Apply the Brand Kit saved in your Pendid account.', 'pendid-ai-studio' ); ?></small></span></label></div></details>

			<div class="pendid-ai-studio-field"><label for="pendid-v12-tone"><?php echo esc_html__( 'Image mood', 'pendid-ai-studio' ); ?></label><select id="pendid-v12-tone" name="pendid_image_tone"><?php foreach ( $tones as $tone ) : ?><option value="<?php echo esc_attr( $tone['id'] ); ?>" <?php selected( 'professional', $tone['id'] ); ?>><?php echo esc_html( $tone['title'] ); ?></option><?php endforeach; ?></select></div>
			<div class="pendid-ai-studio-field"><label for="pendid-v12-prompt"><?php echo esc_html__( 'Describe the image', 'pendid-ai-studio' ); ?></label><textarea id="pendid-v12-prompt" name="pendid_prompt" rows="6" minlength="8" maxlength="1200" required placeholder="<?php echo esc_attr__( 'Describe the subject, environment, composition, lighting, colors and any text you want.', 'pendid-ai-studio' ); ?>"></textarea></div>
			<label class="pendid-ai-studio-reference-card"><input type="file" name="pendid_input_images[]" accept="image/jpeg,image/png,image/webp" multiple data-pendid-v12-inputs data-max-inputs="<?php echo esc_attr( $max_inputs ); ?>"><span class="pendid-ai-studio-reference-preview"><span class="dashicons dashicons-images-alt2" aria-hidden="true"></span></span><span class="pendid-ai-studio-reference-copy"><strong><?php echo esc_html__( 'Reference images', 'pendid-ai-studio' ); ?></strong><small><?php
				/* translators: %d: Maximum number of reference images allowed by the current Pendid plan. */
				echo esc_html( sprintf( __( 'Optional JPG, PNG or WebP. Up to %d images for your current plan.', 'pendid-ai-studio' ), $max_inputs ) );
			?></small></span><span class="button button-secondary"><?php echo esc_html__( 'Choose images', 'pendid-ai-studio' ); ?></span></label>
			<div class="pendid-v12-price-row"><span><?php echo esc_html__( 'Current Pendid price', 'pendid-ai-studio' ); ?></span><strong data-pendid-v12-price>—</strong></div>
			<button type="submit" class="button button-primary button-hero pendid-ai-studio-generate-button"><span class="dashicons dashicons-format-image" aria-hidden="true"></span> <span><?php echo esc_html__( 'Generate and save', 'pendid-ai-studio' ); ?></span></button>
			<p class="pendid-v12-help"><?php echo esc_html__( 'The displayed price comes from Pendid Admin. The server remains authoritative at generation time.', 'pendid-ai-studio' ); ?></p>
		</form>
		<?php
	}

	private function render_edit_form( $result, $tiers, $pricing_bundle ) {
		?>
		<div class="pendid-ai-studio-workspace-heading"><div><p class="pendid-ai-studio-eyebrow"><?php echo esc_html__( 'Next step', 'pendid-ai-studio' ); ?></p><h2><?php echo esc_html__( 'Edit this image', 'pendid-ai-studio' ); ?></h2><p><?php echo esc_html__( 'Describe the change you want and save it as a new image.', 'pendid-ai-studio' ); ?></p></div></div>
		<form class="pendid-ai-studio-generation-form pendid-v12-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" data-pendid-v12-form data-pendid-price-config="<?php echo esc_attr( wp_json_encode( $pricing_bundle ) ); ?>">
			<input type="hidden" name="action" value="pendid_ai_studio_v12_generate"><input type="hidden" name="pendid_mode" value="edit"><input type="hidden" name="pendid_source_image_url" value="<?php echo esc_attr( $result['url'] ); ?>"><input type="hidden" name="pendid_source_r2_key" value="<?php echo esc_attr( isset( $result['key'] ) ? $result['key'] : '' ); ?>"><?php wp_nonce_field( 'pendid_ai_studio_v12_generate', 'pendid_v12_nonce' ); ?>
			<div class="pendid-v12-compact-row"><div class="pendid-ai-studio-field"><label><?php echo esc_html__( 'Model', 'pendid-ai-studio' ); ?></label><div class="pendid-v12-segmented"><?php foreach ( $tiers as $tier ) : $tier = sanitize_key( (string) $tier ); ?><label><input type="radio" name="pendid_model_tier" value="<?php echo esc_attr( $tier ); ?>" <?php checked( isset( $result['model_tier'] ) ? $result['model_tier'] : 'standard', $tier ); ?>><span><?php echo esc_html( 'advanced' === $tier ? __( 'Advanced', 'pendid-ai-studio' ) : __( 'Standard', 'pendid-ai-studio' ) ); ?></span></label><?php endforeach; ?></div></div><div class="pendid-ai-studio-field"><label for="pendid-v12-edit-format"><?php echo esc_html__( 'File format', 'pendid-ai-studio' ); ?></label><select id="pendid-v12-edit-format" name="pendid_output_format"><option value="png">PNG</option><option value="jpeg">JPEG</option><option value="webp">WebP</option></select></div></div>
			<div class="pendid-ai-studio-field"><label for="pendid-v12-edit-prompt"><?php echo esc_html__( 'What should change?', 'pendid-ai-studio' ); ?></label><textarea id="pendid-v12-edit-prompt" name="pendid_prompt" rows="7" minlength="8" maxlength="1200" required placeholder="<?php echo esc_attr__( 'For example: Make the background warmer and keep the subject unchanged.', 'pendid-ai-studio' ); ?>"></textarea></div>
			<div class="pendid-v12-price-row"><span><?php echo esc_html__( 'Current Pendid price', 'pendid-ai-studio' ); ?></span><strong data-pendid-v12-price>—</strong></div>
			<button type="submit" class="button button-primary button-hero pendid-ai-studio-generate-button"><span class="dashicons dashicons-edit" aria-hidden="true"></span> <?php echo esc_html__( 'Edit and save new version', 'pendid-ai-studio' ); ?></button>
		</form>
		<?php
	}

	public function handle_generate() {
		$this->require_admin();
		check_admin_referer( 'pendid_ai_studio_v12_generate', 'pendid_v12_nonce' );
		if ( ! $this->settings->is_connected() ) {
			$this->redirect_error( 'connection_expired' );
		}

		$config = $this->api->get_config( $this->settings->get_access_token() );
		if ( empty( $config['ok'] ) || empty( $config['image'] ) || ! is_array( $config['image'] ) ) {
			$this->redirect_error( 'service_unavailable' );
		}

		$mode          = sanitize_key( $this->post_scalar( 'pendid_mode', 'generate' ) );
		$mode          = in_array( $mode, array( 'generate', 'edit' ), true ) ? $mode : 'generate';
		$description   = trim( sanitize_textarea_field( $this->post_scalar( 'pendid_prompt' ) ) );
		$model_tier    = sanitize_key( $this->post_scalar( 'pendid_model_tier', 'standard' ) );
		$output_size   = sanitize_text_field( $this->post_scalar( 'pendid_output_size', '1:1' ) );
		$output_format = sanitize_key( $this->post_scalar( 'pendid_output_format', 'png' ) );
		$purpose       = sanitize_key( $this->post_scalar( 'pendid_image_purpose', 'featured-image' ) );
		$tone          = sanitize_key( $this->post_scalar( 'pendid_image_tone', 'professional' ) );
		$brand_kit     = 'generate' === $mode && '1' === $this->post_scalar( 'pendid_brand_kit' );
		$source_url    = esc_url_raw( $this->post_scalar( 'pendid_source_image_url' ) );
		$source_key    = sanitize_text_field( $this->post_scalar( 'pendid_source_r2_key' ) );

		if ( strlen( $description ) < 8 ) {
			$this->redirect_error( 'image_prompt_required' );
		}
		if ( ! in_array( $output_format, array( 'png', 'jpeg', 'webp' ), true ) ) {
			$output_format = 'png';
		}

		$image_cfg = $config['image'];
		$tiers     = isset( $image_cfg['model_tiers'] ) && is_array( $image_cfg['model_tiers'] ) ? array_map( 'sanitize_key', $image_cfg['model_tiers'] ) : array( 'standard' );
		if ( ! in_array( $model_tier, $tiers, true ) ) {
			$model_tier = 'standard';
		}

		$size_map = array();
		foreach ( isset( $image_cfg['output_sizes'] ) && is_array( $image_cfg['output_sizes'] ) ? $image_cfg['output_sizes'] : array() as $size ) {
			if ( isset( $size['modelvalue'] ) ) {
				$size_map[ (string) $size['modelvalue'] ] = $size;
			}
		}
		if ( ! isset( $size_map[ $output_size ] ) ) {
			$output_size = '1:1';
		}
		if ( isset( $size_map[ $output_size ] ) && empty( $size_map[ $output_size ]['primary'] ) && empty( $image_cfg['access']['professional_sizes_allowed'] ) ) {
			$this->redirect_error( 'image_plan_required' );
		}

		$tone_ids = array();
		foreach ( isset( $image_cfg['tones'] ) && is_array( $image_cfg['tones'] ) ? $image_cfg['tones'] : array() as $tone_row ) {
			if ( isset( $tone_row['id'] ) ) {
				$tone_ids[] = sanitize_key( $tone_row['id'] );
			}
		}
		if ( ! in_array( $tone, $tone_ids, true ) ) {
			$tone = 'professional';
		}

		$max_inputs  = max( 1, (int) ( isset( $image_cfg['access']['max_input_images'] ) ? $image_cfg['access']['max_input_images'] : 1 ) );
		$input_files = 'generate' === $mode ? $this->collect_multi_uploads( 'pendid_input_images', $max_inputs ) : array();
		if ( is_wp_error( $input_files ) ) {
			$this->redirect_error( 'image_reference_invalid' );
		}
		if ( 'edit' === $mode && '' === $source_url ) {
			$this->redirect_error( 'image_edit_source_missing' );
		}

		$request_config = $this->request_config( $purpose, $output_size );
		$response       = $this->api->generate(
			$this->settings->get_access_token(),
			array(
				'mode' => $mode, 'description' => $description, 'model_tier' => $model_tier,
				'output_size' => $output_size, 'output_format' => $output_format,
				'image_type' => $request_config['image_type'], 'format' => $request_config['format'],
				'tone' => $tone, 'brand_kit' => $brand_kit, 'input_files' => $input_files,
				'source_image_url' => $source_url, 'source_r2_key' => $source_key,
				'edit_aspect_ratio' => 'edit' === $mode ? ( isset( $this->get_result()['aspect_ratio'] ) ? $this->get_result()['aspect_ratio'] : 'auto' ) : 'auto',
			)
		);

		if ( empty( $response['ok'] ) || empty( $response['image'] ) || ! is_array( $response['image'] ) ) {
			$reason = isset( $response['reason'] ) ? sanitize_key( (string) $response['reason'] ) : 'generation_failed';
			$this->redirect_error( $this->map_error( $reason ) );
		}

		$image_result               = $this->sanitize_result( $response['image'] );
		$image_result['prompt']     = $description;
		$image_result['purpose']    = $purpose;
		$image_result['tone']       = $tone;
		$image_result['model_tier'] = $model_tier;
		$attachment = $this->save_to_media( $image_result, $description );
		if ( is_wp_error( $attachment ) ) {
			set_transient( $this->result_key(), $image_result, 12 * HOUR_IN_SECONDS );
			$this->redirect_error( 'image_media_save_failed' );
		}
		$image_result = array_merge( $image_result, $attachment );
		set_transient( $this->result_key(), $image_result, 12 * HOUR_IN_SECONDS );
		wp_safe_redirect( add_query_arg( array( 'page' => 'pendid-ai-studio-create-image', 'pendid_message' => 'image_generated' ), admin_url( 'admin.php' ) ) );
		exit;
	}

	public function handle_new_image() {
		$this->require_admin();
		check_admin_referer( 'pendid_ai_studio_v12_new_image', 'pendid_v12_nonce' );
		delete_transient( $this->result_key() );
		wp_safe_redirect( admin_url( 'admin.php?page=pendid-ai-studio-create-image' ) );
		exit;
	}

	private function collect_multi_uploads( $field, $max ) {
		// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		if ( empty( $_FILES[ $field ] ) || ! is_array( $_FILES[ $field ] ) ) {
			return array();
		}
		$raw = $_FILES[ $field ];
		// phpcs:enable WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$names = isset( $raw['name'] ) && is_array( $raw['name'] ) ? $raw['name'] : array();
		if ( count( array_filter( $names ) ) > $max ) {
			return new WP_Error( 'pendid_input_limit', __( 'Too many input images.', 'pendid-ai-studio' ) );
		}
		$result = array();
		foreach ( $names as $i => $name ) {
			$file = array(
				'name' => $name,
				'tmp_name' => isset( $raw['tmp_name'][ $i ] ) ? $raw['tmp_name'][ $i ] : '',
				'size' => isset( $raw['size'][ $i ] ) ? $raw['size'][ $i ] : 0,
				'error' => isset( $raw['error'][ $i ] ) ? $raw['error'][ $i ] : UPLOAD_ERR_NO_FILE,
			);
			$validated = $this->validate_upload( $file );
			if ( is_wp_error( $validated ) ) {
				return $validated;
			}
			if ( ! empty( $validated ) ) {
				$result[] = $validated;
			}
		}
		return $result;
	}

	private function validate_upload( $file ) {
		if ( empty( $file ) || UPLOAD_ERR_NO_FILE === (int) ( isset( $file['error'] ) ? $file['error'] : UPLOAD_ERR_NO_FILE ) ) {
			return array();
		}
		if ( UPLOAD_ERR_OK !== (int) $file['error'] ) {
			return new WP_Error( 'pendid_upload_failed' );
		}
		$tmp  = isset( $file['tmp_name'] ) ? (string) $file['tmp_name'] : '';
		$size = isset( $file['size'] ) ? (int) $file['size'] : 0;
		if ( ! $tmp || ! is_uploaded_file( $tmp ) || $size < 1 || $size > min( 8 * MB_IN_BYTES, max( 1, (int) wp_max_upload_size() ) ) ) {
			return new WP_Error( 'pendid_upload_invalid' );
		}
		$mime = function_exists( 'wp_get_image_mime' ) ? wp_get_image_mime( $tmp ) : '';
		if ( ! in_array( $mime, array( 'image/jpeg', 'image/png', 'image/webp' ), true ) ) {
			return new WP_Error( 'pendid_upload_type' );
		}
		return array( 'path' => $tmp, 'name' => sanitize_file_name( isset( $file['name'] ) ? $file['name'] : 'image' ), 'type' => $mime, 'size' => $size );
	}

	private function save_to_media( $image, $prompt ) {
		$url   = isset( $image['url'] ) ? esc_url_raw( $image['url'] ) : '';
		$parts = wp_parse_url( $url );
		if ( ! wp_http_validate_url( $url ) || empty( $parts['host'] ) || 'media.pendid.com' !== strtolower( $parts['host'] ) ) {
			return new WP_Error( 'pendid_invalid_media_url' );
		}
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/media.php';
		require_once ABSPATH . 'wp-admin/includes/image.php';
		$tmp = download_url( $url, 120 );
		if ( is_wp_error( $tmp ) ) {
			return $tmp;
		}
		$ext  = 'png';
		$type = isset( $image['content_type'] ) ? strtolower( $image['content_type'] ) : '';
		if ( false !== strpos( $type, 'jpeg' ) ) {
			$ext = 'jpg';
		} elseif ( false !== strpos( $type, 'webp' ) ) {
			$ext = 'webp';
		}
		$slug = sanitize_file_name( wp_html_excerpt( sanitize_text_field( $prompt ), 60, '' ) );
		if ( '' === $slug ) {
			$slug = 'pendid-image';
		}
		$file_array = array( 'name' => $slug . '-' . gmdate( 'Ymd-His' ) . '.' . $ext, 'tmp_name' => $tmp );
		$id = media_handle_sideload( $file_array, 0, null, array( 'post_title' => wp_html_excerpt( sanitize_text_field( $prompt ), 120, '' ) ) );
		if ( is_wp_error( $id ) ) {
			if ( file_exists( $tmp ) ) {
				wp_delete_file( $tmp );
			}
			return $id;
		}
		update_post_meta( $id, '_wp_attachment_image_alt', wp_html_excerpt( sanitize_text_field( $prompt ), 250, '' ) );
		return array( 'attachment_id' => absint( $id ), 'attachment_url' => esc_url_raw( (string) wp_get_attachment_url( $id ) ), 'edit_link' => esc_url_raw( (string) get_edit_post_link( $id, '' ) ) );
	}

	private function sanitize_result( $image ) {
		$keys = array( 'url', 'key', 'filename', 'content_type', 'aspect_ratio', 'mode', 'source_key', 'thumb_url', 'provider', 'model', 'quality', 'output_format', 'created_at' );
		$out  = array();
		foreach ( $keys as $key ) {
			if ( isset( $image[ $key ] ) && is_scalar( $image[ $key ] ) ) {
				$out[ $key ] = 'url' === $key || 'thumb_url' === $key ? esc_url_raw( (string) $image[ $key ] ) : sanitize_text_field( (string) $image[ $key ] );
			}
		}
		return $out;
	}

	private function request_config( $purpose, $output_size ) {
		$ratio  = in_array( $output_size, array( '1:1', '3:2', '2:3' ), true ) ? $output_size : ( false !== strpos( $output_size, 'x' ) ? ( ( (float) strtok( $output_size, 'x' ) ) >= 1.2 * (float) substr( $output_size, strpos( $output_size, 'x' ) + 1 ) ? '3:2' : '1:1' ) : '1:1' );
		$config = array(
			'featured-image' => array( 'image_type' => 'intro-cover', '1:1' => 'intro-square', '3:2' => 'article-cover', '2:3' => 'instagram-story' ),
			'article-image' => array( 'image_type' => 'intro-cover', '1:1' => 'intro-square', '3:2' => 'article-cover', '2:3' => 'instagram-story' ),
			'hero-banner' => array( 'image_type' => 'website-banner', '1:1' => 'instagram-post', '3:2' => 'site-hero', '2:3' => 'instagram-story' ),
			'landing-page' => array( 'image_type' => 'website-banner', '1:1' => 'instagram-post', '3:2' => 'landing-banner', '2:3' => 'instagram-story' ),
			'product-service' => array( 'image_type' => 'product-image', '1:1' => 'product-square', '3:2' => 'product-wide', '2:3' => 'product-story' ),
		);
		$item = isset( $config[ $purpose ] ) ? $config[ $purpose ] : $config['featured-image'];
		return array( 'image_type' => $item['image_type'], 'format' => isset( $item[ $ratio ] ) ? $item[ $ratio ] : $item['1:1'] );
	}

	private function purposes() {
		return array(
			'featured-image' => array( 'title' => __( 'Featured image', 'pendid-ai-studio' ), 'helper' => __( 'Posts and editorial covers', 'pendid-ai-studio' ) ),
			'article-image' => array( 'title' => __( 'Article image', 'pendid-ai-studio' ), 'helper' => __( 'Visuals inside blog content', 'pendid-ai-studio' ) ),
			'hero-banner' => array( 'title' => __( 'Hero or banner', 'pendid-ai-studio' ), 'helper' => __( 'Headers, sliders and campaigns', 'pendid-ai-studio' ) ),
			'landing-page' => array( 'title' => __( 'Landing page', 'pendid-ai-studio' ), 'helper' => __( 'Focused page and service visuals', 'pendid-ai-studio' ) ),
			'product-service' => array( 'title' => __( 'Product or service', 'pendid-ai-studio' ), 'helper' => __( 'Commercial showcase images', 'pendid-ai-studio' ) ),
		);
	}

	private function map_error( $reason ) {
		if ( in_array( $reason, array( 'ai_usage_exhausted', 'monthly_ai_limit_reached' ), true ) ) {
			return 'image_allowance_exhausted';
		}
		if ( in_array( $reason, array( 'paid_plan_required_for_integration', 'ai_plan_expired', 'ai_plan_required', 'ai_not_available_for_plan', 'image_pro_features_required' ), true ) ) {
			return 'image_plan_required';
		}
		if ( in_array( $reason, array( 'invalid_token', 'missing_authorization', 'invalid_authorization' ), true ) ) {
			return 'connection_expired';
		}
		if ( in_array( $reason, array( 'invalid_input_image', 'input_image_too_large', 'input_image_limit_exceeded' ), true ) ) {
			return 'image_reference_invalid';
		}
		if ( 'description_required' === $reason || 'prompt_required' === $reason ) {
			return 'image_prompt_required';
		}
		if ( 'edit_image_required' === $reason ) {
			return 'image_edit_source_missing';
		}
		if ( 'service_unavailable' === $reason ) {
			return 'service_unavailable';
		}
		if ( 'ai_tool_pricing_unavailable' === $reason ) {
			return 'generation_unavailable';
		}
		return 'image_generation_failed';
	}

	private function redirect_error( $error ) {
		wp_safe_redirect( add_query_arg( array( 'page' => 'pendid-ai-studio-create-image', 'pendid_error' => sanitize_key( $error ) ), admin_url( 'admin.php' ) ) );
		exit;
	}

	private function result_key() {
		return 'pendid_ai_studio_v12_result_' . get_current_user_id();
	}

	private function get_result() {
		$value = get_transient( $this->result_key() );
		return is_array( $value ) ? $value : array();
	}

	private function post_scalar( $key, $default = '' ) {
		$value = filter_input( INPUT_POST, $key, FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR );
		return false === $value || null === $value || ! is_scalar( $value ) ? $default : (string) $value;
	}

	private function require_admin() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'pendid-ai-studio' ) );
		}
	}
}
