<?php
/**
 * Unused user meta cleanup task.
 *
 * @package DatabaseCleanup
 */

namespace DatabaseCleanup\Includes\Tasks;

use DatabaseCleanup\Includes\Protected_Items;

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

class Task_Unused_Usermeta extends Abstract_Cleanup_Task {

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

	public function get_label(): string {
		return __( 'Unused user meta', 'wp-powersuite' );
	}

	public function get_description(): string {
		return __( 'Delete usermeta rows whose parent user no longer exists (skips user_id = 0 and protected keys).', 'wp-powersuite' );
	}

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

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

		unset( $settings );

		$count = (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->usermeta} um
			LEFT JOIN {$wpdb->users} u ON u.ID = um.user_id
			WHERE u.ID IS NULL AND um.user_id > 0"
		);

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

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

		unset( $settings, $cursor );

		$meta_ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT um.umeta_id FROM {$wpdb->usermeta} um
				LEFT JOIN {$wpdb->users} u ON u.ID = um.user_id
				WHERE u.ID IS NULL AND um.user_id > 0
				ORDER BY um.umeta_id ASC
				LIMIT %d",
				$batch_size
			)
		);

		$deleted = 0;
		$bytes   = 0;

		foreach ( $meta_ids as $id ) {
			$id = (int) $id;
			if ( $id <= 0 ) {
				continue;
			}

			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
			$row = $wpdb->get_row( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->usermeta} WHERE umeta_id = %d", $id ), ARRAY_A );
			if ( is_array( $row ) ) {
				$key = (string) ( $row['meta_key'] ?? '' );
				if ( Protected_Items::is_protected_meta_key( $key, 'user' ) ) {
					continue;
				}
				$bytes += strlen( $key ) + strlen( (string) ( $row['meta_value'] ?? '' ) ) + 32;
			}
			if ( delete_metadata_by_mid( 'user', $id ) ) {
				++$deleted;
			}
		}

		$remaining = (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->usermeta} um
			LEFT JOIN {$wpdb->users} u ON u.ID = um.user_id
			WHERE u.ID IS NULL AND um.user_id > 0"
		);

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