<?php

namespace RtmBusiness\PostSync\Migrations;

use Exception;

class InitPostSyncMigration implements MigrationInterface
{

    /**
     * @inheritDoc
     */
    public function migrate(): void
    {
        global $wpdb;

        $sql = "CREATE TABLE IF NOT EXISTS {$wpdb->base_prefix}rtm_sync_data (
    	  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
    	  `sync_type` varchar(255) NOT NULL COMMENT 'The Sync Type',
		  `blog_id` int(11) NOT NULL COMMENT 'Blog ID',
		  `post_id` int(11) NOT NULL COMMENT 'Post ID',
		  `children` longtext NOT NULL COMMENT 'Children Data (Serialized)',
          `deletedOn` datetime DEFAULT NULL COMMENT 'Deleted On',
          PRIMARY KEY (`id`),
		  KEY `blog_id` (`blog_id`,`post_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);
        }
    }

    /**
     * @inheritDoc
     */
    public function rollback(): void
    {
        global $wpdb;
        $sql = "DROP TABLE {$wpdb->base_prefix}rtm_sync_data";
        $wpdb->query($sql);
    }

    /**
     * @inheritDoc
     */
    public function isMigrated(): bool
    {
        global $wpdb;
        return ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", "{$wpdb->base_prefix}rtm_sync_data")) === "{$wpdb->base_prefix}rtm_sync_data");
    }

    /**
     * @inheritDoc
     */
    public function getPriority(): int
    {
        return 1;
    }
}
