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

namespace DatabaseCleanup\Includes\Tasks;

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

class Task_Old_Drafts extends Abstract_Cleanup_Task {

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

	public function get_label(): string {
		return __( 'Old draft posts', 'wp-powersuite' );
	}

	public function get_description(): string {
		return __( 'Delete draft posts that have not been updated recently.', 'wp-powersuite' );
	}

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

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

		$days    = max( 1, absint( $settings['draft_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 = 'draft'
				AND post_type NOT IN ('revision', 'auto-draft')
				AND post_modified < %s{$exclude}",
				$cutoff
			)
		);

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

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

		unset( $cursor );

		$days    = max( 1, absint( $settings['draft_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 = 'draft'
				AND post_type NOT IN ('revision', '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 ) + 1024;

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

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

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