<?php
/**
 * Admin tool to delete locked created by the Course Data background processor.
 *
 * @package LifterLMS/Admin/Tools/Classes
 *
 * @since 9.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * LLMS_Admin_Tool_Course_Data_Lock_Eraser
 *
 * @since 9.0.0
 */
class LLMS_Admin_Tool_Course_Data_Lock_Eraser extends LLMS_Abstract_Admin_Tool {

	/**
	 * Tool ID.
	 *
	 * @var string
	 */
	protected $id = 'course-data-eraser';

	/**
	 * Retrieve a description of the tool.
	 *
	 * This is displayed on the right side of the tool's list before the button.
	 *
	 * @since 9.0.0
	 *
	 * @return string
	 */
	protected function get_description() {

		$count = $this->get_locked_courses();

		$desc  = __( 'Deletes locks generated by LifterLMS course data background processor.', 'lifterlms' );
		$desc .= ' ';
		// Translators: %d = the number of pending batches.
		$desc .= sprintf(
			_n(
				'There is currently %d lock that will be deleted.',
				'There are currently %d locks that will be deleted.',
				$count,
				'lifterlms'
			),
			$count
		);

		return $desc;
	}

	/**
	 * Retrieve the tool's label
	 *
	 * The label is the tool's title. It's displayed in the left column on the tool's list.
	 *
	 * @since 9.0.0
	 *
	 * @return string
	 */
	protected function get_label() {
		return __( 'Delete course data locks', 'lifterlms' );
	}

	/**
	 * Retrieve the tool's button text
	 *
	 * @since 9.0.0
	 *
	 * @return string
	 */
	protected function get_text() {
		return __( 'Delete locks', 'lifterlms' );
	}

	/**
	 * Retrieve the number of course data locks.
	 *
	 * @since 9.0.0
	 *
	 * @return int
	 */
	protected function get_locked_courses() {

		$count = wp_cache_get( $this->id, 'llms_tool_data' );
		if ( false === $count ) {

			global $wpdb;
			$count = absint( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = '_llms_temp_calc_data_lock';" ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery

			wp_cache_set( $this->id, $count, 'llms_tool_data' );

		}

		return $count;
	}

	/**
	 * Process the tool.
	 *
	 * This method should do whatever the tool actually does.
	 *
	 * By the time this tool is called a nonce and the user's capabilities have already been checked.
	 *
	 * @since 9.0.0
	 *
	 * @return bool
	 */
	protected function handle() {

		$res = delete_post_meta_by_key( '_llms_temp_calc_data_lock' );
		wp_cache_delete( $this->id, 'llms_tool_data' );
		return $res;
	}

	/**
	 * Conditionally load the tool.
	 *
	 * This tool should only load if there's locks in the database.
	 *
	 * @since 9.0.0
	 *
	 * @return boolean Return `true` to load the tool and `false` to not load it.
	 */
	protected function should_load() {

		return $this->get_locked_courses() > 0;
	}
}

return new LLMS_Admin_Tool_Course_Data_Lock_Eraser();
