<?php
/**
 * Unapproved comments cleanup task.
 *
 * @package DatabaseCleanup
 */

namespace DatabaseCleanup\Includes\Tasks;

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

class Task_Unapproved_Comments extends Abstract_Cleanup_Task {

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

	public function get_label(): string {
		return __( 'Unapproved comments', 'wp-powersuite' );
	}

	public function get_description(): string {
		return __( 'Remove comments awaiting moderation older than the configured threshold. Recent pending comments are kept.', 'wp-powersuite' );
	}

	public function is_safe(): bool {
		return false;
	}

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

		$days   = max( 30, absint( $settings['unapproved_comment_days'] ?? 30 ) );
		$cutoff = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );

		$count = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->comments}
				WHERE comment_approved = '0'
				AND comment_date < %s",
				$cutoff
			)
		);

		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( $cursor );

		$days   = max( 30, absint( $settings['unapproved_comment_days'] ?? 30 ) );
		$cutoff = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );

		$ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT comment_ID FROM {$wpdb->comments}
				WHERE comment_approved = '0'
				AND comment_date < %s
				ORDER BY comment_ID ASC
				LIMIT %d",
				$cutoff,
				$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(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->comments}
				WHERE comment_approved = '0'
				AND comment_date < %s",
				$cutoff
			)
		);

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