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

namespace DatabaseCleanup\Includes\Tasks;

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

class Task_Trashed_Comments extends Abstract_Cleanup_Task {

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

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

	public function get_description(): string {
		return __( 'Permanently delete comments in the trash older than the configured threshold.', 'wp-powersuite' );
	}

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

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

		$days   = max( 1, absint( $settings['trash_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 = 'trash' AND comment_date < %s",
				$cutoff
			)
		);

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

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

		unset( $cursor );

		$days   = max( 1, absint( $settings['trash_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 = 'trash' 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 = 'trash' AND comment_date < %s",
				$cutoff
			)
		);

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