<?php

namespace SugarCalendarBookings\Support\Activities;

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

/**
 * Activities table.
 *
 * General-purpose activity table with support for:
 *  - Multiple object types (e.g., customer, service);
 *  - Multiple entries per object;
 *  - A type to categorize the entry (like note, log, etc.);
 *  - A user_id (who created the entry);
 *  - A content field (the actual note/log/entry).
 *
 * @since 1.0.0
 */
class ActivitiesTableMigration extends AbstractTableMigration {

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

	/**
	 * 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,
				type VARCHAR(30) NOT NULL,
				user_id BIGINT UNSIGNED DEFAULT 0,
				content TEXT,
				created_at DATETIME NOT NULL,
				PRIMARY KEY  (id),
				INDEX object_type_object_id_type (object_type, object_id, type)
		) {$collate};";

		dbDelta( $sql );

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