<?php

namespace SugarCalendarBookings\Services;

use SugarCalendarBookings\Support\Database\AbstractTableMigration;
use WP_Error;

/**
 * Pivot table for locations and services.
 *
 * @since 1.0.0
 */
class LocationServiceTableMigration extends AbstractTableMigration {

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

	/**
	 * 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` (
				`location_id` BIGINT UNSIGNED NOT NULL,
				`service_id` BIGINT UNSIGNED NOT NULL,
				`location_order` INT UNSIGNED NOT NULL DEFAULT 0,
				PRIMARY KEY  (`location_id`, `service_id`),
				INDEX `location_order` (`location_order`)
		) {$collate};";

		dbDelta( $sql );

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