<?php

namespace Yuvayana\AcadlixImporter\Migrations;

defined('ABSPATH') || exit();

if (!class_exists('ImporterSyncMigration')) {
  class ImporterSyncMigration
  {
    private $_table_name = 'acadlix_importer_sync';

    private function get_table_name()
    {
      global $wpdb;

      return $wpdb->prefix . $this->_table_name;
    }

    public function up()
    {
      global $wpdb;
      $table_name = $this->get_table_name();

      $charset_collate = $wpdb->get_charset_collate();

      $sql = "CREATE TABLE {$table_name} (
                id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                old_id BIGINT(20) UNSIGNED NOT NULL,
                new_id BIGINT(20) UNSIGNED NOT NULL,
                type VARCHAR(191) DEFAULT 'quiz' NULL,
                meta_key VARCHAR(191) NULL,
                meta_value LONGTEXT NULL,
                `from` VARCHAR(191) DEFAULT 'wp-pro-quiz' NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
                PRIMARY KEY  (id),
                KEY {$table_name}_old_id_idx (old_id),
                KEY {$table_name}_new_id_idx (new_id),
                KEY {$table_name}_type_idx (type)
            ) $charset_collate;";

      require_once ABSPATH . 'wp-admin/includes/upgrade.php';
      // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
      $table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));

      if ($table_exists !== $table_name) {
        dbDelta($sql);
      }
    }

    public function down()
    {
      global $wpdb;
      $table_name = $wpdb->prefix . "acadlix_importer_sync";
      $safe_table = esc_sql($table_name);
      // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
      $wpdb->query($wpdb->prepare("DROP TABLE IF EXISTS `$safe_table`"));
    }

    public function update()
    {
      global $wpdb;
      $table_name = $this->get_table_name();

      // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
      $column_exists = $wpdb->get_var($wpdb->prepare("SHOW COLUMNS FROM `{$table_name}` LIKE %s", 'from'));

      if (!$column_exists) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange
        $wpdb->query("ALTER TABLE `{$table_name}` ADD COLUMN `from` VARCHAR(191) DEFAULT 'wp-pro-quiz' NULL AFTER `meta_value`");
      }
    }
  }
}