<?php

namespace RtmMail\Migrations;

use Exception;

/**
 * BacktraceMigration - Adds "backtrace" column to the logs table
 * Methods explained in MigrationInterface.php
 */
class BacktraceMigration 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 = 2;

	public function migrate() {
		global $wpdb;

		// Adds the "headers" column to the logs table
		$sql = "ALTER TABLE " . RTM_MAIL_TABLE_PREFIX . "logs
                ADD backtrace TEXT NULL AFTER attachments";

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

		$result = $wpdb->query( $sql );
		if ( ! $result ) {
			throw new Exception( $wpdb->last_error );
		}
	}

	public function rollback() {
		$sql = "ALTER TABLE " . RTM_MAIL_TABLE_PREFIX . "logs DROP COLUMN backtrace;";

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

		dbDelta( $sql );
	}

	public function is_migrated() {
		global $wpdb;
		// Check if column in logs table exists
		$row = $wpdb->get_results( "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" . RTM_MAIL_TABLE_PREFIX . "logs' AND column_name = 'backtrace' AND table_schema = '" . $wpdb->dbname . "'" );

		return ! empty( $row );
	}

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