<?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 ( class_exists( PremiumDuplicateActions::class, false ) ) {
			return PremiumDuplicateActions::regenerate();
		}

		return [
			'queued'  => 0,
			'message' => __( 'Bulk duplicate regeneration is available in Pro.', 'wppowersuite-lite' ),
		];
	}

	/**
	 * 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.', 'wppowersuite-lite' ),
				$synced,
				$posts,
				$skipped
			),
		];
	}
}
