<?php

namespace RtmMail\Migrations;

use Exception;

/**
 * QueueMigration - Adds 'queued' to one of the enum values in status
 * Methods explained in MigrationInterface.php
 */
class QueueMigration 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
                CHANGE status status ENUM('failed','sent','caught','queued') NOT NULL DEFAULT 'caught'";

        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
                CHANGE status status ENUM('failed','sent','caught') NOT NULL DEFAULT 'caught'";

        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 SUBSTRING(COLUMN_TYPE, 5) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" . RTM_MAIL_TABLE_PREFIX . "logs' AND column_name = 'status' AND table_schema = '" . $wpdb->dbname . "'");
        // Convert stdObject to array
        $result = json_decode(json_encode($row), true);
        return strpos($result[0]["SUBSTRING(COLUMN_TYPE, 5)"], 'queued') !== false;
    }

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