Jake Vanderwerf
2025-11-23 d7dbe7fee362d587dfc334135d9581b6216a4295
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
<?php
namespace JVBase\managers;
 
use JVBase\utility\Features;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class IconsManager
{
    protected static ?IconsManager $instance = null;
    protected CacheManager $cache;
    protected string $style = 'regular';
    protected array $styles = ['regular', 'bold', 'duotone', 'fill', 'light', 'thin'];
    // Custom icons registered via filter
    protected array $customIcons = [];
    protected array $usedIcons = [];
    protected array $map = [];
    protected const MAX_VERSIONS = 5;
 
    /**
     * Get singleton instance
     */
    public static function getInstance(): IconsManager
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    private function __construct()
    {
        $this->cache = CacheManager::for('icons', WEEK_IN_SECONDS);
 
        $this->style = (array_key_exists('icons', JVB_SITE) && in_array(JVB_SITE['icons'], $this->styles))
            ? JVB_SITE['icons']
            : 'regular';
 
        $this->addMap();
 
        // Allow custom icon registration
        $this->customIcons = apply_filters('jvbRegisterCustomIcons', [
            'syncing'       => JVB_DIR .'/assets/icons/cloud-sync-thin.svg',
            'alphabetical'  => JVB_DIR.'/assets/icons/alphabetical.svg'
        ]);
 
 
        $this->usedIcons = get_option(BASE.'usedIcons', []);
        $this->includeIcons();
        // Track custom icons for CSS generation
        $this->trackCustomIcons();
        // Register hooks only once
        $this->registerHooks();
    }
 
    /**
     * Ensure custom icons are tracked for CSS generation
     */
    protected function trackCustomIcons(): void
    {
        if (empty($this->customIcons)) {
            return;
        }
 
        foreach ($this->customIcons as $name => $path) {
            $this->trackIconUsage($name, $this->style);
        }
    }
 
    /**
     * Include icons via filter (for JS usage, etc.)
     */
    protected function includeIcons():void
    {
        $icons = get_option(BASE.'includeIcons');
 
        if (!$icons) {
            $icons = [
                'check-circle',
                'close-circle',
                'cloud-slash',
                'exclamation-mark',
                'cloud-arrow-down',
                'cloud-arrow-up',
                'cloud-check',
                'cloud-slash',
                'cloud-warning',
                'syncing',
                'cloud-x',
                'arrows-clockwise',
                'share-fat',
                'trash',
                'star',
                ['name' => 'star-half', 'style' => 'fill'],
                ['name' => 'star', 'style' => 'fill'],
                //FORMATTING
                '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',
            ];
 
            $check = [JVB_CONTENT, JVB_TAXONOMY, JVB_USER];
            foreach ($check as $constant) {
                foreach ($constant as $key => $value) {
                    if (array_key_exists('icon', $value) && !in_array($value['icon'], $icons)) {
                        $icons[] = $value['icon'];
                    }
                }
            }
            $icons = apply_filters('jvbIncludeIcons', $icons);
            $icons = $this->maybePrefixIcons($icons);
            update_option(BASE.'includeIcons', $icons);
        }
 
        // Ensure icons are in the correct format (handle legacy data)
        if (!$this->isIconsArrayPrefixed($icons)) {
            $icons = $this->maybePrefixIcons($icons);
            update_option(BASE.'includeIcons', $icons);
        }
 
        $additional = apply_filters('jvbIncludeIcons', []);
        if (!empty($additional)) {
            $additional = $this->maybePrefixIcons($additional);
            $merged = $this->mergeUsedIcons($icons, $additional);
 
            if ($icons != $merged) {
                update_option(BASE.'includeIcons', $merged);
                $icons = $merged;
            }
        }
 
        foreach ($icons as $style => $theIcons) {
            foreach($theIcons as $icon) {
                $this->trackIconUsage($icon, $style);
            }
        }
    }
 
    /**
     * Check if icons array is in the prefixed format [style => [icons]]
     */
    protected function isIconsArrayPrefixed(array $icons): bool
    {
        if (empty($icons)) {
            return true;
        }
 
        // Check if first key is a valid style name
        $first_key = array_key_first($icons);
        if (!in_array($first_key, $this->styles)) {
            return false;
        }
 
        // Check if first value is an array
        return is_array($icons[$first_key]);
    }
 
    protected function maybePrefixIcons(array $icons):array
    {
        $out = [];
        foreach ($icons as $icon) {
            if (is_array($icon) && array_key_exists('style', $icon)) {
                if (!array_key_exists($icon['style'], $out)) {
                    $out[$icon['style']] = [];
                }
                if (!in_array($icon['name'], $out[$icon['style']])) {
                    $out[$icon['style']][] = $icon['name'];
                }
            } elseif(is_array($icon)) {
                $icon = $icon['name'];
            }
            if (!is_array($icon)) {
                if (!array_key_exists($this->style, $out)) {
                    $out[$this->style] = [];
                }
                if (!in_array($icon, $out[$this->style])){
                    $out[$this->style][] = $icon;
                }
            }
        }
        return $out;
    }
 
    protected function addMap():void
    {
        $map = get_option(BASE.'iconMap');
        if (!$map) {
            $map = [];
            if (Features::forSite()->has('referrals')){
                $map['referrals'] = 'hand-heart';
            }
            if (Features::forSite()->has('dashboard')){
                $map['dash'] = 'door';
            }
            if (Features::forSite()->has('magicLink')){
                $map['magicLink'] = 'magic-wand';
            }
            if (Features::hasAnyIntegration()) {
                $map['integrations'] = 'plugs-connected';
            }
            update_option(BASE.'iconMap', $map);
        }
 
        $this->map = apply_filters('jvbMapIcons', $map);
    }
 
    /**
     * Register WordPress hooks
     */
    protected function registerHooks(): void
    {
        add_action('init', [$this, 'includeIcons'], 1);
        add_action('init', [$this, 'checkCSS'], 10);
        add_action('wp_enqueue_scripts', [$this, 'enqueueIconStyles']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueIconStyles']);
    }
 
    public function checkCSS():void
    {
//      update_option(BASE.'icons_needs_update', true);
        if (get_option(BASE.'icons_needs_update', false)) {
            error_log('Regenerating CSS');
            delete_option(BASE.'icons_needs_update');
            $this->regenerateCSS();
        }
    }
 
    protected function regenerateCSS(): void
    {
        error_log('[IconsManager]:regenerateCSS');
        $css = $this->generateIconCSS();
        $css_path = JVB_CHILD_DIR.'/assets/css/';
        if (!file_exists($css_path)) {
            wp_mkdir_p($css_path);
        }
        $css_path .= '/icons.css';
 
 
        // Archive current version before overwriting
        $this->archiveCurrentVersion($css);
 
        if (file_put_contents($css_path, $css) !== false) {
            CacheManager::updateTimestamp('icons');
        } else {
            error_log('[IconsManager]Could not write 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 getIcon(string $name, array $options = []): string
    {
        $style = array_key_exists('style', $options) ? $options['style'] :$this->style;
        $name = (array_key_exists($name, $this->map)) ? $this->map[$name] : $name;
 
        // Validate icon exists
        if (!$this->iconExists($name, $style)) {
            error_log('[IconsManager] Icon not found: ' . $name);
            return '';
        }
 
 
 
        // Track icon usage
        $this->trackIconUsage($name, $style);
 
        $styleClass = ($style !== $this->style) ? '-'.substr($style, 0,2) : '';
        // Build classes
        $classes = ['icon', 'icon-' . $name.$styleClass];
        if (!empty($options['class'])) {
            $classes[] = $options['class'];
        }
 
 
        $attrs = ['class="' . esc_attr(implode(' ', $classes)) . '"'];
        $attrs[] = 'aria-hidden="true"';
 
 
 
        return '<i ' . implode(' ', $attrs) . '></i>';
    }
 
    /**
     * Track icon usage for CSS generation
     */
    protected function trackIconUsage(string $name, string $style): void
    {
        $needsUpdate = false;
 
        if (!array_key_exists($style, $this->usedIcons)) {
            $this->usedIcons[$style] = [];
            $needsUpdate = true;
        }
 
        if (!in_array($name, $this->usedIcons[$style])) {
            $this->usedIcons[$style][] = $name;
            $needsUpdate = true;
        }
 
        if ($needsUpdate) {
            // Merge with existing option to never lose icons
            $existing = get_option(BASE.'usedIcons', []);
            $merged = $this->mergeUsedIcons($existing, $this->usedIcons);
            update_option(BASE.'usedIcons', $merged);
 
            // Flag for regeneration on next init
            update_option(BASE.'icons_needs_update', true);
 
            // Clear cache
            $this->cache->delete('icon_styles_css');
        }
    }
 
    /**
     * 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
     */
    protected 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);
        $svg = trim($svg);
 
        return $svg;
    }
 
 
    /**
     * Enqueue icon styles via REST endpoint
     */
    public function enqueueIconStyles(): void
    {
        $timestamp = CacheManager::getTimestamp('icons');
 
        wp_enqueue_style(
            'jvb-icons',
            JVB_CHILD_URL.'assets/css/icons.css',
            [],
            $timestamp
        );
    }
 
    /**
     * Generate CSS from icon list
     */
    protected function generateIconCSS(): string
    {
        $css = '';
        $this->mergeUsedIcons();
 
        foreach ($this->usedIcons as $style => $icons) {
            $styleClass = ($style !== $this->style) ? '-'.substr($style, 0,2) : '';
            foreach ($icons as $icon) {
                $svg = $this->getEncodedSVG($icon, $style);
                if ($svg !== '') {
                    $css .= ".icon-{$icon}{$styleClass}{";
                    $css .= "--icon:url('data:image/svg+xml;base64,{$svg}');";
                    $css .= "}";
                }
            }
        }
        return $this->minifyCss($css);
    }
 
    protected function mergeUsedIcons(array|bool $oldIcons = true, array|bool $newIcons = true):array
    {
        $set = false;
        if ($oldIcons === true) {
            $oldIcons = $this->usedIcons;
            $set = true;
        }
        if ($newIcons === true) {
            $history = $this->getVersionHistory();
            $newIcons = (count($history) > 0) ? $history[0]['iconList'] : [];
        }
        foreach ($newIcons as $style => $icons) {
            if (!isset($oldIcons[$style])) {
                //Style  doesn't exist in previous set, add the whole thing
                $oldIcons[$style] = $icons;
            } else {
                $oldIcons[$style] = array_unique(
                    array_merge($oldIcons[$style], $icons)
                );
            }
        }
        if ($set) {
            $this->usedIcons = $oldIcons;
            update_option(BASE.'usedIcons', $oldIcons);
        }
        return $oldIcons;
    }
 
    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;
        }
        $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'); // Clear DB option
        delete_option(BASE.'usedIcons');
        delete_option(BASE.'includeIcons');
        delete_option(BASE.'iconMap');
        $this->cache->delete('icon_styles_css');
        CacheManager::updateTimestamp('icons');
    }
 
    protected function archiveCurrentVersion(string $css): void
    {
        $history = $this->getVersionHistory();
 
        $icon_count = 0;
        foreach ($this->usedIcons as $style => $icons) {
            $icon_count += count($icons);
        }
 
        $newEntry = [
            'css' => $css,
            'iconList' => $this->usedIcons,
            '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', $history);
    }
 
    public function getVersionHistory(): array
    {
        return get_option(BASE.'icon_css_history', []);
    }
 
    public function restoreVersion(int $timestamp): bool
    {
        $history = $this->getVersionHistory();
 
        foreach ($history as $entry) {
            if ($entry['timestamp'] === $timestamp) {
                $css_path = JVB_DIR . '/assets/css/icons.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->usedIcons = $entry['iconList'];
                    update_option(BASE.'usedIcons', $this->usedIcons);
                    CacheManager::updateTimestamp('icons');
                    return true;
                }
 
                return false;
            }
        }
 
        error_log("[IconsManager] Version {$timestamp} not found in history");
        return false;
    }
 
    public function forceRefresh(): void
    {
        $this->clearIconCache();
        update_option(BASE.'icons_needs_update', true);
        CacheManager::updateTimestamp('icons');
    }
 
    public function mergeVersions(array $timestamps): bool
    {
        if (empty($timestamps)) {
            return false;
        }
 
        $history = get_option(BASE.'icon_css_history', []);
        $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_DIR . '/assets/css/icons.css');
        if ($current_css !== false) {
            $this->archiveCurrentVersion($current_css);
        }
 
        // Update used icons and regenerate
        $this->usedIcons = $merged_icons;
        update_option(BASE.'usedIcons', $this->usedIcons);
 
        // Force regeneration
        $this->regenerateCSS();
 
        return true;
    }
}