<?php

namespace SugarCalendarBookings\Locations;

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

/**
 * Locations table.
 *
 * @since 1.0.0
 */
class LocationsTableMigration extends AbstractTableMigration {

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

	/**
	 * 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` INT UNSIGNED NOT NULL AUTO_INCREMENT,
				`name` VARCHAR(255) NOT NULL,
				`status` VARCHAR(30) NOT NULL,
				`address` VARCHAR(255) NOT NULL,
				`address2` VARCHAR(255) NULL DEFAULT NULL,
				`city` VARCHAR(100) NULL DEFAULT NULL,
				`region` VARCHAR(100) NULL DEFAULT NULL,
				`postal_code` VARCHAR(20) NULL DEFAULT NULL,
				`country_code` CHAR(2) NOT NULL,
				`latitude` DECIMAL(10,8) NULL DEFAULT NULL,
				`longitude` DECIMAL(11,8) NULL DEFAULT NULL,
				`timezone` VARCHAR(50) NULL DEFAULT NULL,
				`phone` VARCHAR(30) NULL DEFAULT NULL,
				`website` VARCHAR(255) NULL DEFAULT NULL,
				`author_id` INT UNSIGNED NOT NULL,
				`created_at` DATETIME NOT NULL,
				`updated_at` DATETIME NOT NULL,
				PRIMARY KEY  (`id`),
				INDEX `name` (`name`),
				INDEX `status` (`status`),
				INDEX `created_at` (`created_at`)
		) {$collate};";

		dbDelta( $sql );

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