<?php
/**
 * Auto-draft cleanup task.
 *
 * @package DatabaseCleanup
 */

namespace DatabaseCleanup\Includes\Tasks;

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

class Task_Auto_Drafts extends Abstract_Cleanup_Task {

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

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

	public function get_description(): string {
		return __( 'Delete stale auto-draft posts left behind by the editor (protected post types are skipped).', 'wppowersuite-lite' );
	}

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

	/**
	 * @param array<string, mixed> $settings
	 */
	private function cutoff( array $settings ): string {
		$days = max( 1, absint( $settings['auto_draft_days'] ?? 1 ) );

		return gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) );
	}

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

		$days    = max( 1, absint( $settings['auto_draft_days'] ?? 1 ) );
		$cutoff  = $this->cutoff( $settings );
		$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 = 'auto-draft' AND post_modified < %s{$exclude}",
				$cutoff
			)
		);

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

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

		unset( $cursor );

		$cutoff  = $this->cutoff( $settings );
		$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 = 'auto-draft' 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 ) + 512;

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

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

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