Jake Vanderwerf
4 days ago 5a6906f710e9333507486df3cbb545a67a040881
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
<?php
namespace JVBase\managers;
 
use Exception;
use JVBase\managers\queue\executors\InvitationExecutor;
use JVBase\managers\queue\TypeConfig;
use JVBase\registrar\Registrar;
use JVBase\base\Site;
use WP_Error;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class InvitationsManager
{
    protected array $inviteConfig;
    protected CustomTable $table;
    protected int $expiryDays = 14;
    protected Cache $cache;
    public function __construct()
    {
        $this->defineTable();
        if (!isset($this->table)) {
            return;
        }
        $this->setInviteConfig();
        $this->cache = Cache::for('invitations');
        add_action('init', [$this, 'registerInvitationExecutors'], 5);
 
        add_action('user_register', [$this, 'checkInvitation']);
        add_filter('jvbLoginLabels', [$this, 'modifyLoginLabels'], 10, 2);
        add_action('jvb_daily_maintenance', [$this, 'cleanupExpiredInvitations']);
        add_filter(BASE . 'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
    }
 
    public function defineTable():void
    {
        $terms = Registrar::getFeatured('invitable', 'term');
        $membership = Site::membership();
        $roles = ($membership) ? Site::membership()->has('can_invite') :[];
        if (empty($terms) && empty($roles)) {
            return;
        }
 
        $table = CustomTable::for('invitations');
        $columns = [
            'id'                => 'bigint(20) unsigned NOT NULL AUTO_INCREMENT',
            'name'              => 'varchar(255) NOT NULL',
            'email'             => 'varchar(255) NOT NULL',
            'invitation_token'  => 'varchar(255) NOT NULL',
            'invited_role'      => 'varchar(50) NOT NULL',      //Role being invited to
            'status'            => "ENUM('pending','accepted','rejected','expired','revoked') DEFAULT 'pending'",
            'inviters'          => 'JSON NOT NULL',             // Array of {user_id, invited_at}
            'new_user_id'       => $table->getUserIDType().' DEFAULT NULL',
            'expires_at'        => 'datetime NOT NULL',
            'accepted_at'       => 'datetime DEFAULT NULL',
            'created_at'        => 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP',
            'updated_at'        => 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'
        ];
 
        foreach ($terms as $tax) {
            $columns["to_{$tax}"] = $table->getTermIDType().' DEFAULT NULL';
        }
        $table->setColumns($columns);
 
 
        $table->setKeys([
            ['key' => 'PRIMARY', 'value' => '(`id`)'],
            ['key' => 'UNIQUE', 'value' => '`unique_email_role` (`email`, `invited_role`)'],
            '`token_lookup` (`invitation_token`)',
            '`status_expiry` (`status`, `expires_at`)',
            '`role_status` (`invited_role`, `status`)',
            '`email_status` (`email`, `status`)'
        ]);
        $constraints = [];
        $base = BASE;
        global $wpdb;
        foreach ($terms as $tax) {
            $constraints[] = "CONSTRAINT `{$base}invitations_{$tax}_fk` FOREIGN KEY (`to_{$tax}`) REFERENCES `{$wpdb->terms}` (`term_id`)
            ON DELETE SET NULL";
        }
        $constraints[] = "CONSTRAINT `{$base}invitations_user_fk`  FOREIGN KEY (`new_user_id`) REFERENCES `{$table->getUserTable()}` (`ID`)
        ON DELETE SET NULL";
 
        $table->setConstraints($constraints);
 
        $table->defineTable();
        $this->table = $table;
    }
 
    protected function setInviteConfig():void
    {
        $this->inviteConfig = get_option(BASE.'invitation_config', [
            'roles' => [],
            'terms' => []
        ]);
    }
 
    public function invitableTerms():array
    {
        return $this->inviteConfig['terms'];
    }
 
    public function invitableRoles():array
    {
        return $this->inviteConfig['roles'];
    }
 
    public function getInviteConfig():array
    {
        return $this->inviteConfig;
    }
 
 
    /**
     * Register invitation operation types with queue TypeRegistry
     */
    public function registerInvitationExecutors(): void
    {
        $registry = JVB()->queue()->registry();
        $executor = new InvitationExecutor();
 
        // Create invitations - chunked at 20
        $registry->register('invitation_create', new TypeConfig(
            executor: $executor,
            chunkKey: 'invitations',
            chunkSize: 20
        ));
 
        // Resend invitations - chunked at 10
        $registry->register('invitation_resend', new TypeConfig(
            executor: $executor,
            chunkKey: 'invitations',
            chunkSize: 10
        ));
 
        // Revoke invitations
        $registry->register('invitation_revoke', new TypeConfig(
            executor: $executor
        ));
    }
 
    /**
     * Build invite types from JVB constants
     * Combines JVB_MEMBERSHIP['can_invite'] and invitable taxonomies
     */
    protected function buildInviteTypes(): array
    {
        $invitable = $this->cache->remember(
            'invitableTypes',
            function () {
                $types = [];
 
                // Global invitations from JVB_MEMBERSHIP
                if (!empty(JVB_MEMBERSHIP['can_invite'])) {
                    foreach (JVB_MEMBERSHIP['can_invite'] as $role => $canInvite) {
                        $types[$role] = [
                            'can_invite' => $canInvite,
                            'to_terms' => []
                        ];
                    }
                }
 
                // Term invitations from invitable content taxonomies
                $invitable = Registrar::getFeatured('invitable', 'term');
                $content = Registrar::getFeatured('is_content', 'term');
                $ownable = Registrar::getFeatured('is_ownable', 'term');
                $taxonomies = array_intersect($invitable, $content, $ownable);
                if (!empty($taxonomies)) {
                    $users = Registrar::getRegistered('user');
                }
                foreach ($taxonomies as $taxonomy) {
                    $registrar = Registrar::getInstance($taxonomy);
 
                    foreach ($registrar->registrar->for as $content) {
                        // Find which user roles can create this content
                        foreach ($users as $user) {
                            $userRegistrar = Registrar::getInstance($user);
 
                            $creatable = $userRegistrar->getCreatable();
                            if (in_array($content, $creatable)) {
                                if (!isset($types[$role])) {
                                    $types[$role] = [
                                        'can_invite' => [],
                                        'to_terms' => []
                                    ];
                                }
                                if (!in_array($taxonomy, $types[$role]['to_terms'])) {
                                    $types[$role]['to_terms'][] = $taxonomy;
                                }
                            }
                        }
                    }
                }
 
                return $types;
            }
        );
        return $invitable;
 
    }
 
    /******************************************************************
     * UTILITY
    ******************************************************************/
    public function canInviteToTerm(int $userID, string $taxonomy, int $termID):bool
    {
        $taxonomy = jvbNoBase($taxonomy);
 
        // Check if taxonomy is invitable
        if (!in_array($taxonomy, $this->invitableTerms())) {
            return false;
        }
 
        // User must be owner or manager of the term
        return JVB()->roles()->isManager($userID, $termID);
    }
 
    /**
     * Check if user can send global invitations
     */
    public function canInviteGlobally(int $userID, string $targetRole): bool
    {
        $userRole = jvbUserRole($userID);
        $allowedRoles = $this->inviteConfig['roles'][$userRole] ?? [];
 
        return in_array($targetRole, $allowedRoles);
    }
 
    public function validateInvitations(int $userID, array $invites): array
    {
        $validated = [];
 
        foreach ($invites as $invite) {
            $sanitized = $this->sanitizeInvitation($invite);
            if (!$sanitized) {
                continue;
            }
 
            // Check permissions
            if ($sanitized['to_term'] && $sanitized['taxonomy']) {
                // Term invitation - check management capability
                if (!$this->canInviteToTerm($userID, $sanitized['taxonomy'], $sanitized['to_term'])) {
                    continue;
                }
            } else {
                // Global invitation - check if allowed to invite this role
                if (!$this->canInviteGlobally($userID, $sanitized['invited_role'])) {
                    continue;
                }
            }
 
            $validated[] = $sanitized;
        }
 
        return $validated;
    }
 
    /**
     * Sanitize single invitation
     */
    protected function sanitizeInvitation(array $invite): ?array
    {
        $email = sanitize_email($invite['email'] ?? '');
        $name = sanitize_text_field($invite['name'] ?? '');
        $role = $invite['role'] ?? '';
 
        if (!is_email($email) || empty($name) || empty($role)) {
            return null;
        }
 
        // Check if user already exists
        if (email_exists($email)) {
            return null;
        }
 
        $sanitized = [
            'email' => $email,
            'name' => $name,
            'invited_role' => $role,
            'to_term' => isset($invite['to_term']) ? (int) $invite['to_term'] : null,
            'taxonomy' => isset($invite['taxonomy']) ? jvbNoBase($invite['taxonomy']) : null
        ];
 
        // Validate term if provided
        if ($sanitized['to_term'] && $sanitized['taxonomy']) {
            $term = get_term($sanitized['to_term'], BASE . $sanitized['taxonomy']);
            if (!$term || is_wp_error($term)) {
                $sanitized['to_term'] = null;
                $sanitized['taxonomy'] = null;
            }
        }
 
        return $sanitized;
    }
 
    /**************************************************************************
     * QUEUE
    **************************************************************************/
    /**
     * Process bulk invitations (called by queue)
     */
    public function processOperation(WP_Error|array $result, object $operation, array $data): array|WP_Error
    {
        if ($operation->type !== 'invitation_create') {
            return $result;
        }
 
        return $this->processInvitations($data, $operation->user_id);
    }
 
    /**
     * Process invitations with transaction support
     */
    protected function processInvitations(array $data, int $userID): array
    {
        $invitations = $data['invitations'] ?? [];
 
        $results = [
            'success' => [],
            'failed' => []
        ];
 
        $this->table->startTransaction();
 
        try {
            foreach ($invitations as $invite) {
                $result = $this->createInvitation(
                    $invite['name'],
                    $invite['email'],
                    $userID,
                    $invite['invited_role'],
                    $invite['to_term'],
                    $invite['taxonomy'],
                    false // Don't send email yet
                );
 
                if (is_wp_error($result)) {
                    $results['failed'][] = [
                        'email' => $invite['email'],
                        'name' => $invite['name'],
                        'reason' => $result->get_error_message()
                    ];
                } else {
                    $results['success'][] = array_merge($result, [
                        'email' => $invite['email'],
                        'name' => $invite['name']
                    ]);
                }
            }
 
            if (!empty($results['success'])) {
                $this->table->commit();
 
                // Send emails
                foreach ($results['success'] as $invitation) {
                    $terms = [];
                    if ($invitation['to_term'] && $invitation['taxonomy']) {
                        $terms[$invitation['taxonomy']] = $invitation['to_term'];
                    }
 
                    $this->sendInvitationEmail(
                        $invitation['name'],
                        $invitation['email'],
                        $invitation['token'],
                        $userID,
                        $terms,
                        $invitation['invited_role']
                    );
                }
            } else {
                $this->table->rollback();
            }
 
            return [
                'success' => count($results['success']) > 0,
                'results' => $results
            ];
 
        } catch (Exception $e) {
            $this->table->rollback();
 
            JVB()->error()->log(
                'invitation_create',
                'Error processing invitations: ' . $e->getMessage(),
                ['user_id' => $userID],
            );
 
            return [
                'success' => false,
                'result' => [
                    'failed' => $invitations,
                    'error' => $e->getMessage()
                ]
            ];
        }
    }
 
    /**
     * Create or update an invitation
     */
    public function createInvitation(
        string $name,
        string $email,
        int $inviterID,
        string $invitedRole,
        ?int $termID = null,
        ?string $taxonomy = null,
        bool $sendEmail = true
    ): WP_Error|array {
 
        $email = sanitize_email($email);
        if (!is_email($email)) {
            return new WP_Error('invalid_email', 'Invalid email address');
        }
 
        if (email_exists($email)) {
            return new WP_Error('user_exists', 'User already registered');
        }
 
        // Check for existing invitation
        $existing = $this->table->get([
            'email' => $email,
            'invited_role' => $invitedRole
        ]);
 
        $token = wp_generate_password(32, false);
        $expiresAt = date('Y-m-d H:i:s', strtotime("+{$this->expiryDays} days"));
 
        if ($existing) {
            // Update existing
            $inviters = json_decode($existing->inviters, true) ?: [];
 
            $inviterExists = false;
            foreach ($inviters as &$inviter) {
                if ($inviter['user_id'] == $inviterID) {
                    $inviterExists = true;
                    $inviter['invited_at'] = current_time('mysql');
                    break;
                }
            }
 
            if (!$inviterExists) {
                $inviters[] = [
                    'user_id' => $inviterID,
                    'invited_at' => current_time('mysql')
                ];
            }
 
            $updateData = [
                'inviters' => json_encode($inviters),
                'status' => 'pending',
                'expires_at' => $expiresAt
            ];
 
            if ($termID && $taxonomy) {
                $updateData['to_' . $taxonomy] = $termID;
            }
 
            if ($existing->status === 'expired') {
                $updateData['invitation_token'] = $token;
            } else {
                $token = $existing->invitation_token;
            }
 
            $this->table->update($updateData, ['id' => $existing->id]);
            $invitationID = $existing->id;
 
        } else {
            // Create new
            $insertData = [
                'name' => sanitize_text_field($name),
                'email' => $email,
                'invitation_token' => $token,
                'invited_role' => $invitedRole,
                'status' => 'pending',
                'inviters' => json_encode([[
                    'user_id' => $inviterID,
                    'invited_at' => current_time('mysql')
                ]]),
                'expires_at' => $expiresAt
            ];
 
            if ($termID && $taxonomy) {
                $insertData['to_' . $taxonomy] = $termID;
            }
 
            $invitationID = $this->table->insert($insertData);
        }
 
        if ($sendEmail) {
            $terms = [];
            if ($termID && $taxonomy) {
                $terms[$taxonomy] = $termID;
            }
            $this->sendInvitationEmail($name, $email, $token, $inviterID, $terms, $invitedRole);
        }
 
        return [
            'id' => $invitationID,
            'token' => $token,
            'expires_at' => $expiresAt,
            'to_term' => $termID,
            'taxonomy' => $taxonomy,
            'invited_role' => $invitedRole
        ];
    }
 
    /**
     * Send invitation email
     */
    public function sendInvitationEmail(
        string $name,
        string $email,
        string $token,
        int $inviterID,
        array $terms,
        string $role
    ): void {
        $inviterName = jvbGetUsername($inviterID);
        $siteName = get_bloginfo('name');
 
        $subject = apply_filters('jvbInvitationSubject',
            sprintf("%s invited you to join %s!", $inviterName, $siteName),
            $inviterName
        );
 
        $signupUrl = add_query_arg([
            'invite' => $token,
            'email' => urlencode($email),
            'name' => urlencode($name),
            'role' => $role
        ], wp_registration_url());
 
        // Build term-specific content
        $termContent = [];
        foreach ($terms as $taxonomy => $termID) {
            if (!$termID) continue;
 
            $term = get_term($termID, BASE . $taxonomy);
            if ($term && !is_wp_error($term)) {
                $registrar = Registrar::getInstance($taxonomy);
 
                $singular = $registrar ? $registrar->getSingular() : $taxonomy;
 
                $termContent[] = sprintf(
                    "<p>%s has also invited you to join %s. You'll be automatically added to this %s when you register.</p>",
                    $inviterName,
                    html_entity_decode($term->name),
                    $singular
                );
            }
        }
        $termText = implode('', $termContent);
 
        $button = JVB()->email()->button($signupUrl, 'Join the Scene!');
        $link = JVB()->email()->link($signupUrl);
        $signature = JVB()->email()->signature();
 
        $message = sprintf(
            '<p>Hi %s!</p>
        <p>%s has invited you to join them on %s.</p>
        %s
        <h2>Interested?</h2>
        <p>Join in by clicking the button below:</p>
        %s
        <p>Or by copying and pasting the link below into your browser:</p>
        %s
        <div class="divider"></div>
        <p>This invitation expires in %d days.</p>
        <p>Ink on,</p>
        %s',
            $name,
            $inviterName,
            $siteName,
            $termText,
            $button,
            $link,
            $this->expiryDays,
            $signature
        );
 
        $message = apply_filters('jvbInvitationMessage',
            $message,
            $name,
            $inviterName,
            $role,
            $terms,
            $this->expiryDays,
            $button,
            $link,
            $signature
        );
 
        JVB()->email()->sendEmail($email, $subject, $message);
    }
 
    /**
     * Check invitation on user registration
     * @throws Exception
     */
    public function checkInvitation(int $userID): void
    {
        $token = sanitize_text_field($_GET['invite'] ?? '');
        $email = sanitize_email($_GET['email'] ?? '');
 
        if (!$token || !$email) {
            return;
        }
 
        $user = get_userdata($userID);
        if (!$user || $user->user_email !== $email) {
            return;
        }
 
        $this->acceptInvitation($token, $email, $userID);
    }
 
    /**
     * Accept invitation and grant appropriate capabilities
     * @throws Exception
     */
    public function acceptInvitation(string $token, string $email, int $userID): bool
    {
        // Verify invitation using fluent CustomTable
        $invitation = $this->table
            ->where([
                'invitation_token' => $token,
                'email' => $email,
                'status' => 'pending'
            ])
            ->first();
 
        if (!$invitation) {
            return false;
        }
 
        // Check expiry
        if (strtotime($invitation->expires_at) < time()) {
            return false;
        }
 
        // Update in transaction
        $success = $this->table->transaction(function($table) use ($invitation, $userID) {
            // Update invitation status
            $table->update(
                [
                    'status' => 'accepted',
                    'new_user_id' => $userID,
                    'accepted_at' => current_time('mysql')
                ],
                ['id' => $invitation->id]
            );
 
            // Grant capabilities
            $user = get_userdata($userID);
            $user->add_cap('skip_moderation', true);
 
            return true;
        });
 
        if (!$success) {
            return false;
        }
 
        // Handle term membership
        $this->processTermMembership($userID, $invitation);
 
        // Notify inviters
        $this->notifyInvitersOfAcceptance($invitation, $userID);
 
        // Invalidate cache
        Cache::for('invitations')->forget('user_' . $userID);
 
        return true;
    }
 
    /**
     * Process term membership for accepted invitation
     */
    protected function processTermMembership(int $userID, object $invitation): void
    {
        foreach (JVB()->roles()->getInvitableTaxonomies() as $taxonomy) {
            $column = 'to_' . $taxonomy;
            if (isset($invitation->$column) && $invitation->$column) {
                $termID = (int) $invitation->$column;
 
                do_action(
                    BASE . 'add_user_to_term',
                    $userID,
                    $termID,
                    $taxonomy,
                    'member'
                );
            }
        }
    }
 
    /**
     * Notify inviters that invitation was accepted
     */
    protected function notifyInvitersOfAcceptance(object $invitation, int $userID): void
    {
        $inviters = json_decode($invitation->inviters, true) ?: [];
        $userData = get_userdata($userID);
 
        foreach ($inviters as $inviter) {
            JVB()->notification()->addNotification(
                $inviter['user_id'],
                'invitation_accepted',
                [
                    'invited_email' => $invitation->email,
                    'user_id' => $userID,
                    'display_name' => $userData->display_name
                ]
            );
        }
    }
 
    /**
     * Clean up expired invitations (daily cron)
     */
    public function cleanupExpiredInvitations(): void
    {
        // Use raw query for date comparison
        $this->table->query(
            "UPDATE {$this->table->getFullTableName()}
        SET status = 'expired'
        WHERE status = 'pending'
        AND expires_at < NOW()"
        );
 
        // Clear cache after cleanup
        Cache::for('invitations')->flush();
    }
 
    /*****************************************************************
     * Emails
    *****************************************************************/
    /**
     * Send revocation email
     */
    public function sendRevocationEmail(string $email, string $name): void
    {
        $siteName = get_bloginfo('name');
 
        $subject = apply_filters('jvbInvitationRevokedSubject',
            sprintf('[%s] Your invitation has been revoked', $siteName)
        );
 
        $content = apply_filters('jvbInvitationRevokedMessage',
            sprintf(
                '<p>Hey %s,</p>
            <p>This is to let you know that your invitation to join %s has been revoked.</p>
            <p>If you believe this was done in error, please contact the person who invited you or the site admin.</p>',
                $name,
                $siteName
            ),
            $name
        );
 
        JVB()->email()->sendEmail($email, $subject, $content, 'INVITATION REVOKED');
    }
 
    /**
     * TODO: Check with LoginManager.php
     * Modify login labels for invitation flow
     */
    public function modifyLoginLabels(array $labels, array $getParams): array
    {
        if (!isset($getParams['invite']) || !isset($getParams['email'])) {
            return $labels;
        }
 
        $email = sanitize_email($getParams['email']);
        $token = sanitize_text_field($getParams['invite']);
        $role = $getParams['role'] ?? '';
 
        if (empty($role)) {
            return $labels;
        }
 
        // Use fluent interface
        $invitation = $this->table
            ->where([
                'invitation_token' => $token,
                'email' => $email,
                'invited_role' => $role,
                'status' => 'pending'
            ])
            ->first();
 
        if (!$invitation) {
            return $labels;
        }
 
        // Build inviter names
        $inviters = json_decode($invitation->inviters, true) ?: [];
        $names = array_map(fn($inviter) => jvbGetUsername($inviter['user_id']), $inviters);
 
        $message = count($names) > 1
            ? 'are already here, and have invited you to join in!'
            : ' is already here, and invited you to join in!';
 
        $labels['title'] = 'Join the Scene, ' . $invitation->name;
        $labels['description'] = [jvbCommaList($names) . ' ' . $message];
 
        return $labels;
    }
}