<?php

namespace Meliconnect\Meliconnect\Core;

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Class DatabaseManager
 *
 * @package Meliconnect\Meliconnect
 */
class DatabaseManager
{

    private $prefix;
    private $charset_collate;

    public $tables_names = array();

    public function __construct()
    {
        global $wpdb;
        $this->prefix          = $wpdb->prefix . 'meliconnect_';
        $this->charset_collate = $wpdb->get_charset_collate();
    }

    public function create_or_update_tables()
    {
        $this->create_or_update_notification();
        $this->create_or_update_user_connection();
        $this->create_or_update_template();

        // Always after create_or_update_template
        $this->create_or_update_template_meta();
        $this->create_or_update_template_attributes();
        $this->create_or_update_process();
        $this->create_or_update_process_item();
        $this->create_or_update_user_listings_to_import();
        $this->create_or_update_products_to_export();

        $this->create_or_update_sync_state();
        $this->create_or_update_sync_logs();
        $this->create_or_update_settings_snapshots();
    }

    public function create_or_update_sync_state()
    {
        global $wpdb;

        $table_name = $this->prefix . 'sync_state';

        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `woo_product_id` BIGINT(20) UNSIGNED NOT NULL,
            `woo_variation_id` BIGINT(20) UNSIGNED DEFAULT NULL,
            `meli_item_id` VARCHAR(50) NOT NULL,
            `meli_variation_id` VARCHAR(50) DEFAULT NULL,
            `meli_seller_id` VARCHAR(50) NOT NULL,
            `direction` ENUM('woo_to_meli','meli_to_woo') DEFAULT NULL,
            `sync_type` ENUM('stock','price','status','full') DEFAULT 'full',
            `changes` LONGTEXT DEFAULT NULL,
            `sync_status` ENUM('synced','pending','processing','error') NOT NULL DEFAULT 'pending',
            `last_synced_stock` INT(11) DEFAULT NULL,
            `last_synced_price` DECIMAL(12,2) DEFAULT NULL,
            `last_synced_status` VARCHAR(50) DEFAULT NULL,
            `last_seen_meli_hash` VARCHAR(64) DEFAULT NULL,
            `last_seen_woo_hash` VARCHAR(64) DEFAULT NULL,
            `last_hash` VARCHAR(64) DEFAULT NULL,
            `source` ENUM('woo','meli','reconciler') DEFAULT NULL,
            `needs_sync` TINYINT(1) NOT NULL DEFAULT 0,
            `priority` INT(11) DEFAULT 0,
            `last_error` TEXT DEFAULT NULL,
            `retry_count` INT(11) DEFAULT 0,
            `last_attempt_at` TIMESTAMP NULL DEFAULT NULL,
            `locked_at` TIMESTAMP NULL DEFAULT NULL,
            `lock_token` VARCHAR(64) DEFAULT NULL,
            `initialized_at` TIMESTAMP NULL DEFAULT NULL,
            `last_sync_at` TIMESTAMP NULL DEFAULT NULL,
            `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            `deleted_at` TIMESTAMP NULL DEFAULT NULL,
            PRIMARY KEY (`id`)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);

        //Add Indexes
        $this->add_index_if_not_exists(
            $table_name,
            'idx_pending_dedupe',
            '(`meli_item_id`, `sync_type`, `needs_sync`)'
        );

        $this->add_index_if_not_exists(
            $table_name,
            'sync_queue',
            '(`needs_sync`, `sync_status`, `locked_at`, `priority`, `updated_at`)'
        );

        $this->add_index_if_not_exists(
            $table_name,
            'idx_meli_item',
            '(`meli_item_id`)'
        );
    }

    private function add_index_if_not_exists($table, $index_name, $definition)
    {
        global $wpdb;

        $indexes = $wpdb->get_results("SHOW INDEX FROM {$table}", ARRAY_A);
        $names = array_column($indexes, 'Key_name');

        if (!in_array($index_name, $names)) {
            $wpdb->query("ALTER TABLE {$table} ADD INDEX `{$index_name}` {$definition}");
        }
    }

    public function create_or_update_sync_logs()
    {
        global $wpdb;

        $table_name = $this->prefix . 'sync_logs';
        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `sync_state_id` BIGINT(20) UNSIGNED NULL,
            `woo_product_id` BIGINT(20) UNSIGNED NULL,
            `meli_item_id` VARCHAR(50) NULL,
            `action` VARCHAR(50) NOT NULL,
            `source` VARCHAR(20) NOT NULL,
            `field` VARCHAR(50) NULL,
            `old_value` LONGTEXT NULL,
            `new_value` LONGTEXT NULL,
            `direction` VARCHAR(30) NULL,
            `trigger_type` VARCHAR(20) DEFAULT 'system',
            `status` VARCHAR(20) NOT NULL DEFAULT 'success',
            `message` TEXT NULL,
            `settings_snapshot_id` BIGINT(20) UNSIGNED NULL,
            `plugin_version` VARCHAR(20) NULL,
            `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (`id`),
            KEY `idx_meli_item` (`meli_item_id`),
            KEY `idx_woo_product` (`woo_product_id`),
            KEY `idx_created_at` (`created_at`),
            KEY `idx_action` (`action`),
            KEY `idx_status` (`status`),
            KEY `idx_snapshot` (`settings_snapshot_id`),
            KEY `idx_state` (`sync_state_id`)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);


    }

    public function create_or_update_settings_snapshots()
    {
        global $wpdb;

        $table_name = $this->prefix . 'settings_snapshots';
        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `module` VARCHAR(40) NOT NULL,
            `hash` VARCHAR(64) NOT NULL,
            `description` VARCHAR(255) NULL,
            `settings` LONGTEXT NOT NULL,
            `is_active` TINYINT(1) DEFAULT 0,
            `user_id` BIGINT(20) UNSIGNED NULL,
            `plugin_version` VARCHAR(20) NULL,
            `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY  (id),
            UNIQUE KEY unique_module_hash (module, hash)
        ) {$this->charset_collate};";

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

        dbDelta($sql);

        $this->add_index_if_not_exists(
            $table_name,
            'idx_module',
            '(`module`)'
        );

        $this->add_index_if_not_exists(
            $table_name,
            'idx_module_active',
            '(`module`, `is_active`)'
        );

        $this->add_index_if_not_exists(
            $table_name,
            'idx_created_at',
            '(`created_at`)'
        );
    }

    public function create_or_update_notification()
    {
        $table_name = $this->prefix . 'notifications';

        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` mediumint(9) UNSIGNED NOT NULL AUTO_INCREMENT,
            `unique_id` varchar(250) NOT NULL,
			`title_html` varchar(250) DEFAULT NULL,
			`text_html` text DEFAULT NULL,
			`icon_html` text DEFAULT NULL,
			`bt1_text` varchar(250) DEFAULT NULL,
			`bt1_link` varchar(250) DEFAULT NULL,
			`bt2_text` varchar(250) DEFAULT NULL,
			`bt2_link` varchar(250) DEFAULT NULL,
			`from_version` varchar(50) DEFAULT NULL,
            `to_version` varchar(50) DEFAULT NULL,
            `type` varchar(100) DEFAULT NULL,
            `priority` int(11) DEFAULT 0,
            `meta` LONGTEXT DEFAULT NULL,
			`date_from` timestamp NOT NULL DEFAULT current_timestamp(),
			`status` enum('show','test','hide') NOT NULL DEFAULT 'hide',
			`is_dismissed` tinyint(1) NOT NULL DEFAULT 0,
			`is_made` tinyint(1) NOT NULL DEFAULT 0,
			`created_at` timestamp NULL DEFAULT current_timestamp(),
			`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
            PRIMARY KEY  (id)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    public function create_or_update_user_connection()
    {
        $table_name = $this->prefix . 'user_connection';

        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` mediumint(9) NOT NULL AUTO_INCREMENT,
            `access_token` varchar(255) NOT NULL,
            `app_id` varchar(255) NOT NULL,
            `secret_key` varchar(255) NOT NULL,
            `user_id` bigint(20) NOT NULL,
            `nickname` varchar(255) NOT NULL,
            `permalink` varchar(255) NOT NULL,
            `site_id` varchar(255) NOT NULL,
            `country` varchar(255) NOT NULL,
            `has_mercadoshops` boolean NOT NULL DEFAULT false,
            `status` varchar(50) NOT NULL,
            `meli_user_data` text DEFAULT NULL,
            `api_token` text DEFAULT NULL,
            `plan_type` enum('free','pro','power') NOT NULL DEFAULT 'free',
            `active_connections` int(11) NOT NULL DEFAULT 0,
            `pending_connections` int(11) NOT NULL DEFAULT 0,
            `connected_listing_ids` LONGTEXT DEFAULT NULL,
            `created_at` timestamp NULL DEFAULT current_timestamp(),
			`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
            PRIMARY KEY  (id),
            UNIQUE KEY user_id (user_id)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }


    public function create_or_update_template()
    {
        $table_name = $this->prefix . 'templates';

        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` mediumint(9) UNSIGNED NOT NULL AUTO_INCREMENT,
            `used_by` enum('product','template') NOT NULL DEFAULT 'template',
			`used_asoc_id` varchar(100) DEFAULT NULL,
			`template_parent_id` varchar(200) DEFAULT NULL,
			`seller_meli_id` varchar(100) NOT NULL,
			`name` varchar(200) NOT NULL,
			`short_description` varchar(200) DEFAULT NULL,
			`category_id` varchar(80) NOT NULL,
            `category_name` varchar(80) DEFAULT NULL,
            `category_path` text DEFAULT NULL,
			`channels` enum('mercadolibre','mercadoshop','all') NOT NULL DEFAULT 'mercadolibre',
			`status` tinyint(1) NOT NULL DEFAULT 1,
			`created_at` timestamp NULL DEFAULT current_timestamp(),
			`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
            PRIMARY KEY  (id),
			UNIQUE KEY `unique_template_by_used_asoc` (`used_asoc_id`,`used_by`)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    public function create_or_update_template_meta()
    {
        $table_name           = $this->prefix . 'template_metas';
        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `meta_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `template_id` MEDIUMINT(9) UNSIGNED NOT NULL,
            `meta_key` VARCHAR(255) DEFAULT NULL,
            `meta_value` LONGTEXT DEFAULT NULL,
            `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (meta_id),
            KEY template_id (template_id)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    public function create_or_update_template_attributes()
    {
        $table_name           = $this->prefix . 'template_attributes';
        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `template_id` varchar(200) DEFAULT NULL,
            `used_by` enum('product','template','variation') NOT NULL DEFAULT 'template',
			`used_asoc_id` int(11) DEFAULT NULL,
            `meli_variation_id` varchar(100) DEFAULT NULL,
			`meli_attribute_id` varchar(100) DEFAULT NULL,
            `meli_attribute_name` varchar(250) DEFAULT NULL,
            `meli_value_id` varchar(250) DEFAULT NULL,
            `meli_value_name` varchar(250) DEFAULT NULL,
            `meli_value_type` varchar(250) DEFAULT NULL,
            `product_parent_id` int(11) DEFAULT NULL,
            `woo_attribute_id` int(20) DEFAULT NULL,
            `allow_variations_tag` tinyint(1) NOT NULL DEFAULT 0, /* Attribute used in variation combination */
            `variation_attribute_tag` tinyint(1) NOT NULL DEFAULT 0, /* Attribute used as variation attribute */
            `required_tag` tinyint(1) NOT NULL DEFAULT 0,
            `not_apply` tinyint(1) NOT NULL DEFAULT 0, 
			`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
			`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
            PRIMARY KEY  (id)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    public function create_or_update_process()
    {
        $table_name           = $this->prefix . 'processes';
        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `process_id` varchar(150) NOT NULL,
            `status` enum('pending','processing','paused','finished','failed') NOT NULL DEFAULT 'pending',
            `executed` int(11) DEFAULT 0,
            `total` int(11) NOT NULL DEFAULT 0,
            `process_type` varchar(50) NOT NULL,
            `total_success` int(11) NOT NULL DEFAULT 0,
            `total_fails` int(11) NOT NULL DEFAULT 0,
            `error_log` text DEFAULT NULL,
            `starts_at` timestamp NULL DEFAULT NULL,
            `ends_at` timestamp NULL DEFAULT NULL,
            `created_at` timestamp NULL DEFAULT current_timestamp(),
			`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
            PRIMARY KEY  (id),
            UNIQUE KEY `unique_process_id` (`process_id`)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    public function create_or_update_process_item()
    {
        $table_name           = $this->prefix . 'process_items';
        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `process_id` varchar(200) NOT NULL,
            `meli_user_id` varchar(100) NULL,
            `meli_listing_id` varchar(100) NULL,
            `woo_product_id` varchar(100) NULL,
            `template_id` varchar(100) NULL,
            `process_status` enum('pending','processed','failed') NOT NULL DEFAULT 'pending',
            `process_error` text DEFAULT NULL,
            `created_at` timestamp NULL DEFAULT current_timestamp(),
			`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
            PRIMARY KEY  (id),
            KEY process_id (process_id)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }


    public function create_or_update_user_listings_to_import()
    {
        $table_name           = $this->prefix . 'user_listings_to_import';
        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `meli_listing_id` VARCHAR(50) NOT NULL,
            `meli_user_id` VARCHAR(50) NOT NULL,
            `meli_listing_title` VARCHAR(200) NOT NULL,
            `meli_response` LONGTEXT DEFAULT NULL,
            `meli_sku` VARCHAR(50) DEFAULT NULL,
            `meli_gtin` VARCHAR(50) DEFAULT NULL,
            `meli_status` VARCHAR(50) NOT NULL,
            `meli_sub_status` VARCHAR(50) NOT NULL,
            `meli_product_type` enum('variable','simple') DEFAULT NULL,
            `meli_family_id` VARCHAR(50) DEFAULT NULL,
            `meli_family_name` VARCHAR(200) DEFAULT NULL,
            `meli_family_is_parent` tinyint(1) DEFAULT 0,
            `meli_parent_listing_id` VARCHAR(50) DEFAULT NULL,
            `meli_user_product_id` VARCHAR(50) DEFAULT NULL,
            `meli_seller_custom_field` VARCHAR(50) DEFAULT NULL,
            `vinculated_product_id` BIGINT(20) UNSIGNED DEFAULT NULL,
            `is_product_match_by_sku` tinyint(1) DEFAULT 0,
            `is_product_match_by_gtin` tinyint(1) DEFAULT 0,
            `is_product_match_by_name` tinyint(1) DEFAULT 0,
            `is_product_match_manually` tinyint(1) DEFAULT 0,
            `vinculated_template_id` BIGINT(20) UNSIGNED DEFAULT NULL,
            `import_status` enum('pending','processing','canceled','finished','failed') DEFAULT NULL,
            `import_error` text DEFAULT NULL,
            `process_id` varchar(200) NOT NULL,
            `created_at` timestamp NULL DEFAULT current_timestamp(),
            `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
            PRIMARY KEY (id),
            KEY process_id (process_id),
            UNIQUE KEY meli_listing_id (meli_listing_id)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }


    public function create_or_update_products_to_export()
    {
        $table_name           = $this->prefix . 'products_to_export';
        $this->tables_names[] = $table_name;

        $sql = "CREATE TABLE {$table_name} (
            `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            `woo_product_id` BIGINT(20) UNSIGNED NOT NULL,
            `woo_product_name` VARCHAR(255) NOT NULL, 
            `woo_sku` VARCHAR(50) NOT NULL,
            `woo_gtin` VARCHAR(50) NOT NULL,
            `woo_product_type` ENUM('variable','simple') DEFAULT NULL,
            `woo_status` VARCHAR(50) NOT NULL,
            `vinculated_template_id` BIGINT(20) UNSIGNED DEFAULT NULL,
            `vinculated_listing_id` VARCHAR(100) DEFAULT NULL,
            `template_match_by` VARCHAR(50) DEFAULT NULL,
            `listing_match_by` VARCHAR(50) DEFAULT NULL,
            `meli_seller_id` VARCHAR(255) DEFAULT NULL,
            `meli_permalink` VARCHAR(255) DEFAULT NULL,
            `export_status` ENUM('pending','processing','canceled','finished','failed') DEFAULT NULL,
            `export_error` TEXT DEFAULT NULL,
            `process_id` VARCHAR(100) NOT NULL,
            `created_at` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `process_id` (`process_id`),
            UNIQUE KEY `woo_product_id` (`woo_product_id`)
        ) {$this->charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }


    public static function meliconnect_update_tables()
    {
        $current_version = get_option('meliconnect_db_version', '1.0');

        if (version_compare($current_version, MELICONNECT_DATABASE_VERSION, '>=')) {
            return;
        }

        // Solo ejecutar si la versión del plugin es mayor que la versión guardada
        $db = new self();

        $tables = array(
            'user_connection'         => array(
                'add' => array(
                    'plan_type'             => "enum('free','pro','power') NOT NULL DEFAULT 'free'",
                    'active_connections'    => 'int(11) NOT NULL DEFAULT 0',
                    'pending_connections'   => 'int(11) NOT NULL DEFAULT 0',
                    'connected_listing_ids' => 'LONGTEXT DEFAULT NULL',
                ),
            ),

            'notifications'           => array(
                'add'    => array(
                    'to_version' => 'varchar(50) DEFAULT NULL',
                    'type'       => 'varchar(100) DEFAULT NULL',
                    'priority'   => 'int(11) DEFAULT 0',
                    'meta'       => 'LONGTEXT DEFAULT NULL',
                ),
                'update' => array(
                    'from_version' => 'varchar(50) DEFAULT NULL',
                ),
            ),

            'user_listings_to_import' => array(
                'add' => array(
                    'meli_family_id'           => 'varchar(50) DEFAULT NULL',
                    'meli_family_name'         => 'varchar(200) DEFAULT NULL',
                    'meli_user_product_id'     => 'varchar(50) DEFAULT NULL',
                    'meli_seller_custom_field' => 'varchar(50) DEFAULT NULL',
                    'meli_family_is_parent'    => 'tinyint(1) DEFAULT 0',
                    'meli_parent_listing_id'   => 'varchar(50) DEFAULT NULL',
                ),
                'update' => array(
                    'meli_sub_status' => 'TEXT DEFAULT NULL',
                ),
            ),
        );

        foreach ($tables as $table_key => $changes) {
            $table_name = $db->prefix . $table_key;

            if (! empty($changes['add'])) {
                self::add_columns($table_name, $changes['add']);
            }

            if (! empty($changes['remove'])) {
                self::remove_columns($table_name, $changes['remove']);
            }

            if (! empty($changes['update'])) {
                self::update_columns($table_name, $changes['update']);
            }
        }

        self::migrate_process_type_to_varchar();

        // Actualizamos la versión guardada
        update_option('meliconnect_db_version', MELICONNECT_DATABASE_VERSION);
    }

    public static function migrate_process_type_to_varchar()
    {
        global $wpdb;

        $table_name           = $wpdb->prefix . 'meliconnect_processes';

        $column = $wpdb->get_row("SHOW COLUMNS FROM {$table_name} LIKE 'process_type'");

        if (! $column) {
            return;
        }

        // Si ya es varchar, no hacer nada
        if (stripos($column->Type, 'varchar') !== false) {
            return;
        }

        // Migrar ENUM -> VARCHAR
        $wpdb->query("
            ALTER TABLE {$table_name}
            MODIFY process_type VARCHAR(50) NOT NULL
        ");
    }



    /**
     * Agrega columnas a la tabla si no existen
     */
    protected static function add_columns($table_name, $columns)
    {
        global $wpdb;
        $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name}", ARRAY_A);
        $existing_columns = wp_list_pluck($existing_columns, 'Field');

        foreach ($columns as $column => $definition) {
            if (! in_array($column, $existing_columns)) {
                $wpdb->query("ALTER TABLE {$table_name} ADD COLUMN {$column} {$definition}");
            }
        }
    }

    /**
     * Elimina columnas de la tabla si existen
     */
    protected static function remove_columns($table_name, $columns)
    {
        global $wpdb;
        $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name}", ARRAY_A);
        $existing_columns = wp_list_pluck($existing_columns, 'Field');

        foreach ($columns as $column) {
            if (in_array($column, $existing_columns)) {
                $wpdb->query("ALTER TABLE {$table_name} DROP COLUMN {$column}");
            }
        }
    }

    /**
     * Actualiza columnas existentes (tipo, default, etc)
     */
    protected static function update_columns($table_name, $columns)
    {
        global $wpdb;
        $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM {$table_name}", ARRAY_A);
        $existing_columns = wp_list_pluck($existing_columns, 'Field');

        foreach ($columns as $column => $definition) {
            if (in_array($column, $existing_columns)) {
                $wpdb->query("ALTER TABLE {$table_name} MODIFY COLUMN {$column} {$definition}");
            }
        }
    }
}
