<?php
/**
 * Final alt text formatting and attachment field updates.
 *
 * @package AIAltTextGenerator
 * @since 2.0.1
 */

namespace AIAltTextGenerator;

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

/**
 * Applies prefix/suffix, length limits, and optional attachment field copies.
 *
 * @since 2.0.1
 */
class AltTextOutput {

	/**
	 * Build the final alt text saved to the media library.
	 */
	public static function finalize( string $alt_text, ?array $settings = null ): string {
		$settings = $settings ?? Settings::get();
		$alt_text = trim( $alt_text );

		if ( $alt_text === '' ) {
			return '';
		}

		$prefix = trim( (string) ( $settings['alt_prefix'] ?? '' ) );
		$suffix = trim( (string) ( $settings['alt_suffix'] ?? '' ) );
		$parts  = array_values( array_filter( [ $prefix, $alt_text, $suffix ], static fn( string $part ): bool => $part !== '' ) );
		$final  = implode( ' ', $parts );

		return self::trimToMaxChars( $final, (int) ( $settings['max_chars'] ?? 125 ) );
	}

	/**
	 * Reserve room in the AI prompt for configured prefix/suffix strings.
	 */
	public static function effectiveMaxCharsForGeneration( ?array $settings = null ): int {
		$settings = $settings ?? Settings::get();
		$max      = max( 50, (int) ( $settings['max_chars'] ?? 125 ) );
		$prefix   = trim( (string) ( $settings['alt_prefix'] ?? '' ) );
		$suffix   = trim( (string) ( $settings['alt_suffix'] ?? '' ) );
		$reserve  = Text::length( $prefix ) + Text::length( $suffix );

		if ( $prefix !== '' && $suffix !== '' ) {
			$reserve += 2;
		} elseif ( $prefix !== '' || $suffix !== '' ) {
			++$reserve;
		}

		return max( 20, $max - $reserve );
	}

	/**
	 * Copy finalized alt text into attachment title, caption, or description.
	 */
	public static function applyAttachmentFields( int $attachment_id, string $alt_text, ?array $settings = null ): void {
		$settings = $settings ?? Settings::get();
		$alt_text = trim( $alt_text );

		if ( $alt_text === '' ) {
			return;
		}

		$update = [ 'ID' => $attachment_id ];

		if ( ! empty( $settings['copy_to_title'] ) ) {
			$update['post_title'] = $alt_text;
		}
		if ( ! empty( $settings['copy_to_caption'] ) ) {
			$update['post_excerpt'] = $alt_text;
		}
		if ( ! empty( $settings['copy_to_description'] ) ) {
			$update['post_content'] = sanitize_textarea_field( $alt_text );
		}

		if ( count( $update ) === 1 ) {
			return;
		}

		wp_update_post( $update );
	}

	private static function trimToMaxChars( string $alt_text, int $max_chars ): string {
		$alt_text = sanitize_text_field( $alt_text );

		if ( $max_chars > 0 && Text::length( $alt_text ) > $max_chars ) {
			$alt_text = Text::slice( $alt_text, 0, $max_chars - 1 ) . '…';
		}

		return $alt_text;
	}
}
