| @@ -241,10 +241,40 @@ | ||
| 241 | 241 | ['id' => $customerId], |
| 242 | 242 | null, |
| 243 | 243 | ['%d'] |
| 244 | 244 | ); |
| 245 | - | |
| 245 | + | |
| 246 | 246 | return $result !== false; |
| 247 | + } | |
| 248 | + | |
| 249 | + /** | |
| 250 | + * Link a WordPress user to a customer, ONLY when the customer has none yet. | |
| 251 | + * | |
| 252 | + * Deliberately narrow: the WHERE clause requires the current user_id to be | |
| 253 | + * NULL/0, so this can add a login link but can never reassign or overwrite an | |
| 254 | + * existing one — a customer's login is never silently switched to a different | |
| 255 | + * account. Returns true only when a row was actually linked. | |
| 256 | + */ | |
| 257 | + public function linkUserIfUnlinked(int $customerId, int $userId): bool | |
| 258 | + { | |
| 259 | + global $wpdb; | |
| 260 | + | |
| 261 | + if ($customerId <= 0 || $userId <= 0) { | |
| 262 | + return false; | |
| 263 | + } | |
| 264 | + | |
| 265 | + $table = $this->getTableName(); | |
| 266 | + | |
| 267 | + $result = $wpdb->query($wpdb->prepare( | |
| 268 | + "UPDATE `{$table}` | |
| 269 | + SET user_id = %d, updated_at = %s | |
| 270 | + WHERE id = %d AND (user_id IS NULL OR user_id = 0)", | |
| 271 | + $userId, | |
| 272 | + current_time('mysql'), | |
| 273 | + $customerId | |
| 274 | + )); | |
| 275 | + | |
| 276 | + return $result > 0; | |
| 247 | 277 | } |
| 248 | 278 | |
| 249 | 279 | /** |
| 250 | 280 | * Update customer from admin form |