<?php
/**
 * Pingback and trackback comment cleanup task.
 *
 * @package DatabaseCleanup
 */

namespace DatabaseCleanup\Includes\Tasks;

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

class Task_Pingbacks extends Abstract_Cleanup_Task {

	public function get_id(): string {
		return 'pingbacks';
	}

	public function get_label(): string {
		return __( 'Pingbacks & trackbacks', 'wppowersuite-lite' );
	}

	public function get_description(): string {
		return __( 'Remove pingback and trackback comments, which are rarely needed on modern sites.', 'wppowersuite-lite' );
	}

	public function is_safe(): bool {
		// Pingbacks can be intentional on some sites — require Review confirmation.
		return false;
	}

	public function scan( array $settings ): array {
		global $wpdb;

		unset( $settings );

		$count = (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->comments}
			WHERE comment_type IN ('pingback', 'trackback')"
		);

		return [
			'count'           => $count,
			'estimated_bytes' => $this->estimate_row_bytes( $count, 768 ),
			'details'         => [],
		];
	}

	public function clean( array $settings, int $batch_size, mixed $cursor = null ): array {
		global $wpdb;

		unset( $settings, $cursor );

		$ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT comment_ID FROM {$wpdb->comments}
				WHERE comment_type IN ('pingback', 'trackback')
				ORDER BY comment_ID ASC
				LIMIT %d",
				$batch_size
			)
		);

		$deleted = 0;
		$bytes   = 0;

		foreach ( $ids as $id ) {
			$comment = get_comment( (int) $id );
			if ( $comment ) {
				$bytes += strlen( (string) $comment->comment_content ) + 256;
			}

			if ( wp_delete_comment( (int) $id, true ) ) {
				++$deleted;
			}
		}

		$remaining = (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->comments}
			WHERE comment_type IN ('pingback', 'trackback')"
		);

		return [
			'deleted' => $deleted,
			'done'    => $remaining === 0,
			'cursor'  => null,
			'bytes'   => $bytes,
		];
	}
}
