<?php

namespace RtmMail\Migrations;

use Exception;
use RtmMail\Models\Entities\Log;

/**
 * FirstMigration - SQL migration for version 1.3.0
 * Methods explained in MigrationInterface.php
 */
class LoggerMigration implements MigrationInterface {
	/**
	 * PRIORITY - priority is needed to handle sorting of the different migrations
	 * It goes from low to high (so 1 = first, after that goes priority 2 etc.)
	 */
	const PRIORITY = 3;

	public function migrate() {
		global $wpdb;
		// Creation of the database table "logs"

		$sql = "CREATE TABLE IF NOT EXISTS " . Log::getTable() . " (
                id int(11) NOT NULL AUTO_INCREMENT,
                title varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                message text COLLATE utf8mb4_unicode_ci NOT NULL,
                severity enum('error','info','warning','debug') COLLATE utf8mb4_unicode_ci NOT NULL,
                source varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                category varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
                data longtext COLLATE utf8mb4_unicode_ci NOT NULL,
                metadata longtext CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL,
                timestamp datetime NOT NULL,
                 PRIMARY KEY (id)
            )" . $wpdb->get_charset_collate() . ";";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		dbDelta( $sql );

		if ( ! empty( $wpdb->last_error ) ) {
			throw new Exception( $wpdb->last_error );
		}
	}

	public function rollback() {
		global $wpdb;
		$sql = "DROP TABLE " . Log::getTable() . ";";
		$wpdb->query( $sql );
	}

	public function is_migrated() {
		global $wpdb;

		return ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", Log::getTable() ) ) === Log::getTable() );
	}

	public function get_priority() {
		return self::PRIORITY;
	}
}
