<?php
/**
 * Migraciones de esquema (reemplaza dbDelta de WordPress).
 */

function dbDelta( $queries = '', $execute = true ) {
	global $wpdb;

	if ( is_string( $queries ) ) {
		$queries = array( $queries );
	}

	foreach ( $queries as $query ) {
		$query = trim( $query );
		if ( empty( $query ) ) {
			continue;
		}

		$table_name = '';
		if ( preg_match( '/CREATE TABLE\s+`?([^\s`(]+)`?/i', $query, $m ) ) {
			$table_name = $m[1];
		}

		$exists = $wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'" );
		if ( ! $exists ) {
			$wpdb->query( $query );
			continue;
		}

		// Tabla existe: agregar columnas faltantes.
		$columns = $wpdb->get_results( "SHOW COLUMNS FROM `{$table_name}`" );
		$existing_cols = array();
		foreach ( $columns as $col ) {
			$existing_cols[ $col->Field ] = true;
		}

		if ( preg_match_all( '/^\s*([`"]?)(\w+)\1\s+([^,]+)/m', $query, $col_matches, PREG_SET_ORDER ) ) {
			foreach ( $col_matches as $match ) {
				$col_name = $match[2];
				if ( in_array( strtolower( $col_name ), array( 'primary', 'key', 'unique', 'constraint' ), true ) ) {
					continue;
				}
				if ( ! isset( $existing_cols[ $col_name ] ) ) {
					$col_def = trim( $match[3] );
					$wpdb->query( "ALTER TABLE `{$table_name}` ADD COLUMN `{$col_name}` {$col_def}" );
				}
			}
		}
	}
}
