<?php

namespace SugarCalendarBookings\Payments;

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

/**
 * Payments table.
 *
 * @since 1.0.0
 */
class PaymentsTableMigration extends AbstractTableMigration {

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

	/**
	 * 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,
			customer_id BIGINT UNSIGNED NOT NULL,
			status VARCHAR(30) NOT NULL DEFAULT '',
			subtotal_amount DECIMAL(26,8) NOT NULL DEFAULT 0,
			total_amount DECIMAL(26,8) NOT NULL DEFAULT 0,
			currency VARCHAR(3) NOT NULL DEFAULT '',
			gateway VARCHAR(30) NOT NULL DEFAULT '',
			mode VARCHAR(4) NOT NULL DEFAULT '',
			tracking_id VARCHAR(40) NOT NULL DEFAULT '',
			transaction_id VARCHAR(40) NOT NULL DEFAULT '',
			created_at DATETIME NOT NULL,
			updated_at DATETIME NOT NULL,
			trashed_at DATETIME,
			PRIMARY KEY  (id),
			INDEX customer_id (customer_id),
			INDEX status (status),
			INDEX trashed_at (trashed_at),
			UNIQUE (tracking_id),
			INDEX created_at (created_at)
		) {$collate};";

		dbDelta( $sql );

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