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

namespace DatabaseCleanup\Includes\Tasks;

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

class Task_Trashed_Posts extends Abstract_Cleanup_Task {

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

	public function get_label(): string {
		return __( 'Trashed posts', 'wppowersuite-lite' );
	}

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

	public function is_safe(): bool {
		// Trashed content may include recoverable builder templates — require Review.
		return false;
	}

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

		$days    = max( 1, absint( $settings['trash_post_days'] ?? 30 ) );
		$cutoff  = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );
		$exclude = $this->sql_post_type_exclusion( $this->excluded_post_types( $settings ) );

		$count = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = 'trash' AND post_modified < %s{$exclude}",
				$cutoff
			)
		);

		return [
			'count'           => $count,
			'estimated_bytes' => $this->estimate_row_bytes( $count, 4096 ),
			'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_post_days'] ?? 30 ) );
		$cutoff  = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );
		$exclude = $this->sql_post_type_exclusion( $this->excluded_post_types( $settings ) );

		$ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT ID FROM {$wpdb->posts} WHERE post_status = 'trash' AND post_modified < %s{$exclude} ORDER BY ID ASC LIMIT %d",
				$cutoff,
				$batch_size
			)
		);

		$deleted = 0;
		$bytes   = 0;

		foreach ( $ids as $id ) {
			$post = get_post( (int) $id );
			if ( ! $post ) {
				continue;
			}

			$bytes += strlen( (string) $post->post_content ) + 1024;

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

		$remaining = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = 'trash' AND post_modified < %s{$exclude}",
				$cutoff
			)
		);

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