<?php

namespace SugarCalendarBookings\Support\Database;

use WP_Error;

/**
 * Meta table.
 *
 * General-purpose meta table with support for multiple
 * object types (e.g., customer, service).
 *
 * @since 1.0.0
 */
class MetaTableMigration extends AbstractTableMigration {

	/**
	 * Table name.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	const TABLE_NAME = 'meta';

	/**
	 * Latest DB schema version.
	 *
	 * @since 1.0.0
	 *
	 * @var int
	 */
	const LATEST_VERSION = 1;

	/**
	 * Create the table.
	 *
	 * @since 1.0.0
	 *
	 * @return WP_Error|true
	 */
	protected function migrate_to_1() {

		global $wpdb;

		$table   = self::get_table_name();
		$collate = '';

		if ( $wpdb->has_cap( 'collation' ) ) {
			$collate = $wpdb->get_charset_collate();
		}

		$sql = "CREATE TABLE $table (
				id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
				object_type VARCHAR(30) NOT NULL,
				object_id BIGINT UNSIGNED NOT NULL,
				meta_key VARCHAR(255) DEFAULT NULL,
				meta_value LONGTEXT DEFAULT NULL,
				PRIMARY KEY  (id),
				UNIQUE KEY object_type_object_id_meta_key (object_type,object_id,meta_key)
		) {$collate};";

		dbDelta( $sql );

		return ! empty( $wpdb->last_error ) ? new WP_Error( 'migration_failed', $wpdb->last_error ) : true;
	}
}
