<?php
namespace SugarCalendarBookings\Support\Helpers;

/**
 * Class DB.
 *
 * Helper class for working with the database.
 *
 * @since 1.0.0
 */
class DB {

	/**
	 * Existing tables cache.
	 *
	 * @since 1.0.0
	 *
	 * @var null|array
	 */
	private static $existing_tables;

	/**
	 * Plugin tables prefix.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	private static $prefix = 'scbookings_';

	/**
	 * Get full prefix for plugin tables.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public static function get_prefix() {

		global $wpdb;

		return $wpdb->prefix . self::$prefix;
	}

	/**
	 * Check if table exists.
	 *
	 * @since 1.0.0
	 *
	 * @param string $table Table name.
	 *
	 * @return bool
	 */
	public static function table_exists( $table ) {

		if ( strpos( $table, self::get_prefix() ) === false ) {
			$table = self::get_prefix() . $table;
		}

		return in_array( $table, self::get_existing_tables(), true );
	}

	/**
	 * Get existing plugin tables.
	 *
	 * @since 1.0.0
	 *
	 * @return array
	 */
	private static function get_existing_tables() {

		if ( self::$existing_tables !== null ) {
			return self::$existing_tables;
		}

		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$existing_tables = $wpdb->get_col(
			$wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( self::get_prefix() ) . '%' )
		);

		$existing_tables = is_array( $existing_tables ) ? $existing_tables : [];

		self::$existing_tables = $existing_tables;

		return self::$existing_tables;
	}
}
