Jake Vanderwerf
2026-03-29 275c0d74cd68677622a5431505c5c870c473063d
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
<?php
namespace JVBase\rest\routes;
 
use JVBase\managers\queue\executors\UploadExecutor;
use JVBase\managers\queue\mergers\UploadMerger;
use JVBase\managers\queue\TypeConfig;
use JVBase\registrar\Registrar;
use JVBase\rest\PermissionHandler;
use JVBase\rest\Rest;
use JVBase\meta\Meta;
use JVBase\managers\UploadManager;
use JVBase\rest\Route;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use Exception;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
class UploadRoutes extends Rest
{
 
    public function __construct()
    {
        parent::__construct();
 
        add_action('init', [$this, 'registerUploadExecutors'], 5);
    }
 
    /**
     * Register upload operation types with the queue's TypeRegistry
     */
    public function registerUploadExecutors(): void
    {
        $registry = JVB()->queue()->registry();
        $executor = new UploadExecutor();
        $merger = new UploadMerger('secured_files');
 
        // Image uploads - chunked at 5 files
        $registry->register('image_upload', new TypeConfig(
            mergeable: $merger,
            executor: $executor,
            chunkKey: 'secured_files',
            chunkSize: 3
        ));
 
        // Video uploads - one at a time (heavy processing)
        $registry->register('video_upload', new TypeConfig(
            mergeable: $merger,
            executor: $executor,
            chunkKey: 'secured_files',
            chunkSize: 1
        ));
 
        // Document uploads - chunked at 10
        $registry->register('document_upload', new TypeConfig(
            mergeable: $merger,
            executor: $executor,
            chunkKey: 'secured_files',
            chunkSize: 5
        ));
 
        // Metadata updates
        $registry->register('update_image_meta', new TypeConfig(
            executor: $executor
        ));
 
        // Cleanup - chunked at 5
        $registry->register('temporary_cleanup', new TypeConfig(
            executor: $executor,
            chunkKey: 'files',
            chunkSize: 5
        ));
 
        // Attach to content (depends on upload completing)
        $registry->register('attach_upload_to_content', new TypeConfig(
            executor: $executor
        ));
 
        // Process upload groups into posts
        $registry->register('process_upload_groups', new TypeConfig(
            executor: $executor,
            chunkKey: 'posts',
            chunkSize: 5
        ));
    }
 
    /**
     * Registers upload routes
     * @return void
     */
    public function registerRoutes():void
    {
        Route::for('uploads')
            ->post([$this, 'handleUpload'])
            ->auth(PermissionHandler::combine(['nonce']))
            ->rateLimit(30)
            ->register();
 
        Route::for('uploads/groups')
            ->post([$this, 'handleGroupingRequest'])
            ->auth(PermissionHandler::combine(['nonce']))
            ->rateLimit(30)
            ->args([
                'id'        => 'string|required',
                'content'   => 'string|required',
                'user'      => 'int|required'
            ])
            ->register();
 
        Route::for('uploads/meta')
            ->post([$this, 'handleMetadataUpdate'])
            ->auth(PermissionHandler::combine(['nonce']))
            ->rateLimit(30)
            ->args([
                'user'  => 'int|required',
                'items' => 'array|required',
                'id'    => 'string'
            ])
            ->register();
    }
 
    /**
     * Build the main $context for UploadManager from the $request params
     * @param WP_REST_Request $request
     * @return array
     */
    protected function buildUploadArgs(WP_REST_Request $request):array
    {
        $data = $request->get_params();
        $args = [];
        $registrar = Registrar::getInstance($data['content']??'');
 
        foreach ($data as $key => $value) {
            switch ($key) {
                case 'depends_on':
                    if (is_string($value) && !empty($value)) {
                        $args['depends_on'] = sanitize_text_field($value);
                    }
                    break;
                case 'item_id':
                    if (is_numeric($value)) {
                        $args['item_id'] = absint($value);
                        if ($registrar) {
                            switch ($registrar->getType()) {
                                case 'post':
                                    $args['post_id'] = absint($value);
                                    break;
                                case 'term':
                                    $args['term_id'] = absint($value);
                                    break;
                                case 'user':
                                    $args['user_id'] = absint($value);
                                    break;
                            }
                        }
                    }
                    break;
                // Post Type/Taxonomy
                case 'content':
                    $value = str_replace('-', '_', $value);
                    if ($value === 'options' || $registrar) {
                        $args['content'] = $value;
                    }
                    break;
                case 'destination':
                    if (in_array($value, ['meta', 'post', 'post_group'])) {
                        $args['destination'] = sanitize_text_field($value);
                        if (in_array($value, ['post', 'post_group']) && empty($data['content'])) {
                            throw new Exception("Content type required for destination: {$value}");
                        }
                    }
                    break;
                // User ID
                case 'user':
                    if ($this->userCheck($value)) {
                        $args['user'] = (int) $value;
                        if (!array_key_exists('post_id', $args) &&
                            !array_key_exists('post_id', $data) &&
                            !array_key_exists('term_id', $data) &&
                            !array_key_exists('item_id', $data)) {
                            $args['post_id'] = (int)get_user_meta((int) $value, BASE.'link', true);
                        }
                    }
                    break;
                // Operation ID
                case 'id':
                    if (is_string($value)) {
                        $value = sanitize_text_field($value);
                        $args['id'] =  $value;
                        $args['upload'] = $value.'_upload';
                    }
                    break;
                // Post ID
                case 'post_id':
                    if (is_numeric($value)) {
                        $args['post_id'] = absint($value);
                    }
                    break;
                // Term ID
                case 'term_id':
                    if (is_numeric($value)) {
                        $args['term_id'] = absint($value);
                    }
                    break;
                // Field Name, as defined for Meta.php
                case 'field_name':
                    if (is_string($value)) {
                        $args['field_name'] = sanitize_text_field($value);
                    }
                    break;
                // Upload Mode
                case 'mode':
                    if (in_array($value, ['direct', 'selection'])) {
                        $args['mode'] = sanitize_text_field($value);
                    }
                    break;
                case 'upload_ids':
                    if (is_string($value)) {
                        // Parse JSON array
                        $decoded = json_decode($value, true);
                        if (is_array($decoded)) {
                            $args['upload_ids'] = $decoded;
                        }
                    } elseif (is_array($value)) {
                        // Already an array (shouldn't happen with FormData JSON, but handle it)
                        $args['upload_ids'] = $value;
                    }
                    break;
                case 'metadata':
                    if (!empty($value)) {
                        $metadata = is_string($value) ? json_decode($value, true) : $value;
                        if (is_array($metadata)) {
                            foreach ($metadata as $k => $v) {
                                if (in_array($k, ['title', 'caption', 'alt', 'depends_on'])) {
                                    $args['metadata'][$k] = sanitize_text_field($v);
                                }
                            }
                        }
                    }
                    break;
                case 'posts':
                    if (is_string($value)) {
                        $decoded = json_decode($value, true);
                        if (is_array($decoded)) {
                            $args['posts'] = $decoded;
                        }
                    }
                    break;
 
                case 'group_titles':
                    if (is_string($value)) {
                        $decoded = json_decode($value, true);
                        if (is_array($decoded)) {
                            $args['group_titles'] = array_map('sanitize_text_field', $decoded);
                        }
                    }
                    break;
                // Other field info
                case 'field_key':
                case 'field_type':
                case 'subtype':
                case 'item_id':
                case 'context':
                    if (is_string($value)) {
                        $args[$key] = sanitize_text_field($value);
                    }
                    break;
            }
        }
        return $args;
    }
 
    /**
     * Handle upload request with immediate feedback
     */
    /**
     * @param WP_REST_Request $request
     *
     * @return WP_REST_Response
     */
    public function handleUpload(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $files = $request->get_file_params();
            $args = $this->buildUploadArgs($request);
 
 
            if (!$args['user']) {
                 return $this->unauthorized();
            }
            if (!$args['content']) {
                return $this->validationError(['message' => 'Missing content']);
            }
 
            // Step 1: Secure all uploaded files
            $secured_files = $this->secureFiles($files, $args);
 
            if (empty($secured_files)) {
                $this->logError('No valid files to upload');
                return $this->error('No valid files to upload');
            }
 
            // Step 2: Queue for processing via OperationQueue
            $operation_id = $this->queueProcessing($secured_files, $args);
 
            return $this->queued($operation_id, 'Files secured and queued for processing');
 
        } catch (Exception $e) {
            // Error handling...
            JVB()->error()->log(
                '[UploadRoutes]:handleUploadRequest',
                $e->getMessage(),
                [
                    'request_data' => $request->get_params(),
                    'files_info' => $this->getFilesInfo($_FILES),
                    'trace' => $e->getTraceAsString()
                ]
            );
            return $this->error($e->getMessage());
        }
    }
 
    /**
     * Secure uploaded files to temporary storage
     */
    protected function secureFiles(array $files, array $args): array
    {
        $uploader = new UploadManager();
        $secured_files = [];
        $errors = [];
 
        $context = $args;
        unset($context['upload_ids']);
 
        $file_array = $files['files'] ?? $files;
        if (!is_array($file_array['tmp_name'])) {
            $file_array = [
                'name' => [$file_array['name']],
                'type' => [$file_array['type']],
                'tmp_name' => [$file_array['tmp_name']],
                'error' => [$file_array['error']],
                'size' => [$file_array['size']]
            ];
        }
        $tmp_names = $file_array['tmp_name'] ?? [];
 
 
 
        foreach ($tmp_names as $index => $tmp_name) {
            $file_data = [
                'name' => $file_array['name'][$index],
                'type' => $file_array['type'][$index],
                'tmp_name' => $tmp_name,
                'error' => $file_array['error'][$index],
                'size' => $file_array['size'][$index]
            ];
 
            if ($file_data['error'] !== UPLOAD_ERR_OK) {
                $errors[$index] = $this->getUploadErrorMessage($file_data['error']);
                continue;
            }
 
            try {
                $secured = $uploader->secureUploadedFile($file_data, $context);
 
                if (empty($secured)) {
                    throw new Exception('Failed to secure file');
                }
 
                // Embed upload_id directly in the secured file data
                $secured['upload_id'] = $args['upload_ids'][$index] ?? 'upload_' . $index;
 
                $secured_files[] = $secured;
            } catch (Exception $e) {
                $errors[$index] = $e->getMessage();
            }
        }
 
        return [
            'files' => $secured_files,
            'errors' => $errors
        ];
    }
 
    protected function getUploadErrorMessage(int $error_code): string
    {
        return match($error_code) {
            UPLOAD_ERR_INI_SIZE => 'File exceeds maximum upload size',
            UPLOAD_ERR_FORM_SIZE => 'File exceeds form maximum size',
            UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
            UPLOAD_ERR_NO_FILE => 'No file was uploaded',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
            UPLOAD_ERR_EXTENSION => 'Upload stopped by extension',
            default => 'Unknown upload error'
        };
    }
 
 
    /**
     * Queue files for processing
     */
    protected function queueProcessing(array $secured_data, array $args): string
    {
        $operation_type = $this->determineOperationType($secured_data['files'][0] ?? []);
 
        $chunkSize = 5;
        if ($operation_type === 'video') {
            $chunkSize = 1;
        } elseif ($operation_type === 'document') {
            $chunkSize = 10;
        }
 
        error_log('Queueing Operation: '.print_r($operation_type, true));
        error_log('With ID: '.print_r($args['upload'], true));
        $queuedProcessing = JVB()->queue()->queueOperation(
            $operation_type,
            $args['user'],
            array_merge(
                ['secured_files' => $secured_data['files']],
                $args
            ),
            [
                'operation_id'  => $args['upload'],
                'chunk_key'     => 'secured_files',
                'chunk_size'    => $chunkSize
            ]
        );
 
        error_log('queuedProcessing operation: '.print_r($queuedProcessing, true));
 
        $uploadOpId = $queuedProcessing['operation_id'];
 
        if ($args['mode'] !== 'selection') {
 
            // Only create attach_upload_to_content if the upload was NOT merged.
            // When merged, the original upload's attach_upload_to_content
            // will handle all files after the merged image_upload completes.
            if (!$queuedProcessing['updated_existing']) {
                JVB()->queue()->queueOperation(
                    'attach_upload_to_content',
                    $args['user'],
                    $args,
                    [
                        'priority'      => 'high',
                        'operation_id'  => $args['id'],
                        'depends_on'    => [$uploadOpId]
                    ]
                );
            }
        }
 
        JVB()->queue()->queueOperation(
            'temporary_cleanup',
            $args['user'],
            [
                'files'     => $secured_data['files'],
                'context'   => $args,
            ],
            [
                'priority'      => 'low',
                'chunk_size'    => 5,
                'chunk_key'     => 'files',
                'depends_on'    => [$uploadOpId]
            ]
        );
 
        return $args['id'];
    }
 
    /**
     * Determine operation type from file data
     */
    protected function determineOperationType(array $file): string
    {
        $file_type = $file['file_type'] ?? 'image';
 
        return match($file_type) {
            'video' => 'video_upload',
            'document' => 'document_upload',
            default => 'image_upload'
        };
    }
 
    /**
     * Step 3: Process operation from queue
     * Called by OperationQueue
     * @param WP_Error|array $result
     * @param object $operation
     * @param array $data
     *
     * @return array|WP_Error
     */
    public function processOperation(array $result, object $operation, array $data): array
    {
        // Only handle our operation types
        $handled_types = [
            'image_upload',
            'video_upload',
            'document_upload',
            'update_metadata',
            'temporary_cleanup',
            'attach_upload_to_content',
            'process_upload_groups'
        ];
 
        if (!in_array($operation->type, $handled_types)) {
            return $result; // Not our operation, pass through
        }
 
        try {
            // Route to appropriate handler
            $handler_result = match($operation->type) {
                'image_upload' => $this->processImageUpload($operation, $data),
                'video_upload' => $this->processVideoUpload($operation, $data),
                'document_upload' => $this->processDocumentUpload($operation, $data),
                'update_metadata' => $this->processUploadMeta($result, $operation, $data),
                'temporary_cleanup' => $this->processTemporaryCleanup($result, $operation, $data),
                'attach_upload_to_content' => $this->processAttachToContent($operation, $data),
                'process_upload_groups' => $this->processUploadGroups($result, $operation, $data),
                default => new WP_Error('unknown_type', 'Unknown operation type')
            };
 
            // Handle WP_Error
            if (is_wp_error($handler_result)) {
                return [
                    'success' => false,
                    'result' => $handler_result->get_error_message()
                ];
            }
 
            return $handler_result;
 
        } catch (Exception $e) {
            JVB()->error()->log(
                '[UploadRoutes]:processOperation',
                $e->getMessage(),
                [
                    'operation_id' => $operation->id,
                    'operation_type' => $operation->type
                ]
            );
 
            return [
                'success' => false,
                'result' => $e->getMessage()
            ];
        }
    }
    /**
     * Standardize processing result
     */
    protected function standardizeResult(array $result): array
    {
        return [
            'attachment_id' => $result['attachment_id'],
            'url' => $result['url'],
            'file' => $result['file'],
            'upload_id' => $result['upload_id'] ?? null
        ];
    }
 
    protected function processAttachToContent(object $operation, array $data): array
    {
        try {
            // Get the results from the upload operation
            $upload_results = JVB()->queue()->getOperationValue($data['upload'], 'result', true);
 
            if (empty($upload_results)) {
                throw new Exception('No upload results found for operation: ' . $data['upload']);
            }
 
            if (empty($data['post_id']) || str_starts_with((string)($data['item_id'] ?? ''), 'new')) {
                foreach ($operation->dependencies as $depId) {
                    $dep = JVB()->queue()->get($depId);
                    if ($dep && $dep->type === 'content_update' && !empty($dep->result['new_posts'])) {
                        $itemId = $data['item_id'] ?? null;
                        if ($itemId && isset($dep->result['new_posts'][$itemId])) {
                            $data['post_id'] = $dep->result['new_posts'][$itemId];
                            break;
                        }
                    }
                }
 
                if (empty($data['post_id'])) {
                    throw new Exception('Could not resolve post_id from dependencies');
                }
            }
 
            // Now attach to the specified content
            if (!empty($data['field_name'])) {
                $this->updateFieldValue($data, $upload_results);
            }
 
            return [
                'success' => true,
                'result' => 'Attachments linked to content'
            ];
 
        } catch (Exception $e) {
            return [
                'success' => false,
                'result' => $e->getMessage()
            ];
        }
    }
 
    /**
     * Cleanup temporary files after processing
     */
    protected function cleanupTempFiles(array $secured_files, int $user_id): void
    {
        $uploader = new UploadManager();
 
        foreach ($secured_files as $secured) {
            if (!empty($secured['temp_path']) && file_exists($secured['temp_path'])) {
                @unlink($secured['temp_path']);
            }
        }
 
        // Clean up empty directories
        $uploader->cleanupEmptyTempDirs($user_id);
    }
 
    /**
     * Update field value with new attachment IDs
     */
    protected function updateFieldValue(array $data, array $results): void
    {
        if ((!array_key_exists('post_id', $data) && !array_key_exists('term_id', $data) && !array_key_exists('user', $data))  && !array_key_exists('field_name', $data)) {
            return;
        }
 
        $attachment_ids = array_column($results, 'attachment_id');
        if (array_key_exists('post_id', $data)) {
            $meta = Meta::forPost($data['post_id']);
        } elseif (array_key_exists('term_id', $data)) {
            $meta = Meta::forTerm($data['term_id']);
        } else {
            $link = (int)get_user_meta($data['user'], BASE.'link');
            $meta = Meta::forPost($link);
        }
 
        // Get existing value
        $existing = $meta->get($data['field_name']);
        $existing_ids = !empty($existing) ? explode(',', $existing) : [];
 
        // Merge with new IDs
        $all_ids = array_unique(array_merge($existing_ids, $attachment_ids));
 
        // Update with comma-separated string
        $meta->set($data['field_name'], implode(',', $all_ids));
    }
 
    /**
     * Generic file upload processor - works for images, videos, documents
     */
    protected function processFileUpload(object $operation, array $data, string $file_type): WP_Error|array
    {
        try {
            $uploader = new UploadManager();
            $processed_results = [];
            $config = $this->getFieldConfig($data);
 
            $args = $data;
            unset($args['secured_files']);
 
            foreach ($data['secured_files'] as $secured_file) {
                $result = $uploader->processUpload(
                    $secured_file['temp_path'],
                    array_merge(
                        $config,
                        [
                            'file_type' => $file_type,
                            'user_id' => $operation->user_id,
                            'post_id' => (int)($data['post_id'] ?? 0),
                            'term_id' => (int)($data['term_id'] ?? 0),
                            'original_name' => $secured_file['original_name'],
                            'mime_type' => $secured_file['mime_type'],
                            'content' => $data['content'] ?? '',
                        ]
                    )
                );
 
                if (!is_wp_error($result)) {
                    $standardized = $this->standardizeResult($result);
 
                    // Use embedded upload_id from the secured file itself
                    $standardized['upload_id'] = $secured_file['upload_id'] ?? null;
 
                    if ($standardized['upload_id']) {
                        $processed_results[$standardized['upload_id']] = $standardized;
                    } else {
                        $processed_results[] = $standardized;
                    }
 
                    // Apply frontend metadata if provided
                    if (!empty($secured_file['metadata'])) {
                        $this->applyMeta($standardized['attachment_id'], $secured_file['metadata']);
                    }
                }
            }
 
            $this->handleUploadDestination($data, $processed_results);
 
            // Cleanup temporary files
            $this->cleanupTempFiles($data['secured_files'], $operation->user_id);
 
            return [
                'success' => true,
                'result' => $processed_results
            ];
 
        } catch (Exception $e) {
            JVB()->error()->log(
                '[UploadRoutes]:processFileUpload',
                $e->getMessage(),
                [
                    'operation_id' => $operation->id,
                    'file_type' => $file_type,
                    'user_id' => $operation->user_id
                ]
            );
            return [
                'success'   => false,
                'result'    => $e->getMessage()
            ];
        }
    }
 
    /**
     * Process image uploads
     */
    protected function processImageUpload(object $operation, array $data): WP_Error|array
    {
        return $this->processFileUpload($operation, $data, 'image');
    }
 
    /**
     * Process video uploads
     */
    protected function processVideoUpload(object $operation, array $data): WP_Error|array
    {
        return $this->processFileUpload($operation, $data, 'video');
    }
 
    /**
     * Process document uploads
     */
    protected function processDocumentUpload(object $operation, array $data): WP_Error|array
    {
        return $this->processFileUpload($operation, $data, 'document');
    }
 
    /**
     * Process temporary cleanup operation
     * Called by OperationQueue for 'temporary_cleanup' operations
     *
     * @param array $result
     * @param object $operation
     * @param array $data
     * @return array
     */
    protected function processTemporaryCleanup(array $result, object $operation, array $data): array
    {
        try {
            // Cleanup temporary files if they exist
            if (!empty($data['secured_files'])) {
                $this->cleanupTempFiles($data['secured_files'], $operation->user_id);
            }
 
            // If specific temp paths provided
            if (!empty($data['temp_paths']) && is_array($data['temp_paths'])) {
                foreach ($data['temp_paths'] as $temp_path) {
                    if (file_exists($temp_path)) {
                        @unlink($temp_path);
                    }
                }
            }
 
            // Cleanup empty temp directories for this user
            if (!empty($operation->user_id)) {
                $uploader = new UploadManager();
                $uploader->cleanupEmptyTempDirs($operation->user_id);
            }
 
            return [
                'success' => true,
                'result' => 'Temporary files cleaned up successfully'
            ];
 
        } catch (Exception $e) {
            JVB()->error()->log(
                '[UploadRoutes]:processTemporaryCleanup',
                $e->getMessage(),
                [
                    'operation_id' => $operation->id,
                    'user_id' => $operation->user_id
                ]
            );
 
            return [
                'success' => false,
                'result' => $e->getMessage()
            ];
        }
    }
 
    /**
     * Handle metadata update requests
     */
    public function handleMetadataUpdate(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $data = $request->get_params();
 
            error_log('Received data for meta change: '.print_r($data, true));
 
 
            $items = $data['items']??false;
            if (!$items) {
                return $this->sendResponse(
                    true,
                    [
                    ],
                    'No items to update'
                );
            }
            $pending = [];
            $attachments = array_filter($items, function ($item) {
                return array_key_exists('attachmentId', $item) || array_key_exists('uploadId', $item);
            });
 
 
            if (!empty($attachments)) {
                error_log('Attachments: '.print_r($attachments, true));
                return $this->queueMetaUpdate($attachments, absint($data['user']), sanitize_text_field($data['id']??''));
            }
 
 
            return $this->sendResponse(
                false,
                ['error_code' => 'missing_identifiers'],
                'Must provide either attachment_ids or operation_id'
            );
 
        } catch (Exception $e) {
            JVB()->error()->log(
                '[UploadRoutes]:handleMetadataUpdate',
                $e->getMessage(),
                [
                    'request_data' => $request->get_params(),
                    'trace' => $e->getTraceAsString()
                ]
            );
 
            return $this->sendResponse(
                false,
                ['error_code' => 'metadata_update_failed'],
                'Metadata update failed: ' . $e->getMessage()
            );
        }
    }
    /**
     * Update metadata directly on completed attachments
     */
    protected function updateMeta(array $data, int $user): WP_REST_Response
    {
        $updated_count = 0;
        $errors = [];
        $ids = [];
        foreach ($data as $info) {
            try {
                $attachment_id = $info['attachmentId'];
                error_log('Updating attachment ID:'.print_r($attachment_id,true));
                $ids[] = $attachment_id;
                unset($info['attachmentId']);
                // Verify attachment exists and user has permission
                if (!$this->verifyAttachmentAccess($attachment_id, $user)) {
                    $errors[] = "No permission to edit attachment {$attachment_id}";
                    continue;
                }
 
                $this->applyMeta($attachment_id, $info);
                $updated_count++;
 
            } catch (Exception $e) {
                $errors[] = "Failed to update attachment {$attachment_id}: " . $e->getMessage();
            }
        }
 
        return $this->sendResponse(
            $updated_count > 0,
            [
                'updated_count' => $updated_count,
                'errors' => $errors,
                'attachment_ids' => $ids
            ],
            $updated_count > 0 ?
                "Updated metadata for {$updated_count} attachment(s)" :
                'No attachments were updated'
        );
    }
    /**
     * Queue metadata update with dependency on upload operation
     */
    protected function queueMetaUpdate(array $data, int $user, ?string $operationId = null): WP_REST_Response
    {
        $queue = JVB()->queue();
        $depends_on = [];
        $errors = [];
        $original = count($data);
        foreach ($data as $uploadID => $info) {
            if (array_key_exists('depends_on', $info) && !in_array($info['depends_on'], $depends_on)) {
                $depends_on[] = $info['depends_on'];
            }
        }
        $queueData = [
            'depends_on' => $depends_on,
        ];
        if ($operationId) {
            $queueData['operation_id'] = $operationId;
        }
        $operationID = $queue->queueOperation(
            'update_image_meta',
            $user,
            $data,
            $queueData
        );
 
        return $this->sendResponse(
            true,
            [
                'operation_id' => $operationID['operation_id']??$operationId,
                'message'       => "Successfully queued ".count($data)." of {$original} meta updates"
            ],
            'Metadata update queued - will apply after upload completes'
        );
    }
 
    /**
     * Process metadata update operation (called by queue processor)
     */
    public function processUploadMeta(WP_Error|array $result, object $operation, array $data): WP_Error|array
    {
        try {
            if (!is_array($operation->depends_on)) {
                $operation->depends_on = [$operation->depends_on];
            }
            $updated_count = 0;
            $errors = [];
            foreach ($operation->depends_on as $dependency) {
                $operationData = JVB()->queue()->getOperation($dependency);
                if (!$operationData || $operationData->state !== 'completed') {
                    throw new Exception('Original upload operation not found or not completed');
                }
 
                $uploadResults = json_decode($operationData->result, true);
                if (!$uploadResults || !$uploadResults['success']) {
                    throw new Exception('Original upload operation failed');
                }
                $attachmentsToUpdate = array_filter($data, function ($item) use ($dependency) {
                    return $item['depends_on'] === $dependency;
                });
 
                $uploadIDToAttachment = $this->buildUploadToAttachmentMapping(
                    array_keys($attachmentsToUpdate),
                    $uploadResults['data']
                );
 
                if (empty($uploadIDToAttachment)) {
                    throw new Exception('No valid upload ID to attachment ID mappings found');
                }
 
                foreach ($uploadIDToAttachment as $uploadId => $attachmentId) {
                    try {
                        $this->applyMeta($attachmentId, $attachmentsToUpdate[$uploadId]);
                        $updated_count++;
                    } catch (Exception $e) {
                        $errors[] = "Upload {$uploadId} (Attachment {$attachmentId}): " . $e->getMessage();
                    }
                }
            }
 
            return [
                'success' => $updated_count > 0,
                'result'    => [
                    'updated_count' => $updated_count,
                    'mappings' => $uploadIDToAttachment,
                    'errors' => $errors,
                    'message' => "Applied metadata to {$updated_count} attachment(s)"
                ]
            ];
 
        } catch (Exception $e) {
            JVB()->error()->log(
                '[UploadRoutes]:processUploadMeta',
                $e->getMessage(),
                [
                    'operation_id' => $operation->id,
                    'original_operation_id' => $data['original_operation_id'] ?? 'unknown'
                ]
            );
 
            return [
                'success'   => false,
                'result'    => $e->getMessage()
            ];
        }
    }
 
    protected function applyMeta(int $attachment_id, array $metadata): void
    {
        // Update alt text
        if (!empty($metadata['image-alt-text'])) {
            update_post_meta($attachment_id, '_wp_attachment_image_alt', sanitize_text_field($metadata['image-alt-text']));
        }
        $postUpdates = [];
        // Update title
        if (!empty($metadata['image-title'])) {
            $postUpdates['post_title'] = $metadata['image-title'];
        }
 
        // Update caption
        if (!empty($metadata['image-caption'])) {
            $postUpdates['post_excerpt'] = sanitize_textarea_field($metadata['image-caption']);
        }
 
        if (!empty($postUpdates)) {
            $postUpdates['ID'] = $attachment_id;
            wp_update_post($postUpdates);
        }
    }
 
    /**
     * Build mapping from frontend upload IDs to WordPress attachment IDs
     */
    protected function buildUploadToAttachmentMapping(array $upload_ids, array $results): array
    {
        $mapping = [];
 
        foreach ($results as $result) {
            if (!isset($result['upload_id']) || !isset($result['attachment_id'])) {
                continue;
            }
 
            $upload_id = $result['upload_id'];
            $attachment_id = $result['attachment_id'];
 
            // Validate that this upload_id was requested
            if (in_array($upload_id, $upload_ids)) {
                $mapping[$upload_id] = $attachment_id;
            }
        }
 
        return $mapping;
    }
 
    /**
     * Verify user has access to attachment
     */
    protected function verifyAttachmentAccess(int $attachment_id, int $user_id): bool
    {
        $attachment = get_post($attachment_id);
 
        if (!$attachment || $attachment->post_type !== 'attachment') {
            return false;
        }
 
        // Check if user owns the attachment or has admin privileges
        return ($attachment->post_author == $user_id) || current_user_can('manage_options');
    }
 
    /**
     * Get field configuration for upload processing
     */
    protected function getFieldConfig(array $data): array
    {
        static $config_cache = [];
 
        $cache_key = md5(json_encode([
            $args['content'] ?? '',
            $args['field_name'] ?? ''
        ]));
 
        if (isset($config_cache[$cache_key])) {
            return $config_cache[$cache_key];
        }
 
        $config = [
            'allowed_types' => null,
            'max_size' => null,
            'convert' => 'webp',
            'quality' => 80,
            'create_thumbnails' => true,
        ];
 
        // Get field definition from registry if available
        if (!empty($args['content']) && !empty($args['field_name'])) {
            $content_type = $args['content'];
            $field_name = $args['field_name'];
            $registrar = Registrar::getInstance($content_type);
            if ($registrar) {
                $content_fields = $registrar->getFields();
                if (array_key_exists($field_name, $content_fields)) {
                    $field_def = $content_fields[$field_name];
 
                    // Extract relevant config from field definition
                    $config = array_merge($config, [
                        'allowed_types' => $field_def['accepted_types'] ?? null,
                        'max_size' => $field_def['max_size'] ?? null,
                        'convert' => $field_def['convert'] ?? 'webp',
                        'quality' => $field_def['quality'] ?? 80,
                        'create_thumbnails' => $field_def['create_thumbnails'] ?? true,
                    ]);
                }
            }
        }
 
        $config_cache[$cache_key] = $config;
        return $config;
    }
 
 
 
    /**
     * Get files info for error logging
     */
    protected function getFilesInfo(array $files): array
    {
        return [
            'files_count' => is_array($files['name']) ? count($files['name']) : 1,
            'total_size' => is_array($files['size']) ? array_sum($files['size']) : $files['size'],
            'file_types' => is_array($files['type']) ? array_unique($files['type']) : [$files['type']]
        ];
    }
 
    protected function sendResponse(bool $success, array $data = [], string $message = '', string $operation_id = ''): WP_REST_Response
    {
        $response = [
            'success' => $success,
            'message' => $message,
            'data' => $data,
            'timestamp' => current_time('mysql')
        ];
 
        if ($operation_id) {
            $response['operation_id'] = $operation_id;
        }
 
        return $this->success($response);
    }
 
    public function handleGroupingRequest(WP_REST_Request $request): WP_REST_Response
    {
        try {
            $files = $request->get_file_params();
            $args = $this->buildUploadArgs($request);
 
            if (!array_key_exists('user', $args) || $args['user'] === 0){
                return $this->unauthorized();
            }
            if (!array_key_exists('content', $args) || empty($args['content'])) {
                return $this->validationError(['message'=>'Missing required content']);
            }
            if (!array_key_exists('posts', $args) || empty($args['posts'])) {
                return $this->validationError(['message' => 'Missing posts required']);
            }
 
            // Secure files to temporary storage
            $secured_files = $this->secureFiles($files, $args);
 
            if (empty($secured_files['files'])) {
                return $this->error('No valid files to upload');
            }
 
            // Queue file upload operation
            $operation_type = $this->determineOperationType($secured_files['files'][0] ?? []);
            $chunkSize = 5;
            if ($operation_type === 'video') {
                $chunkSize = 1;
            } elseif ($operation_type === 'document') {
                $chunkSize = 10;
            }
 
            JVB()->queue()->queueOperation(
                $operation_type,
                $args['user'],
                array_merge(
                    ['secured_files' => $secured_files['files']],
                    $args
                ),
                [
                    'operation_id' => $args['upload'],
                    'chunk_key' => 'secured_files',
                    'chunk_size' => $chunkSize
                ]
            );
 
            $ID = JVB()->queue()->queueOperation(
                'process_upload_groups',
                $args['user'],
                $args,
                [
                    'operation_id' => $args['id'],
                    'depends_on' => [$args['upload']],
                    'priority' => 'high',
                    'chunk_key' => 'posts'
                ]
            );
 
            return $this->queued($ID['operation_id'], 'Files uploaded and posts queued for creation');
        } catch (Exception $e) {
            JVB()->error()->log(
                '[UploadRoutes]:handleGroupingRequest',
                $e->getMessage(),
                [
                    'request_data' => $request->get_params(),
                    'trace' => $e->getTraceAsString()
                ]
            );
            return $this->error('Grouping operation failed: '.$e->getMessage());
        }
    }
}