#!/usr/bin/env bash
set -euo pipefail

# --- CONFIG: EDIT THESE ---
OLD_ID=3883
NEW_LOGIN="ashto_new"
NEW_EMAIL="info@ashtotrading.com"
NEW_PASS="NewStrongPass!42"
# --------------------------

echo "==> Backing up database…"
wp db export "pre-delete-user-${OLD_ID}-$(date +%F-%H%M).sql"

echo "==> Reading old email…"
OLD_EMAIL="$(wp user get "$OLD_ID" --field=user_email)"
PLACEHOLDER_EMAIL="${OLD_EMAIL/@/+old@}"

echo "==> Freeing target email from old user ($OLD_ID)…"
wp user update "$OLD_ID" --user_email="$PLACEHOLDER_EMAIL"

echo "==> Creating new user $NEW_LOGIN <$NEW_EMAIL>…"
if wp user get "$NEW_LOGIN" >/dev/null 2>&1; then
  NEW_ID="$(wp user get "$NEW_LOGIN" --field=ID)"
else
  NEW_ID="$(wp user create "$NEW_LOGIN" "$NEW_EMAIL" --role=customer --user_pass="$NEW_PASS" --porcelain)"
fi
echo "    New user ID: $NEW_ID"

echo "==> Ensuring roles on the new user…"
wp user set-role "$NEW_ID" customer
wp user add-role "$NEW_ID" subscriber || true

echo "==> Copying customer profile/meta (skipping sessions/lockouts/etc.)…"
OLD_ID="$OLD_ID" NEW_ID="$NEW_ID" wp eval '
$old = (int) getenv("OLD_ID");
$new = (int) getenv("NEW_ID");
$meta = get_user_meta($old);
$skipped = 0; $copied = 0;
foreach ($meta as $k => $vals) {
  // Skip capabilities/level (prefix-aware), sessions, lockouts, 2FA, captcha, transients, plugin-specific auth flags
  if (preg_match("/(_capabilities|_user_level)$/", $k)) { $skipped++; continue; }
  if (preg_match("/(session|lockout|2fa|captcha|wfls|nextcart|wholesale_approval|wholesale_status|require_password|_transient|_session)/i", $k)) { $skipped++; continue; }
  foreach ($vals as $v) { update_user_meta($new, $k, $v); $copied++; }
}
echo "Copied $copied meta values; skipped $skipped.\n";
'

echo "==> Reassigning WooCommerce orders to the new user…"
OLD_ID="$OLD_ID" NEW_ID="$NEW_ID" wp eval '
if (!function_exists("wc_get_orders")) { echo "WooCommerce not active; skipping orders.\n"; return; }
$old = (int) getenv("OLD_ID"); $new = (int) getenv("NEW_ID");
$orders = wc_get_orders(["limit" => -1, "customer_id" => $old, "return" => "ids"]);
$cnt=0;
foreach ($orders as $id) { $o = wc_get_order($id); $o->set_customer_id($new); $o->save(); $cnt++; }
echo "Reassigned $cnt orders from user $old -> $new.\n";
'

echo "==> (Optional) Sync billing_email to the new user…"
if BILLING_EMAIL="$(wp user meta get "$OLD_ID" billing_email 2>/dev/null)"; then
  if [ -n "${BILLING_EMAIL:-}" ]; then wp user meta update "$NEW_ID" billing_email "$BILLING_EMAIL" >/dev/null; fi
fi

echo "==> Deleting OLD user ($OLD_ID) and reassigning any posts/comments to $NEW_ID…"
wp user delete "$OLD_ID" --reassign="$NEW_ID" --yes

echo "==> Flushing caches…"
wp cache flush
wp transient delete --all
wp redis flush 2>/dev/null || true

echo "==> Done."
echo "Login creds for the new user:"
echo "  Username: $NEW_LOGIN"
echo "  Password: $NEW_PASS"
