<?php
/**
 * Dashboard and bulk operations.
 *
 * @package AIAltTextGenerator
 * @since 1.8.0
 */

namespace AIAltTextGenerator;

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

/**
 * @since 1.8.0
 */
class BulkActions {

	/**
	 * Queue or process duplicate alt regeneration.
	 *
	 * @return array{queued: int, message: string}
	 */
	public static function regenerateDuplicates(): array {
		if ( ! FeatureGate::featureEnabled( 'bulk_duplicates' ) ) {
			return [
				'queued'  => 0,
				'message' => __( 'Bulk duplicate regeneration requires a Pro license.', 'wp-powersuite' ),
			];
		}

		$ids = array_values(
			array_filter(
				array_map( 'intval', DuplicateDetector::getDuplicateAttachmentIds() ),
				static function ( int $id ): bool {
					return $id > 0 && current_user_can( 'edit_post', $id );
				}
			)
		);
		if ( $ids === [] ) {
			return [
				'queued'  => 0,
				'message' => __( 'No duplicate alt images found.', 'wp-powersuite' ),
			];
		}

		$settings = Settings::get();
		if ( ! Settings::hasApiKey() ) {
			return [
				'queued'  => 0,
				'message' => __( 'API key is not configured for the selected provider.', 'wp-powersuite' ),
			];
		}

		if ( ! empty( $settings['queue_enabled'] ) ) {
			$added = Queue::enqueue( $ids, true );
			return [
				'queued'  => $added,
				'message' => sprintf(
					/* translators: %d: number of images */
					_n( '%d duplicate image queued for regeneration.', '%d duplicate images queued for regeneration.', $added, 'wp-powersuite' ),
					$added
				),
			];
		}

		$processed = 0;
		foreach ( array_slice( $ids, 0, 5 ) as $attachment_id ) {
			if ( ! Module::checkRateLimit() ) {
				break;
			}

			$result = GenerationService::generateForAttachment( (int) $attachment_id, true );
			if ( $result['status'] === 'success' ) {
				++$processed;
			}
		}

		return [
			'queued'  => $processed,
			'message' => sprintf(
				/* translators: 1: processed count, 2: total duplicates */
				__( 'Regenerated %1$d of %2$d duplicate images. Enable the background queue to process all at once.', 'wp-powersuite' ),
				$processed,
				count( $ids )
			),
		];
	}

	/**
	 * Push library alt text into post content for scanned issues.
	 *
	 * @return array{synced: int, skipped: int, posts: int, message: string}
	 */
	public static function syncLibraryAltToContent( bool $refresh_scan = false ): array {
		$summary = ContentScanner::getSummary( $refresh_scan );
		$ids     = is_array( $summary['issue_attachment_ids'] ?? null ) ? $summary['issue_attachment_ids'] : [];

		if ( $ids === [] ) {
			foreach ( is_array( $summary['sample_issues'] ?? null ) ? $summary['sample_issues'] : [] as $row ) {
				foreach ( (array) ( $row['issues'] ?? [] ) as $issue ) {
					$id = (int) ( $issue['attachment_id'] ?? 0 );
					if ( $id > 0 ) {
						$ids[] = $id;
					}
				}
			}
			$ids = array_values( array_unique( $ids ) );
		}

		$synced  = 0;
		$skipped = 0;
		$posts   = 0;

		foreach ( $ids as $attachment_id ) {
			$alt = trim( (string) get_post_meta( (int) $attachment_id, '_wp_attachment_image_alt', true ) );
			if ( $alt === '' ) {
				++$skipped;
				continue;
			}

			$updated = ContentSync::pushLibraryAlt( (int) $attachment_id, $alt );
			if ( $updated > 0 ) {
				++$synced;
				$posts += $updated;
			}
		}

		ContentScanner::invalidateCache();

		return [
			'synced'  => $synced,
			'skipped' => $skipped,
			'posts'   => $posts,
			'message' => sprintf(
				/* translators: 1: images synced, 2: posts updated, 3: skipped count */
				__( 'Synced %1$d images into %2$d posts. Skipped %3$d images without library alt text.', 'wp-powersuite' ),
				$synced,
				$posts,
				$skipped
			),
		];
	}
}
