Jake Vanderwerf
7 days ago 46d681c6b825d21b3f698d793c4e630c687d90ad
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
<?php
namespace JVBase\managers;
 
use JVBase\registrar\Registrar;
use JVBase\base\Site;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class IconsManager
{
    // Static array holding all source instances
    protected static array $instances = [];
 
    // Static storage for all custom icons across sources
    protected static array $customIconsRegistry = [];
 
    // Instance-specific properties
    protected string $source;
    protected array $icons = []; // Icons for THIS source [style => [names]]
    protected Cache $cache;
    protected string $style = 'regular';
    protected array $styles = ['regular', 'bold', 'duotone', 'fill', 'light', 'thin'];
    protected array $customIcons = []; // Custom icons for THIS source
    protected array $map = [];
    protected const MAX_VERSIONS = 5;
 
    /**
     * Factory method - get or create instance for a source
     */
    public static function for(string $source = 'icons'): IconsManager
    {
        if (!isset(self::$instances[$source])) {
            self::$instances[$source] = new self($source);
        }
        return self::$instances[$source];
    }
 
    /**
     * Constructor now takes source parameter
     */
    private function __construct(string $source)
    {
        $this->source = $source;
        $this->cache = Cache::for('icons_' . $source, WEEK_IN_SECONDS);
        $this->style = Site::icon();
 
        $this->addMap();
 
        // Register custom icons only once for all sources
        if ($source === 'icons') {
            $this->registerCustomIcons();
        }
 
        // Load custom icons for THIS source
        $this->loadCustomIconsForSource();
 
        // Load stored icons for this source
        $this->loadStoredIcons();
 
        if (empty($this->icons)) {
            $this->includeIcons();
        }
 
        // Register global hooks only once (first instance)
        if (count(self::$instances) === 1) {
            $this->registerGlobalHooks();
        }
 
        // Register instance's hooks (every instance)
        $this->registerInstanceHooks();
    }
 
 
 
    /**
     * Register all custom icons (runs once)
     */
    protected function registerCustomIcons(): void
    {
        $icons = array_merge(apply_filters('jvbRegisterCustomIcons', []), ['syncing' => JVB_DIR . '/assets/icons/cloud-sync-thin.svg',
            'alphabetical' => JVB_DIR . '/assets/icons/alphabetical.svg']);
 
        // Process and store in static property so all instances can access
        self::$customIconsRegistry = $this->processCustomIconsArray($icons);
    }
 
    /**
     * Process custom icons array into source-grouped format
     */
    protected function processCustomIconsArray(array $icons): array
    {
        $out = [];
        foreach ($icons as $name => $source) {
            if (!file_exists($source)) {
                error_log('[IconsManager] No file exists for custom Icon: '.$name);
                continue;
            }
            $out[$name] = $source;
        }
 
        return $out;
    }
 
    /**
     * Load custom icons for this instance's source
     */
    protected function loadCustomIconsForSource(): void
    {
        $this->customIcons = self::$customIconsRegistry;
//      foreach ($this->customIcons as $name => $path) {
//          if (!isset($this->icons[$this->style])) {
//              $this->icons[$this->style] = [];
//          }
//          if (!in_array($name, $this->icons[$this->style])) {
//              $this->icons[$this->style][] = $name;
//          }
//      }
    }
 
    /**
     * Load previously stored icons for this source
     */
    protected function loadStoredIcons(): void
    {
        $allIcons = get_option(BASE.'usedIcons', []);
        $storedIcons = $allIcons[$this->source] ?? [];
 
        // Merge stored icons with any existing icons (like custom icons)
        foreach ($storedIcons as $style => $names) {
            if (!isset($this->icons[$style])) {
                $this->icons[$style] = [];
            }
            $this->icons[$style] = array_unique(array_merge($this->icons[$style], $names));
        }
    }
 
    protected function includeIcons():void
    {
        $defaults = [
            'icons' => [
                'google-logo',
                'apple-logo',
                'check-circle',
                'close-circle',
                'faders-horizontal',
                'cloud-slash',
                'exclamation-mark',
                'cloud-arrow-down',
                'caret-down',
                'cloud-arrow-up',
                'cloud-check',
                'cloud-slash',
                'cloud-warning',
                'syncing',
                'cloud-x',
                'arrows-clockwise',
                'share-fat',
                'trash',
                'star',
                'alphabetical',
                ['name' => 'star-half', 'style' => 'fill'],
                ['name' => 'star', 'style' => 'fill'],
            ],
            'forms' => [
                'copy',
                'paragraph',
                'text-h-one',
                'text-h-two',
                'text-h-three',
                'text-h-four',
                'text-h-five',
                'text-h-six',
                ['name' =>'text-b', 'style' => 'fill'],
                'text-italic',
                'text-underline',
                'text-strikethrough',
                'list-dashes',
                'list-numbers',
                'text-align-left',
                'text-align-center',
                'text-align-right',
//          'text-align-justify',
                'link',
                //FILE ICONS
                'file-pdf',
                'file-csv',
                'file-doc',
                'file-txt',
                'file-xls',
            ],
//          'dash' => [
//
//          ]
        ];
 
 
        // Add icons from content/taxonomy/user configs (like old behavior)
        $configIcons = $this->getIconsFromConfigs();
        if (!empty($configIcons)) {
            $defaults['icons'] = array_merge($defaults['icons'], $configIcons);
        }
 
        // Allow filtering per source (extensibility)
        $icons = apply_filters("jvbIncludeIcons_{$this->source}", $defaults[$this->source] ?? []);
 
        // Also allow filtering all sources at once
        $allIcons = apply_filters('jvbIncludeIcons', $defaults);
        if (isset($allIcons[$this->source])) {
            $icons = array_merge($icons, $allIcons[$this->source]);
        }
        if (!empty($icons)) {
            $this->include($icons);
        }
    }
 
    /**
     * Get icons from Registrar instances
     *
     */
    protected function getIconsFromConfigs(): array
    {
        $icons = [];
        $registered = Registrar::getRegistered();
 
        foreach ($registered as $type) {
            $registrar = Registrar::getInstance($type);
            $icons[] = $registrar->getIcon();
        }
 
 
        return array_unique(array_filter($icons));
    }
 
    /**
     * Public method to include icons in this source
     */
    public function include(array $icons): self
    {
        $processed = $this->processIconArray($icons);
        $changed = false;
 
        foreach ($processed as $style => $names) {
            if (!isset($this->icons[$style])) {
                $this->icons[$style] = [];
            }
 
            foreach ($names as $name) {
                // Skip if already in this source
                if (in_array($name, $this->icons[$style])) {
                    continue;
                }
 
                // Skip if already in main 'icons' source
                if ($this->iconExistsInMainSource($name, $style)) {
                    error_log("[IconsManager] Skipping '{$name}' in '{$this->source}' - already in 'icons' source");
                    continue;
                }
 
                $this->icons[$style][] = $name;
                $changed = true;
            }
        }
 
        // Only save if something actually changed
        if ($changed) {
            $this->saveIcons();
        }
 
        return $this;
    }
 
    /**
     * Process icon array into [style => [names]] format
     */
    protected function processIconArray(array $icons): array
    {
        $out = [];
 
        foreach ($icons as $icon) {
            if (is_array($icon) && isset($icon['style'])) {
                $style = $icon['style'];
                $name = $icon['name'];
            } else {
                $style = $this->style;
                $name = is_array($icon) ? $icon['name'] : $icon;
            }
 
            if (!isset($out[$style])) {
                $out[$style] = [];
            }
 
            if (!in_array($name, $out[$style])) {
                $out[$style][] = $name;
            }
        }
 
        return $out;
    }
 
    /**
     * Save all icons across all instances
     */
    protected function saveIcons(): void
    {
        $allIcons = [];
        foreach (self::$instances as $source => $instance) {
            $allIcons[$source] = $instance->icons;
        }
 
        update_option(BASE.'usedIcons', $allIcons);
 
        // Track WHICH source needs updating
        $needsUpdate = get_option(BASE.'icons_needs_update', []);
        if (!is_array($needsUpdate)) {
            $needsUpdate = [];
        }
        $needsUpdate[$this->source] = true;
        update_option(BASE.'icons_needs_update', $needsUpdate);
    }
 
    /**
     * Check if icon exists in other sources
     */
    protected function checkDuplicateAcrossInstances(string $name, string $style): void
    {
        $foundIn = [];
 
        foreach (self::$instances as $source => $instance) {
            if (isset($instance->icons[$style]) && in_array($name, $instance->icons[$style])) {
                $foundIn[] = $source;
            }
        }
 
        if (count($foundIn) > 1) {
            error_log(sprintf(
                '[IconsManager] Warning: Icon "%s" (%s) is registered in multiple sources: %s. Consider consolidating to avoid duplicate CSS output.',
                $name,
                $style,
                implode(', ', $foundIn)
            ));
        }
    }
 
    protected function addMap(): void
    {
        $map = get_option(BASE.'iconMap');
        if (!$map) {
            $map = [
                'seo'   => 'robot'
            ];
            if (Site::has('referrals')) {
                $map['referrals'] = 'hand-heart';
            }
            if (Site::has('dashboard')) {
                $map['dash'] = 'door';
            }
            if (Site::has('magicLink')) {
                $map['magicLink'] = 'magic-wand';
            }
            if (Site::hasAnyIntegration()) {
                $map['integrations'] = 'plugs-connected';
            }
            update_option(BASE.'iconMap', $map);
        }
 
        $this->map = apply_filters('jvbMapIcons', $map);
    }
 
    /**
     * Register global hooks (only once)
     */
    protected function registerGlobalHooks(): void
    {
        add_action('wp_loaded', [self::class, 'checkCSS']);
        add_action('shutdown', [self::class, 'checkCSS']);
    }
 
    /**
     * Register instance-specific hooks (every instance)
     */
    protected function registerInstanceHooks(): void
    {
        // Register this source's stylesheet
        add_action('init', [$this, 'registerStyle'], 11);
 
        // Auto-enqueue base icons on front-end
        if ($this->source === 'icons') {
            add_action('wp_enqueue_scripts', [$this, 'enqueueIconStyles']);
        }
 
        // Auto-enqueue all in admin
        add_action('admin_enqueue_scripts', [$this, 'enqueueIconStyles']);
    }
 
    public function enqueueIconStyles():void
    {
//      if (file_exists(JVB_CHILD_URL . "assets/css/{$this->source}.css")){
            wp_enqueue_style('jvb-icons-'.$this->source);
//      }
 
    }
 
    public static function checkCSS(): void
    {
        $needsUpdate = get_option(BASE.'icons_needs_update', []);
        if (!empty($needsUpdate)) {
            error_log('Regenerating CSS for sources: ' . implode(', ', array_keys($needsUpdate)));
            delete_option(BASE.'icons_needs_update');
            self::regenerateAllCSS($needsUpdate);
        }
    }
 
    public static function regenerateAllCSS(array $sourcesToUpdate = []): void
    {
        error_log('[IconsManager]:regenerateCSS');
        $css_dir = JVB_CHILD_DIR.'/assets/css/';
 
        if (!file_exists($css_dir)) {
            wp_mkdir_p($css_dir);
        }
 
        // Load all icons from database option
        $allIcons = get_option(BASE.'usedIcons', []);
 
        // If no specific sources provided, regenerate all
        if (empty($sourcesToUpdate)) {
            $sourcesToUpdate = array_fill_keys(array_keys($allIcons), true);
        }
 
        // Generate CSS for each source that needs it
        foreach ($sourcesToUpdate as $source => $needsUpdate) {
            if (!$needsUpdate || !isset($allIcons[$source])) {
                continue;
            }
 
            // Get or create instance for this source
            $instance = self::for($source);
 
            // Temporarily set icons from database
            $originalIcons = $instance->icons;
            $instance->icons = $allIcons[$source];
 
            $css = $instance->generateIconCSS();
            $css_path = $css_dir . $source . '.css';
 
            $instance->archiveCurrentVersion($css);
 
            if (file_put_contents($css_path, $css) !== false) {
                Cache::touch('icons_' . $source);
                error_log("[IconsManager] Updated {$source}.css");
            } else {
                error_log("[IconsManager] Could not write {$source}.css");
            }
 
            // Restore original icons
            $instance->icons = $originalIcons;
        }
    }
 
    protected function regenerateCSS(array $sourcesToUpdate = []): void
    {
        error_log('[IconsManager]:regenerateCSS');
        $css_dir = JVB_CHILD_DIR.'/assets/css/';
 
        if (!file_exists($css_dir)) {
            wp_mkdir_p($css_dir);
        }
 
        // If no specific sources provided, regenerate all
        if (empty($sourcesToUpdate)) {
            $sourcesToUpdate = array_fill_keys(array_keys(self::$instances), true);
        }
 
        // Generate CSS only for sources that need it
        foreach (self::$instances as $source => $instance) {
            if (!isset($sourcesToUpdate[$source])) {
                continue; // Skip this source
            }
 
            $css = $instance->generateIconCSS();
            $css_path = $css_dir . $source . '.css';
 
            // Archive current version before overwriting
            $instance->archiveCurrentVersion($css);
 
            if (file_put_contents($css_path, $css) !== false) {
                Cache::touch('icons_' . $source);
                error_log("[IconsManager] Updated {$source}.css");
            } else {
                error_log("[IconsManager] Could not write {$source}.css");
            }
        }
    }
 
    /**
     * Prevent cloning
     */
    private function __clone() {}
 
    /**
     * Prevent unserialization
     */
    public function __wakeup()
    {
        throw new \Exception("Cannot unserialize singleton");
    }
 
    /**
     * Get an icon element
     *
     * @param string $name Icon name (e.g., 'heart', 'calendar')
     * @param array $options Options array:
     *   - 'style' => 'regular'|'bold'|'fill'|etc.
     *   - 'label' => 'Accessible label' (for standalone icons)
     *   - 'decorative' => true (for icons next to text)
     *   - 'class' => 'additional classes'
     *   - 'size' => 24 (for custom sizing via inline style)
     * @return string HTML icon element
     */
    public function get(string $name, array $options = []): string
    {
        if (empty($name)) {
            //No icon requested
            return '';
        }
        $style = $options['style'] ?? $this->style;
        $name = $this->map[$name] ?? $name;
 
        // Validate icon exists
        if (!$this->iconExists($name, $style)) {
            error_log('[IconsManager] Icon not found: ' . $name);
            return '';
        }
 
        // Track usage - only if not already tracked
        if (!isset($this->icons[$style])) {
            $this->icons[$style] = [];
        }
 
        if (!in_array($name, $this->icons[$style])) {
            // Check if it's already in main source (for non-main sources)
            if ($this->iconExistsInMainSource($name, $style)) {
                // Don't add to this source, but still render the icon
                // The CSS from icons.css will handle it
            } else {
                // Add to this source
                $this->icons[$style][] = $name;
                $this->checkDuplicateAcrossInstances($name, $style);
                $this->saveIcons();
            }
        }
 
        // Build icon HTML (same as before)
        $styleClass = ($style !== $this->style) ? '-'.substr($style, 0, 2) : '';
        $classes = ['icon', 'icon-' . $name.$styleClass];
 
        if (isset($options['class'])) {
            $classes[] = $options['class'];
        }
 
        $attrs = ['class' => implode(' ', $classes)];
 
        if (isset($options['label'])) {
            $attrs['aria-label'] = esc_attr($options['label']);
            $attrs['role'] = 'img';
        } elseif (isset($options['decorative']) && $options['decorative']) {
            $attrs['aria-hidden'] = 'true';
        }
 
        if (isset($options['size'])) {
            $attrs['style'] = sprintf('--icon-size: %dpx;', absint($options['size']));
        }
 
        $attr_string = '';
        foreach ($attrs as $key => $value) {
            $attr_string .= sprintf(' %s="%s"', $key, $value);
        }
 
        return sprintf('<i%s></i>', $attr_string);
    }
 
    /**
     * Check if icon file exists
     */
    protected function iconExists(string $name, ?string $style = null): bool
    {
        if (!$style) {
            $style = $this->style;
        }
        // Check custom icons first
        if (array_key_exists($name, $this->customIcons)) {
            return file_exists($this->customIcons[$name]);
        }
 
        // Check standard icons
        $filepath = $this->buildFilePath($name, $style);
        return file_exists($filepath);
    }
 
    /**
     * Build file path for icon
     */
    protected function buildFilePath(string $name, ?string $style = null): string
    {
        if (!$style) {
            $style = $this->style;
        }
        // Custom icons (absolute path provided)
        if (array_key_exists($name, $this->customIcons)) {
            return $this->customIcons[$name];
        }
 
        // Standard SVG icons in /assets/icons/
        if (str_ends_with($name, '.svg')) {
            return JVB_DIR . '/assets/icons/' . $name;
        }
        $name = ($style === 'regular') ? $name : $name . '-' . $style;
 
        // Phosphor icons with style variants
        return JVB_DIR . '/assets/phosphor-icons/' . $style . '/' . $name . '.svg';
    }
 
    /**
     * Get raw SVG content for CSS mask-image
     */
    public function getRawSvg(string $name, ?string $style = null): ?string
    {
        if (!$style) {
            $style = $this->style;
        }
        $filepath = $this->buildFilePath($name, $style);
 
        if (!file_exists($filepath)) {
            return null;
        }
 
        $svg = file_get_contents($filepath);
        if ($svg === false) {
            return null;
        }
 
        // Clean up SVG for CSS usage
        $svg = preg_replace("/([\n\t]+)/", ' ', $svg);
        $svg = preg_replace('/>\s*</', '><', $svg);
        return trim($svg);
    }
 
    public function registerStyle(): void
    {
        $timestamp = Cache::lastModified('icons_' . $this->source);
        $handle = 'jvb-icons-' . $this->source;
 
        wp_register_style(
            $handle,
            JVB_CHILD_URL . "assets/css/{$this->source}.css",
            [],
            $timestamp
        );
    }
 
    /**
     * Generate CSS from icon list
     */
    protected function generateIconCSS(): string
    {
        $css = '';
 
        foreach ($this->icons as $style => $names) {
            $styleClass = ($style !== $this->style) ? '-'.substr($style, 0, 2) : '';
            foreach ($names as $icon) {
                $svg = $this->getEncodedSVG($icon, $style);
                if ($svg !== '') {
                    if ($icon === 'caret-down') {
                        $css .= 'details summary::after,';
                    } elseif ($icon === 'faders-horizontal') {
                        $css .= 'details.all-filters summary::after,';
                    } elseif ($icon === 'link') {
                        $css .= 'input[type=url],';
                    } elseif ($icon === apply_filters('jvbSeparatorLogo', 'logo')) {
                        $css .= 'hr.logo::before,';
                    }
                    $css .= ".icon-{$icon}{$styleClass}{";
                    $css .= "--icon:url('data:image/svg+xml;base64,{$svg}');";
                    $css .= "}";
                }
            }
        }
 
        return $this->minifyCss($css);
    }
 
    protected function minifyCSS(string $css): string
    {
        // Remove comments
        $css = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $css);
        // Remove whitespace
        $css = preg_replace('/\s+/', ' ', $css);
        // Remove spaces around specific characters
        $css = preg_replace('/\s*([:;{}])\s*/', '$1', $css);
 
        return trim($css);
    }
 
    public function getCSSIcon(string $icon, ?string $style = null): string
    {
        if (!$style) {
            $style = $this->style;
        }
 
        $icon = $this->map[$icon] ?? $icon;
 
        // Validate icon exists
        if (!$this->iconExists($icon, $style)) {
            error_log('[IconsManager] Icon not found: ' . $icon);
            return '';
        }
        $svg = $this->getEncodedSVG($icon, $style);
        if ($svg !== '') {
            return "data:image/svg+xml;base64,{$svg}";
        }
        return '';
    }
 
    public function getEncodedSVG(string $icon, ?string $style = null): string
    {
        if (!$style) {
            $style = $this->style;
        }
        return $this->cache->remember($style.$icon,
            function () use ($icon, $style) {
                $svg = $this->getRawSvg($icon, $style);
                if ($svg) {
                    return base64_encode($svg);
                }
                return '';
            });
    }
 
    /**
     * Clear icon cache (useful for development/debugging)
     */
    public function clearIconCache(): void
    {
        delete_option(BASE . 'icon_usage_list'); // Legacy
        delete_option(BASE.'usedIcons');
        delete_option(BASE.'iconMap');
 
        // Clear cache for all sources
        foreach (self::$instances as $source => $instance) {
            $instance->cache->forget('icon_styles_css');
        }
    }
 
    protected function archiveCurrentVersion(string $css): void
    {
        $history = $this->getVersionHistory();
 
        $icon_count = 0;
        foreach ($this->icons as $style => $names) {
            $icon_count += count($names);
        }
 
        $newEntry = [
            'css' => $css,
            'iconList' => $this->icons,
            'timestamp' => time(),
            'icon_count' => $icon_count,
            'size' => strlen($css),
            'size_formatted' => size_format(strlen($css), 2)
        ];
 
        array_unshift($history, $newEntry);
 
        if (count($history) > self::MAX_VERSIONS) {
            $history = array_slice($history, 0, self::MAX_VERSIONS);
        }
 
        update_option(BASE.'icon_css_history_' . $this->source, $history);
    }
 
    public function getVersionHistory(): array
    {
        return get_option(BASE.'icon_css_history_' . $this->source, []);
    }
 
    public function restoreVersion(int $timestamp): bool
    {
        $history = $this->getVersionHistory();
 
        foreach ($history as $entry) {
            if ($entry['timestamp'] === $timestamp) {
                $css_path = JVB_CHILD_DIR . '/assets/css/' . $this->source . '.css';
 
                // Archive current before restoring
                $current_css = file_get_contents($css_path);
                if ($current_css !== false) {
                    $this->archiveCurrentVersion($current_css);
                }
 
                // Restore the version
                if (file_put_contents($css_path, $entry['css']) !== false) {
                    $this->icons = $entry['iconList'];
                    $this->saveIcons();
                    Cache::touch('icons_' . $this->source);
                    return true;
                }
 
                return false;
            }
        }
 
        error_log("[IconsManager] Version {$timestamp} not found in history for source {$this->source}");
        return false;
    }
 
    public function forceRefresh(): void
    {
        $this->clearIconCache();
        $needsUpdate = get_option(BASE.'icons_needs_update', []);
        if (!is_array($needsUpdate)) {
            $needsUpdate = [];
        }
        $needsUpdate[$this->source] = true;
        update_option(BASE.'icons_needs_update', $needsUpdate);
        Cache::touch('icons_' . $this->source);
    }
 
    public function mergeVersions(array $timestamps): bool
    {
        if (empty($timestamps)) {
            return false;
        }
 
        $history = get_option(BASE.'icon_css_history_' . $this->source, []);
        $merged_icons = [];
 
        // Collect icons from selected versions
        foreach ($history as $entry) {
            if (in_array($entry['timestamp'], $timestamps)) {
                foreach ($entry['iconList'] as $style => $icons) {
                    if (!isset($merged_icons[$style])) {
                        $merged_icons[$style] = [];
                    }
                    // Merge and keep unique
                    $merged_icons[$style] = array_unique(
                        array_merge($merged_icons[$style], $icons)
                    );
                }
            }
        }
 
        if (empty($merged_icons)) {
            error_log('[IconsManager] No icons found in selected versions');
            return false;
        }
 
        // Archive current version
        $current_css = file_get_contents(JVB_CHILD_DIR . '/assets/css/' . $this->source . '.css');
        if ($current_css !== false) {
            $this->archiveCurrentVersion($current_css);
        }
 
        // Update used icons and regenerate
        $this->icons = $merged_icons;
        $this->saveIcons();
 
        return true;
    }
 
    /**
     * Check if icon already exists in the main 'icons' source
     */
    protected function iconExistsInMainSource(string $name, string $style): bool
    {
        // If this IS the main source, no need to check
        if ($this->source === 'icons') {
            return false;
        }
 
        // Check if main icons source exists
        if (!isset(self::$instances['icons'])) {
            return false;
        }
 
        $mainIcons = self::$instances['icons']->icons;
        return isset($mainIcons[$style]) && in_array($name, $mainIcons[$style]);
    }
}