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

namespace DatabaseCleanup\Includes\Tasks;

use DatabaseCleanup\Includes\Protected_Items;

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

class Task_Unused_Termmeta extends Abstract_Cleanup_Task {

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

	public function get_label(): string {
		return __( 'Unused term meta', 'wppowersuite-lite' );
	}

	public function get_description(): string {
		return __( 'Delete termmeta rows whose parent term no longer exists (skips term_id = 0 and protected keys).', 'wppowersuite-lite' );
	}

	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->termmeta} tm
			LEFT JOIN {$wpdb->terms} t ON t.term_id = tm.term_id
			WHERE t.term_id IS NULL AND tm.term_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 tm.meta_id FROM {$wpdb->termmeta} tm
				LEFT JOIN {$wpdb->terms} t ON t.term_id = tm.term_id
				WHERE t.term_id IS NULL AND tm.term_id > 0
				ORDER BY tm.meta_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->termmeta} WHERE meta_id = %d", $id ), ARRAY_A );
			if ( is_array( $row ) ) {
				$key = (string) ( $row['meta_key'] ?? '' );
				if ( Protected_Items::is_protected_meta_key( $key, 'term' ) ) {
					continue;
				}
				$bytes += strlen( $key ) + strlen( (string) ( $row['meta_value'] ?? '' ) ) + 32;
			}
			if ( delete_metadata_by_mid( 'term', $id ) ) {
				++$deleted;
			}
		}

		$remaining = (int) $wpdb->get_var(
			"SELECT COUNT(*) FROM {$wpdb->termmeta} tm
			LEFT JOIN {$wpdb->terms} t ON t.term_id = tm.term_id
			WHERE t.term_id IS NULL AND tm.term_id > 0"
		);

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