Jake Vanderwerf
2026-02-11 3b3bd067d0ff2671fca2890c14428c97e1011a2b
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
<?php
namespace JVBase\managers\queue\executors;
 
use JVBase\managers\CustomTable;
use JVBase\managers\queue\Executor;
use JVBase\managers\queue\Operation;
use JVBase\managers\queue\Progress;
use JVBase\managers\queue\Result;
use JVBase\managers\RoleManager;
use JVBase\meta\Meta;
use JVBase\utility\Features;
use Exception;
 
if (!defined('ABSPATH')) {
    exit;
}
 
/**
 * Executor for content taxonomy operations (shops, studios, etc.)
 *
 * Handles:
 * - Term metadata updates
 * - Member additions (via history table)
 * - Member removals (via history table)
 */
class ContentTermExecutor implements Executor
{
    protected RoleManager $roleManager;
 
    public function __construct()
    {
        $this->roleManager = new RoleManager();
    }
 
    public function execute(Operation $operation, Progress $progress): Result
    {
        // Extract taxonomy from operation type (e.g., "shop_update" -> "shop")
        $parts = explode('_', $operation->type);
        $taxonomy = $parts[0] ?? '';
 
        if (!$taxonomy || !isset(JVB_TAXONOMY[$taxonomy])) {
            return Result::fail("Invalid taxonomy: {$taxonomy}");
        }
 
        return match(true) {
            str_ends_with($operation->type, '_update') => $this->processUpdate($operation, $taxonomy),
            str_ends_with($operation->type, '_member_add') => $this->processMemberAdd($operation, $taxonomy),
            str_ends_with($operation->type, '_member_remove') => $this->processMemberRemove($operation, $taxonomy),
            default => Result::fail("Unknown operation type: {$operation->type}")
        };
    }
 
    /**
     * Process term metadata updates
     */
    protected function processUpdate(Operation $operation, string $taxonomy): Result
    {
        $termID = $operation->requestData['term_id'] ?? 0;
        $userID = $operation->userId;
 
        if (!$termID || !term_exists($termID, jvbCheckBase($taxonomy))) {
            return Result::fail('Invalid term ID');
        }
 
        // Verify permissions using RoleManager
        if (!user_can($userID, 'manage_options') && !$this->roleManager->isManager($userID, $termID)) {
            return Result::fail('User does not have permission to manage this ' . $taxonomy);
        }
 
        try {
            $meta = Meta::forTerm($termID);
            $data = $operation->requestData;
            unset($data['term_id']);
 
            // Filter to only allowed fields
            $allowed = jvbGetFields($taxonomy, 'term');
            $setData = array_filter(
                $data,
                fn($key) => array_key_exists($key, $allowed),
                ARRAY_FILTER_USE_KEY
            );
 
            if (empty($setData)) {
                return Result::fail('No valid fields to update');
            }
 
            // Update metadata
            $meta->setAll($setData);
            $results = $meta->save();
 
            if ($results) {
                // Trigger any post-update actions (e.g., thumbnail generation)
                do_action(BASE . "{$taxonomy}_updated", $termID, $userID, $setData);
 
                return Result::success([
                    'updated_fields' => array_keys($setData),
                    'term_id' => $termID
                ]);
            }
 
            return Result::fail('Failed to update term metadata');
 
        } catch (Exception $e) {
            return Result::fail('Update error: ' . $e->getMessage());
        }
    }
 
    /**
     * Add member to term (via history table)
     */
    protected function processMemberAdd(Operation $operation, string $taxonomy): Result
    {
        $termID = $operation->requestData['term_id'] ?? 0;
        $targetUserID = $operation->requestData['target_user'] ?? 0;
        $userID = $operation->userId;
 
        if (!$termID || !term_exists($termID, jvbCheckBase($taxonomy))) {
            return Result::fail('Invalid term ID');
        }
 
        if (!get_userdata($targetUserID)) {
            return Result::fail('Invalid target user');
        }
 
        // Verify permissions
        if (!user_can($userID, 'manage_options') && !$this->roleManager->isManager($userID, $termID)) {
            return Result::fail('User does not have permission to manage this ' . $taxonomy);
        }
 
        // Check if tracking enabled
        if (!Features::forTaxonomy($taxonomy)->has('track_changes')) {
            return Result::fail('Member tracking not enabled for ' . $taxonomy);
        }
 
        try {
            return $this->addMember($targetUserID, $termID, $taxonomy);
        } catch (Exception $e) {
            return Result::fail('Add member error: ' . $e->getMessage());
        }
    }
 
    /**
     * Remove member from term (via history table)
     */
    protected function processMemberRemove(Operation $operation, string $taxonomy): Result
    {
        $termID = $operation->requestData['term_id'] ?? 0;
        $targetUserID = $operation->requestData['target_user'] ?? 0;
        $userID = $operation->userId;
 
        if (!$termID || !term_exists($termID, jvbCheckBase($taxonomy))) {
            return Result::fail('Invalid term ID');
        }
 
        if (!get_userdata($targetUserID)) {
            return Result::fail('Invalid target user');
        }
 
        // Verify permissions
        if (!user_can($userID, 'manage_options') && !$this->roleManager->isManager($userID, $termID)) {
            return Result::fail('User does not have permission to manage this ' . $taxonomy);
        }
 
        try {
            return $this->removeMember($targetUserID, $termID, $taxonomy);
        } catch (Exception $e) {
            return Result::fail('Remove member error: ' . $e->getMessage());
        }
    }
 
    /**
     * Add member to term with transaction support
     */
    protected function addMember(int $userID, int $termID, string $taxonomy): Result
    {
        $config = JVB_TAXONOMY[$taxonomy] ?? [];
        $content = $config['for_content'] ?? [];
 
        if (empty($content)) {
            return Result::fail('No content types configured for ' . $taxonomy);
        }
 
        // Get table name (e.g., "history_artist_shop")
        $contentType = $content[0]; // Use first content type
        $tableName = "history_{$contentType}_{$taxonomy}";
        $table = CustomTable::for($tableName);
 
        return $table->transaction(function($table) use ($userID, $termID, $taxonomy, $contentType) {
            // Check if already a member
            $existing = $table
                ->where([
                    'user_id' => $userID,
                    'term_id' => $termID,
                    'end_date' => null
                ])
                ->first();
 
            if ($existing) {
                return Result::success([
                    'message' => 'User is already a member',
                    'existing' => true
                ]);
            }
 
            // Get user's content post ID
            $contentID = get_user_meta($userID, BASE . 'link', true);
            if (!$contentID) {
                throw new Exception('User profile not found');
            }
 
            // Verify content post exists
            $post = get_post($contentID);
            if (!$post || $post->post_type !== BASE . $contentType) {
                throw new Exception('Content post not found or invalid type');
            }
 
            // Insert new membership
            $result = $table->create([
                'user_id' => $userID,
                'content_id' => $contentID,
                'term_id' => $termID,
                'role' => 'member',
                'is_primary' => 1,
                'start_date' => current_time('mysql')
            ]);
 
            if (!$result) {
                throw new Exception('Failed to create membership record');
            }
 
            // Add taxonomy term to content post
            $termResult = wp_set_object_terms($contentID, [$termID], jvbCheckBase($taxonomy), true);
 
            if (is_wp_error($termResult)) {
                throw new Exception('Failed to set taxonomy term: ' . $termResult->get_error_message());
            }
 
            // Clear cache
            JVB()->cache()->for($taxonomy)->delete("{$taxonomy}_{$termID}_members");
 
            // Notify term managers
            $this->notifyTermManagers($termID, $userID, $taxonomy, 'member_added');
 
            return Result::success([
                'message' => 'Member added successfully',
                'user_id' => $userID,
                'term_id' => $termID
            ]);
        });
    }
 
    /**
     * Remove member from term with transaction support
     */
    protected function removeMember(int $userID, int $termID, string $taxonomy): Result
    {
        $config = JVB_TAXONOMY[$taxonomy] ?? [];
        $content = $config['for_content'] ?? [];
 
        if (empty($content)) {
            return Result::fail('No content types configured for ' . $taxonomy);
        }
 
        // Get table name
        $contentType = $content[0];
        $tableName = "history_{$contentType}_{$taxonomy}";
        $table = CustomTable::for($tableName);
 
        return $table->transaction(function($table) use ($userID, $termID, $taxonomy, $contentType) {
            // Get user's content post ID
            $contentID = get_user_meta($userID, BASE . 'link', true);
            if (!$contentID) {
                throw new Exception('User profile not found');
            }
 
            // Update membership record - set end_date
            $updated = $table
                ->where([
                    'user_id' => $userID,
                    'term_id' => $termID,
                    'end_date' => null
                ])
                ->updateResults([
                    'end_date' => current_time('mysql'),
                    'is_primary' => 0
                ]);
 
            if (!$updated) {
                throw new Exception('No active membership found');
            }
 
            // Remove taxonomy term from content post
            $termResult = wp_remove_object_terms($contentID, [$termID], jvbCheckBase($taxonomy));
 
            if (is_wp_error($termResult)) {
                throw new Exception('Failed to remove taxonomy term: ' . $termResult->get_error_message());
            }
 
            // Clear cache
            JVB()->cache()->for($taxonomy)->delete("{$taxonomy}_{$termID}_members");
 
            // Notify term managers
            $this->notifyTermManagers($termID, $userID, $taxonomy, 'member_removed');
 
            return Result::success([
                'message' => 'Member removed successfully',
                'user_id' => $userID,
                'term_id' => $termID
            ]);
        });
    }
 
    /**
     * Notify term owners/managers about member changes
     */
    protected function notifyTermManagers(int $termID, int $userID, string $taxonomy, string $notificationType): void
    {
        $managers = $this->roleManager->getManagedTerms($userID, $taxonomy);
        $term = get_term($termID, jvbCheckBase($taxonomy));
        $user = get_userdata($userID);
 
        foreach ($managers as $managerID) {
            JVB()->notification()->addNotification(
                $managerID,
                $notificationType,
                [
                    'user_id' => $userID,
                    'user_name' => $user ? $user->display_name : 'Unknown',
                    'term_id' => $termID,
                    'term_name' => $term && !is_wp_error($term) ? $term->name : 'Unknown',
                    'taxonomy' => $taxonomy
                ]
            );
        }
    }
}