<?php
/**
 * REST API KKART System Status Tools Controller
 *
 * Handles requests to the /system_status/tools/* endpoints.
 *
 * @package Kkart\RestApi
 * @since   3.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * System status tools controller.
 *
 * @package Kkart\RestApi
 * @extends KKART_REST_Controller
 */
class KKART_REST_System_Status_Tools_V2_Controller extends KKART_REST_Controller {

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'kkart/v2';

	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'system_status/tools';

	/**
	 * Register the routes for /system_status/tools/*.
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_items' ),
					'permission_callback' => array( $this, 'get_items_permissions_check' ),
					'args'                => $this->get_collection_params(),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);

		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<id>[\w-]+)',
			array(
				'args'   => array(
					'id' => array(
						'description' => __( 'Unique identifier for the resource.', 'kkart' ),
						'type'        => 'string',
					),
				),
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => array( $this, 'get_item_permissions_check' ),
				),
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_item' ),
					'permission_callback' => array( $this, 'update_item_permissions_check' ),
					'args'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
				),
				'schema' => array( $this, 'get_public_item_schema' ),
			)
		);
	}

	/**
	 * Check whether a given request has permission to view system status tools.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function get_items_permissions_check( $request ) {
		if ( ! kkart_rest_check_manager_permissions( 'system_status', 'read' ) ) {
			return new WP_Error( 'kkart_rest_cannot_view', __( 'Sorry, you cannot list resources.', 'kkart' ), array( 'status' => rest_authorization_required_code() ) );
		}
		return true;
	}

	/**
	 * Check whether a given request has permission to view a specific system status tool.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function get_item_permissions_check( $request ) {
		if ( ! kkart_rest_check_manager_permissions( 'system_status', 'read' ) ) {
			return new WP_Error( 'kkart_rest_cannot_view', __( 'Sorry, you cannot view this resource.', 'kkart' ), array( 'status' => rest_authorization_required_code() ) );
		}
		return true;
	}

	/**
	 * Check whether a given request has permission to execute a specific system status tool.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function update_item_permissions_check( $request ) {
		if ( ! kkart_rest_check_manager_permissions( 'system_status', 'edit' ) ) {
			return new WP_Error( 'kkart_rest_cannot_update', __( 'Sorry, you cannot update resource.', 'kkart' ), array( 'status' => rest_authorization_required_code() ) );
		}
		return true;
	}

	/**
	 * A list of available tools for use in the system status section.
	 * 'button' becomes 'action' in the API.
	 *
	 * @return array
	 */
	public function get_tools() {
		$tools = array(
			'clear_transients'                   => array(
				'name'   => __( 'Kkart transients', 'kkart' ),
				'button' => __( 'Clear transients', 'kkart' ),
				'desc'   => __( 'This tool will clear the product/shop transients cache.', 'kkart' ),
			),
			'clear_expired_transients'           => array(
				'name'   => __( 'Expired transients', 'kkart' ),
				'button' => __( 'Clear transients', 'kkart' ),
				'desc'   => __( 'This tool will clear ALL expired transients.', 'kkart' ),
			),
			'delete_orphaned_variations'         => array(
				'name'   => __( 'Orphaned variations', 'kkart' ),
				'button' => __( 'Delete orphaned variations', 'kkart' ),
				'desc'   => __( 'This tool will delete all variations which have no parent.', 'kkart' ),
			),
			'clear_expired_download_permissions' => array(
				'name'   => __( 'Used-up download permissions', 'kkart' ),
				'button' => __( 'Clean up download permissions', 'kkart' ),
				'desc'   => __( 'This tool will delete expired download permissions and permissions with 0 remaining downloads.', 'kkart' ),
			),
			'regenerate_product_lookup_tables' => array(
				'name'   => __( 'Product lookup tables', 'kkart' ),
				'button' => __( 'Regenerate', 'kkart' ),
				'desc'   => __( 'This tool will regenerate product lookup table data. This process may take a while.', 'kkart' ),
			),
			'recount_terms'                      => array(
				'name'   => __( 'Term counts', 'kkart' ),
				'button' => __( 'Recount terms', 'kkart' ),
				'desc'   => __( 'This tool will recount product terms - useful when changing your settings in a way which hides products from the catalog.', 'kkart' ),
			),
			'reset_roles'                        => array(
				'name'   => __( 'Capabilities', 'kkart' ),
				'button' => __( 'Reset capabilities', 'kkart' ),
				'desc'   => __( 'This tool will reset the admin, customer and shop_manager roles to default. Use this if your users cannot access all of the Kkart admin pages.', 'kkart' ),
			),
			'clear_sessions'                     => array(
				'name'   => __( 'Clear customer sessions', 'kkart' ),
				'button' => __( 'Clear', 'kkart' ),
				'desc'   => sprintf(
					'<strong class="red">%1$s</strong> %2$s',
					__( 'Note:', 'kkart' ),
					__( 'This tool will delete all customer session data from the database, including current carts and saved carts in the database.', 'kkart' )
				),
			),
			'clear_template_cache'               => array(
				'name'   => __( 'Clear template cache', 'kkart' ),
				'button' => __( 'Clear', 'kkart' ),
				'desc'   => sprintf(
					'<strong class="red">%1$s</strong> %2$s',
					__( 'Note:', 'kkart' ),
					__( 'This tool will empty the template cache.', 'kkart' )
				),
			),
			'install_pages'                      => array(
				'name'   => __( 'Create default Kkart pages', 'kkart' ),
				'button' => __( 'Create pages', 'kkart' ),
				'desc'   => sprintf(
					'<strong class="red">%1$s</strong> %2$s',
					__( 'Note:', 'kkart' ),
					__( 'This tool will install all the missing Kkart pages. Pages already defined and set up will not be replaced.', 'kkart' )
				),
			),
			'delete_taxes'                       => array(
				'name'   => __( 'Delete Kkart tax rates', 'kkart' ),
				'button' => __( 'Delete tax rates', 'kkart' ),
				'desc'   => sprintf(
					'<strong class="red">%1$s</strong> %2$s',
					__( 'Note:', 'kkart' ),
					__( 'This option will delete ALL of your tax rates, use with caution. This action cannot be reversed.', 'kkart' )
				),
			),
			'regenerate_thumbnails'              => array(
				'name'   => __( 'Regenerate shop thumbnails', 'kkart' ),
				'button' => __( 'Regenerate', 'kkart' ),
				'desc'   => __( 'This will regenerate all shop thumbnails to match your theme and/or image settings.', 'kkart' ),
			),
			'db_update_routine'                  => array(
				'name'   => __( 'Update database', 'kkart' ),
				'button' => __( 'Update database', 'kkart' ),
				'desc'   => sprintf(
					'<strong class="red">%1$s</strong> %2$s',
					__( 'Note:', 'kkart' ),
					__( 'This tool will update your Kkart database to the latest version. Please ensure you make sufficient backups before proceeding.', 'kkart' )
				),
			),
		);
		if ( method_exists( 'KKART_Install', 'verify_base_tables' ) ) {
			$tools['verify_db_tables'] = array(
				'name'   => __( 'Verify base database tables', 'kkart' ),
				'button' => __( 'Verify database', 'kkart' ),
				'desc'   => sprintf(
					__( 'Verify if all base database tables are present.', 'kkart' )
				),
			);
		}

		// Jetpack does the image resizing heavy lifting so you don't have to.
		if ( ( class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'photon' ) ) || ! apply_filters( 'kkart_background_image_regeneration', true ) ) {
			unset( $tools['regenerate_thumbnails'] );
		}

		if ( ! function_exists( 'kkart_clear_template_cache' ) ) {
			unset( $tools['clear_template_cache'] );
		}

		return apply_filters( 'kkart_debug_tools', $tools );
	}

	/**
	 * Get a list of system status tools.
	 *
	 * @param WP_REST_Request $request Full details about the request.
	 * @return WP_Error|WP_REST_Response
	 */
	public function get_items( $request ) {
		$tools = array();
		foreach ( $this->get_tools() as $id => $tool ) {
			$tools[] = $this->prepare_response_for_collection(
				$this->prepare_item_for_response(
					array(
						'id'          => $id,
						'name'        => $tool['name'],
						'action'      => $tool['button'],
						'description' => $tool['desc'],
					),
					$request
				)
			);
		}

		$response = rest_ensure_response( $tools );
		return $response;
	}

	/**
	 * Return a single tool.
	 *
	 * @param  WP_REST_Request $request Request data.
	 * @return WP_Error|WP_REST_Response
	 */
	public function get_item( $request ) {
		$tools = $this->get_tools();
		if ( empty( $tools[ $request['id'] ] ) ) {
			return new WP_Error( 'kkart_rest_system_status_tool_invalid_id', __( 'Invalid tool ID.', 'kkart' ), array( 'status' => 404 ) );
		}
		$tool = $tools[ $request['id'] ];
		return rest_ensure_response(
			$this->prepare_item_for_response(
				array(
					'id'          => $request['id'],
					'name'        => $tool['name'],
					'action'      => $tool['button'],
					'description' => $tool['desc'],
				),
				$request
			)
		);
	}

	/**
	 * Update (execute) a tool.
	 *
	 * @param  WP_REST_Request $request Request data.
	 * @return WP_Error|WP_REST_Response
	 */
	public function update_item( $request ) {
		$tools = $this->get_tools();
		if ( empty( $tools[ $request['id'] ] ) ) {
			return new WP_Error( 'kkart_rest_system_status_tool_invalid_id', __( 'Invalid tool ID.', 'kkart' ), array( 'status' => 404 ) );
		}

		$tool = $tools[ $request['id'] ];
		$tool = array(
			'id'          => $request['id'],
			'name'        => $tool['name'],
			'action'      => $tool['button'],
			'description' => $tool['desc'],
		);

		$execute_return = $this->execute_tool( $request['id'] );
		$tool           = array_merge( $tool, $execute_return );

		/**
		 * Fires after a Kkart REST system status tool has been executed.
		 *
		 * @param array           $tool    Details about the tool that has been executed.
		 * @param WP_REST_Request $request The current WP_REST_Request object.
		 */
		do_action( 'kkart_rest_insert_system_status_tool', $tool, $request );

		$request->set_param( 'context', 'edit' );
		$response = $this->prepare_item_for_response( $tool, $request );
		return rest_ensure_response( $response );
	}

	/**
	 * Prepare a tool item for serialization.
	 *
	 * @param  array           $item     Object.
	 * @param  WP_REST_Request $request  Request object.
	 * @return WP_REST_Response $response Response data.
	 */
	public function prepare_item_for_response( $item, $request ) {
		$context = empty( $request['context'] ) ? 'view' : $request['context'];
		$data    = $this->add_additional_fields_to_object( $item, $request );
		$data    = $this->filter_response_by_context( $data, $context );

		$response = rest_ensure_response( $data );

		$response->add_links( $this->prepare_links( $item['id'] ) );

		return $response;
	}

	/**
	 * Get the system status tools schema, conforming to JSON Schema.
	 *
	 * @return array
	 */
	public function get_item_schema() {
		$schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => 'system_status_tool',
			'type'       => 'object',
			'properties' => array(
				'id'          => array(
					'description' => __( 'A unique identifier for the tool.', 'kkart' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'arg_options' => array(
						'sanitize_callback' => 'sanitize_title',
					),
				),
				'name'        => array(
					'description' => __( 'Tool name.', 'kkart' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'arg_options' => array(
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
				'action'      => array(
					'description' => __( 'What running the tool will do.', 'kkart' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'arg_options' => array(
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
				'description' => array(
					'description' => __( 'Tool description.', 'kkart' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'arg_options' => array(
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
				'success'     => array(
					'description' => __( 'Did the tool run successfully?', 'kkart' ),
					'type'        => 'boolean',
					'context'     => array( 'edit' ),
				),
				'message'     => array(
					'description' => __( 'Tool return message.', 'kkart' ),
					'type'        => 'string',
					'context'     => array( 'edit' ),
					'arg_options' => array(
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
			),
		);

		return $this->add_additional_fields_schema( $schema );
	}

	/**
	 * Prepare links for the request.
	 *
	 * @param string $id ID.
	 * @return array
	 */
	protected function prepare_links( $id ) {
		$base  = '/' . $this->namespace . '/' . $this->rest_base;
		$links = array(
			'item' => array(
				'href'       => rest_url( trailingslashit( $base ) . $id ),
				'embeddable' => true,
			),
		);

		return $links;
	}

	/**
	 * Get any query params needed.
	 *
	 * @return array
	 */
	public function get_collection_params() {
		return array(
			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
		);
	}

	/**
	 * Actually executes a tool.
	 *
	 * @param  string $tool Tool.
	 * @return array
	 */
	public function execute_tool( $tool ) {
		global $wpdb;
		$ran = true;
		switch ( $tool ) {
			case 'clear_transients':
				kkart_delete_product_transients();
				kkart_delete_shop_order_transients();
				delete_transient( 'kkart_count_comments' );
				delete_transient( 'as_comment_count' );

				$attribute_taxonomies = kkart_get_attribute_taxonomies();

				if ( $attribute_taxonomies ) {
					foreach ( $attribute_taxonomies as $attribute ) {
						delete_transient( 'kkart_layered_nav_counts_pa_' . $attribute->attribute_name );
					}
				}

				KKART_Cache_Helper::get_transient_version( 'shipping', true );
				$message = __( 'Product transients cleared', 'kkart' );
				break;

			case 'clear_expired_transients':
				/* translators: %d: amount of expired transients */
				$message = sprintf( __( '%d transients rows cleared', 'kkart' ), kkart_delete_expired_transients() );
				break;

			case 'delete_orphaned_variations':
				// Delete orphans.
				$result = absint(
					$wpdb->query(
						"DELETE products
					FROM {$wpdb->posts} products
					LEFT JOIN {$wpdb->posts} wp ON wp.ID = products.post_parent
					WHERE wp.ID IS NULL AND products.post_type = 'product_variation';"
					)
				);
				/* translators: %d: amount of orphaned variations */
				$message = sprintf( __( '%d orphaned variations deleted', 'kkart' ), $result );
				break;

			case 'clear_expired_download_permissions':
				// Delete expired download permissions and ones with 0 downloads remaining.
				$result = absint(
					$wpdb->query(
						$wpdb->prepare(
							"DELETE FROM {$wpdb->prefix}kkart_downloadable_product_permissions
							WHERE ( downloads_remaining != '' AND downloads_remaining = 0 ) OR ( access_expires IS NOT NULL AND access_expires < %s )",
							gmdate( 'Y-m-d', current_time( 'timestamp' ) )
						)
					)
				);
				/* translators: %d: amount of permissions */
				$message = sprintf( __( '%d permissions deleted', 'kkart' ), $result );
				break;

			case 'regenerate_product_lookup_tables':
				if ( ! kkart_update_product_lookup_tables_is_running() ) {
					kkart_update_product_lookup_tables();
				}
				$message = __( 'Lookup tables are regenerating', 'kkart' );
				break;
			case 'reset_roles':
				// Remove then re-add caps and roles.
				KKART_Install::remove_roles();
				KKART_Install::create_roles();
				$message = __( 'Roles successfully reset', 'kkart' );
				break;

			case 'recount_terms':
				$product_cats = get_terms(
					'product_cat',
					array(
						'hide_empty' => false,
						'fields'     => 'id=>parent',
					)
				);
				_kkart_term_recount( $product_cats, get_taxonomy( 'product_cat' ), true, false );
				$product_tags = get_terms(
					'product_tag',
					array(
						'hide_empty' => false,
						'fields'     => 'id=>parent',
					)
				);
				_kkart_term_recount( $product_tags, get_taxonomy( 'product_tag' ), true, false );
				$message = __( 'Terms successfully recounted', 'kkart' );
				break;

			case 'clear_sessions':
				$wpdb->query( "TRUNCATE {$wpdb->prefix}kkart_sessions" );
				$result = absint( $wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key='_kkart_persistent_cart_" . get_current_blog_id() . "';" ) ); // WPCS: unprepared SQL ok.
				wp_cache_flush();
				/* translators: %d: amount of sessions */
				$message = sprintf( __( 'Deleted all active sessions, and %d saved carts.', 'kkart' ), absint( $result ) );
				break;

			case 'install_pages':
				KKART_Install::create_pages();
				$message = __( 'All missing Kkart pages successfully installed', 'kkart' );
				break;

			case 'delete_taxes':
				$wpdb->query( "TRUNCATE TABLE {$wpdb->prefix}kkart_tax_rates;" );
				$wpdb->query( "TRUNCATE TABLE {$wpdb->prefix}kkart_tax_rate_locations;" );

				if ( method_exists( 'KKART_Cache_Helper', 'invalidate_cache_group' ) ) {
					KKART_Cache_Helper::invalidate_cache_group( 'taxes' );
				} else {
					KKART_Cache_Helper::incr_cache_prefix( 'taxes' );
				}
				$message = __( 'Tax rates successfully deleted', 'kkart' );
				break;

			case 'regenerate_thumbnails':
				KKART_Regenerate_Images::queue_image_regeneration();
				$message = __( 'Thumbnail regeneration has been scheduled to run in the background.', 'kkart' );
				break;

			case 'db_update_routine':
				$blog_id = get_current_blog_id();
				// Used to fire an action added in WP_Background_Process::_construct() that calls WP_Background_Process::handle_cron_healthcheck().
				// This method will make sure the database updates are executed even if cron is disabled. Nothing will happen if the updates are already running.
				do_action( 'wp_' . $blog_id . '_kkart_updater_cron' );
				$message = __( 'Database upgrade routine has been scheduled to run in the background.', 'kkart' );
				break;

			case 'clear_template_cache':
				if ( function_exists( 'kkart_clear_template_cache' ) ) {
					kkart_clear_template_cache();
					$message = __( 'Template cache cleared.', 'kkart' );
				} else {
					$message = __( 'The active version of Kkart does not support template cache clearing.', 'kkart' );
					$ran = false;
				}
				break;

			case 'verify_db_tables':
				if ( ! method_exists( 'KKART_Install', 'verify_base_tables' ) ) {
					$message = __( 'You need Kkart 4.2 or newer to run this tool.', 'kkart' );
					$ran = false;
					break;
				}
				// Try to manually create table again.
				$missing_tables = KKART_Install::verify_base_tables( true, true );
				if ( 0 === count( $missing_tables ) ) {
					$message = __( 'Database verified successfully.', 'kkart' );
				} else {
					$message = __( 'Verifying database... One or more tables are still missing: ', 'kkart' );
					$message .= implode( ', ', $missing_tables );
					$ran = false;
				}
				break;

			default:
				$tools = $this->get_tools();
				if ( isset( $tools[ $tool ]['callback'] ) ) {
					$callback = $tools[ $tool ]['callback'];
					$return   = call_user_func( $callback );
					if ( is_string( $return ) ) {
						$message = $return;
					} elseif ( false === $return ) {
						$callback_string = is_array( $callback ) ? get_class( $callback[0] ) . '::' . $callback[1] : $callback;
						$ran             = false;
						/* translators: %s: callback string */
						$message = sprintf( __( 'There was an error calling %s', 'kkart' ), $callback_string );
					} else {
						$message = __( 'Tool ran.', 'kkart' );
					}
				} else {
					$ran     = false;
					$message = __( 'There was an error calling this tool. There is no callback present.', 'kkart' );
				}
				break;
		}

		return array(
			'success' => $ran,
			'message' => $message,
		);
	}
}
