<?php
/**
 * Admin bulk actions for review and history tabs.
 *
 * @package AIAltTextGenerator
 * @since 2.2.0
 */

namespace AIAltTextGenerator;

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

/**
 * @since 2.2.0
 */
class AdminActions {

	public const NONCE_ACTION = 'wpps_ai_alt_admin_list';

	/**
	 * Process list-table bulk actions for review/history tabs.
	 */
	public static function maybeProcess(): void {
		if ( ! isset( $_POST[ self::NONCE_ACTION ] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( (string) $_POST[ self::NONCE_ACTION ] ) ), self::NONCE_ACTION ) ) {
			return;
		}

		$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( (string) $_GET['tab'] ) ) : '';
		$action = self::currentBulkAction();
		$ids    = self::selectedIds();

		if ( $action === '' || $ids === [] ) {
			return;
		}

		if ( $tab === 'review' ) {
			self::processReviewBulk( $action, $ids );
		} elseif ( $tab === 'history' ) {
			self::processHistoryBulk( $action, $ids );
		}
	}

	private static function currentBulkAction(): string {
		$action  = isset( $_POST['action'] ) ? sanitize_key( wp_unslash( (string) $_POST['action'] ) ) : '';
		$action2 = isset( $_POST['action2'] ) ? sanitize_key( wp_unslash( (string) $_POST['action2'] ) ) : '';

		if ( $action !== '' && $action !== '-1' ) {
			return $action;
		}
		if ( $action2 !== '' && $action2 !== '-1' ) {
			return $action2;
		}

		return '';
	}

	/**
	 * @return list<int>
	 */
	private static function selectedIds(): array {
		$raw = isset( $_POST['item'] ) && is_array( $_POST['item'] ) ? wp_unslash( $_POST['item'] ) : [];

		return array_values(
			array_filter(
				array_map( 'intval', $raw ),
				static fn( int $id ): bool => $id > 0
			)
		);
	}

	/**
	 * @param list<int> $attachment_ids
	 */
	private static function processReviewBulk( string $action, array $attachment_ids ): void {
		if ( ! Capabilities::canGenerate() ) {
			wp_die( esc_html__( 'Permission denied.', 'wp-powersuite' ) );
		}

		$suggestions = isset( $_POST['wpps_ai_alt_suggestion'] ) && is_array( $_POST['wpps_ai_alt_suggestion'] )
			? wp_unslash( $_POST['wpps_ai_alt_suggestion'] )
			: [];

		$processed = 0;

		foreach ( $attachment_ids as $attachment_id ) {
			if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
				continue;
			}

			if ( $action === 'approve' ) {
				$alt = isset( $suggestions[ $attachment_id ] )
					? sanitize_text_field( (string) $suggestions[ $attachment_id ] )
					: AttachmentMeta::getSuggestion( $attachment_id );
				if ( $alt !== '' ) {
					AttachmentMeta::saveAltText( $attachment_id, $alt );
					delete_post_meta( $attachment_id, AttachmentMeta::META_SUGGESTION );
					++$processed;
				}
			} elseif ( $action === 'reject' ) {
				update_post_meta( $attachment_id, AttachmentMeta::META_STATUS, 'rejected' );
				delete_post_meta( $attachment_id, AttachmentMeta::META_SUGGESTION );
				++$processed;
			} elseif ( $action === 'regenerate' ) {
				if ( Module::checkRateLimit() ) {
					GenerationService::generateForAttachment( $attachment_id, true );
					++$processed;
				}
			}
		}

		Scanner::invalidateCache();
		self::redirectWithNotice( 'review', $action, $processed );
	}

	/**
	 * @param list<int> $log_ids
	 */
	private static function processHistoryBulk( string $action, array $log_ids ): void {
		$processed = 0;

		if ( $action === 'delete' ) {
			if ( ! Capabilities::canManage() ) {
				wp_die( esc_html__( 'Permission denied.', 'wp-powersuite' ) );
			}
			$processed = Logger::deleteByIds( $log_ids );
			self::redirectWithNotice( 'history', $action, $processed );
			return;
		}

		if ( ! Capabilities::canGenerate() ) {
			wp_die( esc_html__( 'Permission denied.', 'wp-powersuite' ) );
		}

		$rows = Logger::getByIds( $log_ids );
		foreach ( $rows as $row ) {
			$attachment_id = (int) ( $row['attachment_id'] ?? 0 );
			if ( $attachment_id <= 0 || ! current_user_can( 'edit_post', $attachment_id ) ) {
				continue;
			}
			if ( ! Module::checkRateLimit() ) {
				break;
			}
			$result = GenerationService::generateForAttachment( $attachment_id, true );
			if ( ( $result['status'] ?? '' ) === 'success' ) {
				++$processed;
			}
		}

		Scanner::invalidateCache();
		self::redirectWithNotice( 'history', $action, $processed );
	}

	private static function redirectWithNotice( string $tab, string $action, int $count ): void {
		wp_safe_redirect(
			add_query_arg(
				[
					'page'        => Module::DASHBOARD_SLUG,
					'tab'         => $tab,
					'bulk_done'   => sanitize_key( $action ),
					'bulk_count'  => max( 0, $count ),
				],
				admin_url( 'admin.php' )
			)
		);
		exit;
	}
}
