<?php
/**
 * Migración de datos desde instalación WordPress existente.
 *
 * Uso CLI:
 *   php install/migrate-from-wordpress.php --wp-prefix=wp_ --jb-prefix=jb_
 *
 * Requiere config.php ya configurado y acceso a la misma base MySQL
 * (o exportar/importar tablas latingraf_* y opciones logistica_*).
 */

if ( PHP_SAPI !== 'cli' ) {
	die( 'Ejecutar desde línea de comandos.' );
}

require_once dirname( __DIR__ ) . '/core/bootstrap.php';

$opts = getopt( '', array( 'wp-prefix:', 'jb-prefix:', 'dry-run' ) );
$wp_prefix = $opts['wp-prefix'] ?? 'wp_';
$dry_run   = isset( $opts['dry-run'] );

global $wpdb;
$jb_prefix = $wpdb->prefix;

echo "Migrando desde {$wp_prefix}* hacia {$jb_prefix}*\n";

$tables = array(
	'latingraf_productos', 'latingraf_materia_prima', 'latingraf_movimientos',
	'latingraf_conversiones', 'latingraf_empaques', 'latingraf_reportes',
	'latingraf_inventario_bodega', 'latingraf_inventario_ajustes',
	'latingraf_cierre_caracteristicas', 'latingraf_planeacion_impresion',
	'latingraf_planeacion_formado', 'latingraf_etiqueta_productos',
	'latingraf_etiqueta_pack_historial', 'latingraf_rotulo_rollos',
	'latingraf_pedidos_inventario', 'latingraf_pedidos_entregas',
	'latingraf_pedidos_ordenes_compra', 'latingraf_pedidos_ordenes_lineas',
	'latingraf_pedidos_orden_linea_entregas', 'latingraf_pedidos_clientes',
	'latingraf_minutas', 'latingraf_auditoria', 'latingraf_papelera', 'latingraf_versiones',
);

foreach ( $tables as $table ) {
	$from = $wp_prefix . $table;
	$to   = $jb_prefix . $table;
	$exists = $wpdb->get_var( "SHOW TABLES LIKE '{$from}'" );
	if ( ! $exists ) {
		echo "  [skip] {$from} no existe\n";
		continue;
	}
	if ( $dry_run ) {
		$count = $wpdb->get_var( "SELECT COUNT(*) FROM `{$from}`" );
		echo "  [dry-run] {$from} -> {$to} ({$count} filas)\n";
		continue;
	}
	$wpdb->query( "DROP TABLE IF EXISTS `{$to}`" );
	$wpdb->query( "CREATE TABLE `{$to}` LIKE `{$from}`" );
	$wpdb->query( "INSERT INTO `{$to}` SELECT * FROM `{$from}`" );
	echo "  [ok] {$table}\n";
}

// Opciones logistica_*
$options = $wpdb->get_results(
	$wpdb->prepare(
		"SELECT option_name, option_value, autoload FROM `{$wp_prefix}options` WHERE option_name LIKE %s",
		'logistica_%'
	)
);
foreach ( $options as $opt ) {
	if ( $dry_run ) {
		echo "  [dry-run] option {$opt->option_name}\n";
		continue;
	}
	update_option( $opt->option_name, maybe_unserialize( $opt->option_value ) );
	echo "  [ok] option {$opt->option_name}\n";
}

// Usuarios WP con rol JB
$wp_users = $wpdb->get_results(
	"SELECT u.* FROM `{$wp_prefix}users` u
	INNER JOIN `{$wp_prefix}usermeta` m ON m.user_id = u.ID AND m.meta_key = 'logistica_jb_role'"
);
foreach ( $wp_users as $wu ) {
	if ( $dry_run ) {
		echo "  [dry-run] usuario {$wu->user_login}\n";
		continue;
	}
	$exists = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM `{$jb_prefix}users` WHERE user_login = %s", $wu->user_login ) );
	if ( ! $exists ) {
		$wpdb->insert( "{$jb_prefix}users", array(
			'user_login'    => $wu->user_login,
			'user_pass'     => $wu->user_pass,
			'user_nicename' => $wu->user_nicename,
			'user_email'    => $wu->user_email,
			'display_name'  => $wu->display_name,
		) );
		$new_id = (int) $wpdb->insert_id;
	} else {
		$new_id = (int) $exists;
	}
	$metas = $wpdb->get_results( $wpdb->prepare(
		"SELECT meta_key, meta_value FROM `{$wp_prefix}usermeta` WHERE user_id = %d AND meta_key LIKE 'logistica_%'",
		$wu->ID
	) );
	foreach ( $metas as $meta ) {
		update_user_meta( $new_id, $meta->meta_key, maybe_unserialize( $meta->meta_value ) );
	}
	$panel_meta = $wpdb->get_var( $wpdb->prepare(
		"SELECT meta_value FROM `{$wp_prefix}usermeta` WHERE user_id = %d AND meta_key = 'logistica_user_panel_v1'",
		$wu->ID
	) );
	if ( $panel_meta ) {
		update_user_meta( $new_id, 'logistica_user_panel_v1', maybe_unserialize( $panel_meta ) );
	}
	echo "  [ok] usuario {$wu->user_login} -> ID {$new_id}\n";
}

echo "Migración finalizada.\n";
