<?php
/**
 * Instalación y migración por CLI (XAMPP local).
 *
 * Uso: php install/setup-cli.php
 */

if ( PHP_SAPI !== 'cli' && ! defined( 'JB_SETUP_CLI' ) ) {
	die( 'CLI only' );
}

$root = dirname( __DIR__ );
define( 'JB_BOOTSTRAP', true );
define( 'ABSPATH', $root . '/' );
define( 'JB_APP_ROOT', $root . '/' );
define( 'JB_SRC_ROOT', $root . '/src/' );

require_once $root . '/core/App.php';
JB_App::load_config();

$config = JB_App::config();
$wp_db  = 'JORGEBORJA';
$wp_prefix = 'wp_';

echo "=== JB Planeación — Setup CLI ===\n";
echo "App DB: {$config['db']['name']} (prefix {$config['db']['prefix']})\n";
echo "WP DB:  {$wp_db} (prefix {$wp_prefix})\n\n";

require_once $root . '/core/HookSystem.php';
require_once $root . '/core/Database.php';
require_once $root . '/core/dbDelta.php';
require_once $root . '/core/Options.php';
require_once $root . '/core/Security.php';
require_once $root . '/core/Http.php';
require_once $root . '/core/Auth.php';
require_once $root . '/core/Assets.php';
require_once $root . '/core/Router.php';
require_once $root . '/core/wp-compat.php';
require_once $root . '/core/WP_Error.php';

/** @disregard P1009 Clase core cargada por require_once arriba. */
JB_Database::init( $config['db'] );
JB_Options::init( 'options' );
JB_Auth::init();

global $wpdb;

// 1. Tablas base de usuarios/opciones
echo "[1/4] Tablas base...\n";
JB_Auth::create_tables();

update_option( 'jb_pages', array(
	'jb-planeacion-backend' => array(
		'ID'           => 1,
		'post_title'   => 'JB Planeación — Operaciones',
		'post_content' => '',
		'post_status'  => 'publish',
		'post_type'    => 'page',
		'post_name'    => 'jb-planeacion-backend',
	),
) );
update_option( 'logistica_backend_page_id', 1 );

// 2. Tablas de negocio del plugin
echo "[2/4] Tablas de negocio...\n";
require_once JB_SRC_ROOT . 'bootstrap.php';
do_action( 'plugins_loaded' );

// 3. Migración desde WordPress
echo "[3/4] Migración WordPress -> standalone...\n";

$wp_pdo = new PDO(
	"mysql:host={$config['db']['host']};dbname={$wp_db};charset=utf8mb4",
	$config['db']['user'],
	$config['db']['password'],
	array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
);

$jb_prefix = $config['db']['prefix'];
$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;
	$check = $wp_pdo->query( "SHOW TABLES LIKE '{$from}'" )->fetch();
	if ( ! $check ) {
		echo "  skip {$from}\n";
		continue;
	}
	$count = $wp_pdo->query( "SELECT COUNT(*) FROM `{$from}`" )->fetchColumn();
	$wpdb->query( "DROP TABLE IF EXISTS `{$to}`" );
	$wpdb->query( "CREATE TABLE `{$to}` LIKE `{$wp_db}`.`{$from}`" );
	$wpdb->query( "INSERT INTO `{$to}` SELECT * FROM `{$wp_db}`.`{$from}`" );
	echo "  ok {$table} ({$count} filas)\n";
}

// Opciones logistica_*
$opts = $wp_pdo->query( "SELECT option_name, option_value FROM `{$wp_prefix}options` WHERE option_name LIKE 'logistica_%'" )->fetchAll( PDO::FETCH_ASSOC );
foreach ( $opts as $opt ) {
	update_option( $opt['option_name'], maybe_unserialize( $opt['option_value'] ) );
	echo "  ok option {$opt['option_name']}\n";
}

// Usuarios WP con meta logistica_*
$wp_users = $wp_pdo->query(
	"SELECT u.* FROM `{$wp_prefix}users` u
	INNER JOIN `{$wp_prefix}usermeta` m ON m.user_id = u.ID
	WHERE m.meta_key IN ('logistica_jb_role', 'wp_capabilities')
	GROUP BY u.ID"
)->fetchAll( PDO::FETCH_ASSOC );

$admin_created = false;

foreach ( $wp_users as $wu ) {
	$jb_role = $wp_pdo->prepare( "SELECT meta_value FROM `{$wp_prefix}usermeta` WHERE user_id = ? AND meta_key = 'logistica_jb_role'" );
	$jb_role->execute( array( $wu['ID'] ) );
	$role_val = $jb_role->fetchColumn();

	$is_wp_admin = $wp_pdo->prepare( "SELECT meta_value FROM `{$wp_prefix}usermeta` WHERE user_id = ? AND meta_key = '{$wp_prefix}capabilities'" );
	$is_wp_admin->execute( array( $wu['ID'] ) );
	$caps = maybe_unserialize( $is_wp_admin->fetchColumn() );
	$is_admin = is_array( $caps ) && ! empty( $caps['administrator'] );

	if ( ! $role_val && ! $is_admin ) {
		continue;
	}

	$exists = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM `{$jb_prefix}users` WHERE user_login = %s", $wu['user_login'] ) );
	if ( $exists ) {
		$new_id = (int) $exists;
	} else {
		$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;
	}

	if ( $is_admin ) {
		update_user_meta( $new_id, 'jb_is_admin', '1' );
		$admin_created = true;
	}
	if ( $role_val ) {
		update_user_meta( $new_id, 'logistica_jb_role', maybe_unserialize( $role_val ) ?: $role_val );
	}

	$metas = $wp_pdo->prepare( "SELECT meta_key, meta_value FROM `{$wp_prefix}usermeta` WHERE user_id = ? AND meta_key LIKE 'logistica_%'" );
	$metas->execute( array( $wu['ID'] ) );
	while ( $meta = $metas->fetch( PDO::FETCH_ASSOC ) ) {
		update_user_meta( $new_id, $meta['meta_key'], maybe_unserialize( $meta['meta_value'] ) );
	}

	echo "  ok usuario {$wu['user_login']} -> ID {$new_id}" . ( $is_admin ? ' [admin]' : '' ) . "\n";
}

if ( ! $admin_created ) {
	$admin_id = JB_Auth::create_user( 'admin', 'JbPlaneacion2026!', 'admin@latingraf.com', 'Administrador', true );
	update_user_meta( $admin_id, 'logistica_jb_role', 'jb_administrador' );
	echo "  ok usuario admin creado (contraseña: JbPlaneacion2026!)\n";
}

// 4. Finalizar
file_put_contents( $root . '/storage/.installed', date( 'c' ) );
file_put_contents( $root . '/storage/sessions/.gitkeep', '' );
file_put_contents( $root . '/storage/uploads/.gitkeep', '' );

echo "\n[4/4] Instalación completada.\n";
echo "URL: {$config['app_url']}/\n";
echo "Listo.\n";
