<?php
/**
 * Instalador de JB Planeación (standalone).
 */

$step = (int) ( $_GET['step'] ?? 1 );
$error = '';
$success = '';

if ( 'POST' === ( $_SERVER['REQUEST_METHOD'] ?? '' ) && 2 === $step ) {
	require_once dirname( __DIR__ ) . '/core/WP_Error.php';
	require_once dirname( __DIR__ ) . '/core/App.php';
	require_once dirname( __DIR__ ) . '/core/HookSystem.php';
	require_once dirname( __DIR__ ) . '/core/Database.php';
	require_once dirname( __DIR__ ) . '/core/dbDelta.php';
	require_once dirname( __DIR__ ) . '/core/Options.php';
	require_once dirname( __DIR__ ) . '/core/Security.php';
	require_once dirname( __DIR__ ) . '/core/Http.php';
	require_once dirname( __DIR__ ) . '/core/Password.php';
	require_once dirname( __DIR__ ) . '/core/Auth.php';
	require_once dirname( __DIR__ ) . '/core/wp-compat.php';

	try {
		$db_name = trim( (string) ( $_POST['db_name'] ?? 'jb_planeacion' ) );
		$db_user = trim( (string) ( $_POST['db_user'] ?? 'root' ) );
		$db_pass = (string) ( $_POST['db_pass'] ?? '' );
		$db_host = trim( (string) ( $_POST['db_host'] ?? '127.0.0.1' ) );
		$db_prefix = preg_replace( '/[^a-z0-9_]/', '', (string) ( $_POST['db_prefix'] ?? 'jb_' ) );
		$app_url = rtrim( (string) ( $_POST['app_url'] ?? '' ), '/' );
		$admin_user = trim( (string) ( $_POST['admin_user'] ?? 'admin' ) );
		$admin_pass = (string) ( $_POST['admin_pass'] ?? '' );
		$admin_email = trim( (string) ( $_POST['admin_email'] ?? 'admin@localhost' ) );

		$pdo = new PDO(
			"mysql:host={$db_host};charset=utf8mb4",
			$db_user,
			$db_pass,
			array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )
		);
		$pdo->exec( "CREATE DATABASE IF NOT EXISTS `{$db_name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" );

		$config = array(
			'app_name'     => 'JB Planeación',
			'app_url'      => $app_url,
			'app_url_auto' => true,
			'app_env'  => 'production',
			'app_key'  => bin2hex( random_bytes( 32 ) ),
			'db'       => array(
				'host'     => $db_host,
				'port'     => 3306,
				'name'     => $db_name,
				'user'     => $db_user,
				'password' => $db_pass,
				'prefix'   => $db_prefix,
				'charset'  => 'utf8mb4',
			),
			'session'  => array(
				'lifetime' => 86400 * 14,
				'name'     => 'jb_planeacion_session',
			),
			'timezone' => 'America/Bogota',
		);

		$config_php = "<?php\nreturn " . var_export( $config, true ) . ";\n";
		file_put_contents( dirname( __DIR__ ) . '/config/config.php', $config_php );

		if ( ! defined( 'ABSPATH' ) ) {
			define( 'ABSPATH', dirname( __DIR__ ) . '/' );
		}
		if ( ! defined( 'JB_APP_ROOT' ) ) {
			define( 'JB_APP_ROOT', dirname( __DIR__ ) . '/' );
		}
		if ( ! defined( 'JB_SRC_ROOT' ) ) {
			define( 'JB_SRC_ROOT', JB_APP_ROOT . 'src/' );
		}

		JB_App::load_config();
		JB_Database::init( $config['db'] );
		JB_Options::init( 'options' );
		JB_Auth::init();
		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',
			),
			'latingraf-inventarios' => array(
				'ID'           => 2,
				'post_title'   => 'Planeación, Logística y Almacén',
				'post_content' => '[logistica_panel]',
				'post_status'  => 'publish',
				'post_type'    => 'page',
				'post_name'    => 'latingraf-inventarios',
			),
		) );
		update_option( 'logistica_backend_page_id', 1 );
		update_option( 'logistica_frontend_page_id', 2 );

		if ( ! defined( 'JB_BOOTSTRAP' ) ) {
			define( 'JB_BOOTSTRAP', true );
		}
		require_once JB_SRC_ROOT . 'bootstrap.php';
		do_action( 'plugins_loaded' );

		$admin_id = JB_Auth::create_user( $admin_user, $admin_pass, $admin_email, 'Administrador', true );
		update_user_meta( $admin_id, 'logistica_jb_role', 'jb_administrador' );

		file_put_contents( dirname( __DIR__ ) . '/storage/.installed', date( 'c' ) );
		$success = 'Instalación completada. <a href="' . htmlspecialchars( $app_url . '/' ) . '">Ir al panel</a>';
		$step = 3;
	} catch ( Throwable $e ) {
		$error = $e->getMessage();
	}
}

$default_url = ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http' )
	. '://' . ( $_SERVER['HTTP_HOST'] ?? 'localhost' );

$script_dir = rtrim( str_replace( '\\', '/', dirname( $_SERVER['SCRIPT_NAME'] ?? '' ) ), '/' );
if ( str_ends_with( $script_dir, '/install' ) ) {
	$script_dir = substr( $script_dir, 0, -strlen( '/install' ) ) . '/public';
} elseif ( ! str_ends_with( $script_dir, '/public' ) ) {
	$script_dir .= '/public';
}
$default_url .= $script_dir;

?><!DOCTYPE html>
<html lang="es">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Instalar JB Planeación</title>
	<link rel="icon" href="favicon.svg" type="image/svg+xml">
	<style>
		body { font-family: system-ui, sans-serif; max-width: 520px; margin: 2rem auto; padding: 0 1rem; }
		label { display: block; margin-top: 1rem; font-weight: 600; }
		input { width: 100%; padding: 0.5rem; margin-top: 0.25rem; box-sizing: border-box; }
		button { margin-top: 1.5rem; padding: 0.6rem 1.2rem; background: #1e3a5f; color: #fff; border: 0; cursor: pointer; }
		.error { color: #b00020; background: #fde8e8; padding: 0.75rem; border-radius: 4px; }
		.success { color: #0d5c2e; background: #e8f5e9; padding: 0.75rem; border-radius: 4px; }
	</style>
</head>
<body>
	<h1>Instalar JB Planeación</h1>
	<?php if ( $error ) : ?><p class="error"><?php echo htmlspecialchars( $error ); ?></p><?php endif; ?>
	<?php if ( $success ) : ?><p class="success"><?php echo $success; ?></p><?php endif; ?>

	<?php if ( 3 !== $step ) : ?>
	<form method="post" action="?step=2">
		<label>URL de la aplicación</label>
		<input type="url" name="app_url" value="<?php echo htmlspecialchars( $default_url ); ?>" required>

		<label>Host MySQL</label>
		<input type="text" name="db_host" value="127.0.0.1" required>

		<label>Base de datos</label>
		<input type="text" name="db_name" value="jb_planeacion" required>

		<label>Usuario MySQL</label>
		<input type="text" name="db_user" value="root" required>

		<label>Contraseña MySQL</label>
		<input type="password" name="db_pass">

		<label>Prefijo de tablas</label>
		<input type="text" name="db_prefix" value="jb_" required>

		<hr>
		<label>Usuario administrador</label>
		<input type="text" name="admin_user" value="admin" required>

		<label>Contraseña administrador</label>
		<input type="password" name="admin_pass" required minlength="8">

		<label>Email administrador</label>
		<input type="email" name="admin_email" value="admin@latingraf.com" required>

		<button type="submit">Instalar</button>
	</form>
	<?php endif; ?>
</body>
</html>
