Jake Vanderwerf
2026-07-12 c204185ae86a98994f80010abf35a190c9406739
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
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
<?php
namespace JVBase\integrations;
 
use Exception;
use JVBase\managers\Cache;
use JVBase\managers\ErrorHandler;
use JVBase\managers\queue\executors\IntegrationExecutor;
use JVBase\managers\queue\mergers\DefaultMerger;
use JVBase\managers\queue\TypeConfig;
use JVBase\managers\UploadManager;
use JVBase\meta\Form;
use JVBase\meta\Meta;
use JVBase\registrar\helpers\AddIntegrationFields;
use JVBase\registrar\Registrar;
use WP_Error;
use WP_Post;
 
if (!defined('ABSPATH')) {
    exit;
}
 
/**
 * Base Integration Class
 *
 * This abstract class provides the foundation for all external service integrations.
 * Child classes should extend this to implement specific service integrations.
 *
 * @abstract
 * @since 1.0.0
 */
abstract class Integrations
{
    use _Base;
 
    //Flag to allow for custom settings (defaults, etc) for an integration in the dashboard
    public bool $hasExtraOptions = false;
    public bool $hasBatchCreate = false;
    public bool $hasBatchUpdate = false;
    public bool $hasBatchDelete = false;
    public bool $canCreateOnUpdate = false;
 
    /**
     * API Configuration
     * These properties define how the integration connects to external services
     */
    protected string|array $apiBase = ''; // Base URL(s) for API endpoints. Array format: ['base' => '', 'auth' => '']
    protected array $apiEndpoints = [];   // Valid endpoint paths for this service
 
    protected int $refresh_interval = 0; //seconds before expiry to refresh tokens. 0 to disable
 
 
    /**
     * Credentials & State
     */
 
    protected string $defaultContent = 'post'; //Default integration content type, is none is set. MUST EXIST as array key in $this->>getContentTypes
 
    protected array $allowedContent = [];
 
    /**
     * Caching Configuration
     */
    protected ?string $cacheName = null;
    protected Cache $cache;
    protected array $cacheStrategy = [
        'aggressive' => 3600,  // 1 hour for stable data (e.g., profile info)
        'moderate' => 300,     // 5 minutes for semi-dynamic data (e.g., posts)
        'minimal' => 60,       // 1 minute for frequently changing data
        'none' => 0           // No caching for real-time data
    ];
 
    /**
     * Post Syncing Capabilities
     * Define what sync operations this integration supports
     */
    protected array $canSync = [
        'initial' => false,    // Can share new posts to the service
        'update' => false,     // Can update already-shared posts
        'delete' => false,     // Can remove posts from the service
    ];
    protected array $syncPostTypes = []; // Post types that can be synced (e.g., ['artwork', 'tattoo']): usually built by Registrar.php if the integration name exists as a key in [ 'integrations' => []]
    protected array $syncTaxonomies = []; // Post types that can be synced (e.g., ['artwork', 'tattoo']): usually built by Registrar.php if the integration name exists as a key in [ 'integrations' => []]
    protected array $contentTypes = [];   // Integration's available content types. Set by child classes' getContentTypes
    protected bool $has_content = false; // Whether integration has content that can sync
    /**
     * Error Handling Configuration
     */
    protected array $lastError = [];
    protected array $retryDelays = [1, 2, 5]; // Exponential backoff in seconds
 
 
 
    protected function __construct(?int $userID = null)
    {
        $this->cacheName = $this->cacheName ?: $this->service_name;
        $this->userID = $userID;
        $this->cache = Cache::for('integrations_' . $this->cacheName);
 
        $this->getPostTypes();
        $this->getTaxonomies();
        $this->setContentTypes();
        $this->registerHooks();
 
        if (method_exists($this, 'setQueueTypes')) {
            $this->setQueueTypes();
        }
 
        $this->initializeRateLimiters();
        if (method_exists($this, 'initializeActions')) {
            $this->initializeActions();
        }
        if (method_exists($this, 'addOAuthActions')) {
            $this->addOAuthActions();
        }
 
        add_filter('jvbShouldRenderMeta', [$this, 'checkRenderField'], 10, 4);
    }
        protected function initializeRateLimiters():void
        {
            $key = $this->service_name;
            if (!is_null($this->userID)) {
                $key .= '_'.$this->userID;
            }
 
            if ($this->hasRequests && !isset($this->requestLimiter) && !is_null($this->oauthLimiter)) {
                $this->requestLimiter = new RateLimits($key);
            }
            if ($this->hasOAuth && !isset($this->oauthLimiter) && !is_null($this->oauthLimiter)) {
                $key .= '_oauth';
                $this->oauthLimiter = new RateLimits($key, ['s' => 1,'m' => 10, 'h' => 100]);
            }
        }
 
 
    protected function setContentTypes():void
    {
 
    }
    public function getContentTypes(string $type):array
    {
        return (array_key_exists($type, $this->contentTypes)) ? $this->contentTypes[$type] : $this->contentTypes;
    }
 
    public function checkRenderField($shouldRender, $name, $type, $objectType):bool
    {
        if ($type !== 'form') {
            return $shouldRender;
        }
 
        if (!$this->isSetUp() && str_contains($name, $this->service_name)) {
            return false;
        }
        return $shouldRender;
    }
 
    public function handleOAuthConnect(): array
    {
        if (!$this->hasOAuth) {
            return ['success' => false, 'message' => 'Not an OAuth service'];
        }
 
        // This would typically redirect to OAuth provider
        // Child classes can override for specific behavior
        $auth_url = $this->getOAuthUrl();
 
        if ($auth_url) {
            return [
                'success' => true,
                'redirect' => $auth_url,
            ];
        }
 
        return ['success' => false, 'message' => 'Failed to generate OAuth URL'];
    }
 
    /**
     * Check if OAuth token is valid and not expired
     * @return bool
     */
    public function isOAuthValid(): bool
    {
        if (!$this->isOAuthService) {
            return false;
        }
 
        // Check if we have tokens
        if (empty($this->credentials['access_token'])) {
            return false;
        }
 
        // Check token expiry if stored
        if (!empty($this->credentials['expires_at'])) {
            $expires_at = intval($this->credentials['expires_at']);
            if ($expires_at <= time()) {
                return false;
            }
        }
 
        // For services without expiry info, do a test API call
        return true;
//      return $this->testConnection();
    }
 
 
 
    public function getOAuthUrlAction(array $data = []): array
    {
        if (!$this->isOAuthService) {
            return ['success' => false, 'message' => 'Not an OAuth service'];
        }
 
        $return_url = $data['return_url'] ?? null;
        $auth_url = $this->getOAuthUrl($return_url);
 
        if ($auth_url) {
            return [
                'success' => true,
                'auth_url' => $auth_url,
                'popup' => true
            ];
        }
 
        return ['success' => false, 'message' => 'Failed to generate OAuth URL'];
    }
 
    protected function getPostTypes(): void
    {
        $this->syncPostTypes = Registrar::withIntegration($this->service_name);
    }
 
    protected function getTaxonomies():void
    {
        $key = BASE . $this->service_name . '_sync_taxonomies';
        $taxonomies = get_option($key, false);
 
        if (!$taxonomies) {
            // Combine both content and taxonomy filtering
            $taxonomies = [];
            foreach (Registrar::withFeature('is_content', 'term') as $type) {
                $registrar = Registrar::getInstance($type);
                if ($registrar->hasIntegration($this->service_name)) {
                    $taxonomies[] = $registrar->getSlug();
                }
            }
 
            update_option($key, $taxonomies);
        }
 
        $this->syncTaxonomies = $taxonomies;
    }
 
    protected function getRedirectUri(): string
    {
//      if (!empty($this->oauth['redirect_uri'])) {
//          return $this->oauth['redirect_uri'];
//      }
        if ($this->hasOAuth) {
            return admin_url('admin-ajax.php?action=' . BASE . $this->service_name . '_oauth_callback');
        }
        // Changed from admin-ajax.php to REST endpoint
        return rest_url('jvb/v1/oauth/callback?service=' . $this->service_name);
    }
 
    /**
     * Used by IntegrationsRoutes.php
     * @param string $code
     * @param string $state
     * @return array
     */
    public function handleOAuthCode(string $code, string $state): array
    {
        try {
            $this->loadCredentials();
            $tokens = $this->exchangeOAuthCode($code);
 
            if (!$tokens) {
                return ['success' => false, 'message' => 'Failed to exchange authorization code'];
            }
 
            $credentials = array_merge($this->credentials, $tokens);
            $credentials = $this->addCredentialData($credentials, $tokens);
            $saved = $this->saveCredentials($credentials, false);
 
            if ($saved) {
                return ['success' => true, 'message' => 'Successfully connected'];
            }
 
            return ['success' => false, 'message' => 'Failed to save credentials'];
        } catch (Exception $e) {
            $this->logError('OAuth code exchange failed', ['error' => $e->getMessage()]);
            return ['success' => false, 'message' => 'OAuth error: ' . $e->getMessage()];
        }
    }
 
 
    /*********************************************************************
     * ABSTRACT METHODS - MUST BE IMPLEMENTED BY CHILD CLASSES
     *********************************************************************/
 
    /**
     * Initialize the integration with loaded credentials
     *
     * Called after credentials are loaded. Use this to:
     * - Set up API endpoints with dynamic values (e.g., account IDs)
     * - Initialize service-specific configurations
     * - Validate credentials format
     *
     * @return void
     */
    abstract protected function initialize(): void;
 
 
    /**
     * Render the connection settings form
     *
     * Output HTML form fields for configuring this integration.
     * Use the provided $credentials array to populate existing values.
     *
     * Guidelines:
     * - Use proper escaping (esc_attr, esc_html, etc.)
     * - Include helpful descriptions for each field
     * - Mark required fields clearly
     * - Use appropriate input types (password for secrets, url for endpoints)
     *
     * @param array $credentials Current credentials (may be empty)
     * @return void
     */
//  abstract public function renderConnectionSettings(): void;
 
    /*********************************************************************
     * OPTIONAL OVERRIDE METHODS - IMPLEMENT AS NEEDED
     *********************************************************************/
    /**
     * Save credentials using Auth
     */
    public function saveCredentials(array $credentials, bool $test = true):array
    {
        try {
            // Process and validate credentials
            if (!$this->validateCredentials($credentials)) {
                $this->logError('Invalid credentials');
                return [
                    'success'   => false,
                    'message'   => 'Credentials not formatted correctly'
                ];
            }
 
            $old = $this->getCredentials();
            $credentials = array_merge($old, $credentials);
 
            // Temporarily set credentials for testing
            $this->credentials = $credentials;
            $this->initialize();
 
            // Test the connection before saving
            if ($test) {
                if (!$this->testConnection(true)) {
                    $this->logError('Connection test failed');
                    // Revert to old credentials
                    $this->credentials = $old;
                    $this->initialize();
 
                    return [
                        'success' => false,
                        'message' => 'Connection failed. Please check your credentials.',
                        'test_failed' => true
                    ];
                }
            }
 
 
            // Connection successful, save credentials
            $stored = Auth::getInstance()->storeCredentials(
                $this->service_name,
                $credentials,
                $this->userID
            );
 
            if ($stored) {
                $this->updateLastTestedTime();
                $this->clearCache();
 
                return [
                    'success' => true,
                    'message' => 'Credentials validated and saved successfully',
                    'reload' => true
                ];
            }
 
            return [
                'success' => false,
                'message' => 'Failed to save credentials to database'
            ];
 
        } catch (\Exception $e) {
            // Revert to old credentials on any error
            $old = Auth::getInstance()->getCredentials(
                $this->service_name,
                $this->userID
            );
            $this->credentials = $old;
            $this->initialize();
 
            return [
                'success' => false,
                'message' => 'Validation error: ' . $e->getMessage()
            ];
        }
    }
 
    /**
     * Delete credentials
     */
    public function deleteCredentials():array
    {
        $success = Auth::getInstance()->deleteCredentials($this->service_name, $this->userID);
        return [
            'success'   => $success
        ];
    }
    /**
     * Validate credentials before storing
     *
     * Override to add service-specific validation logic.
     * Check for required fields, format validation, etc.
     *
     * @param array $credentials Credentials to validate
     * @return bool True if valid
     */
    protected function validateCredentials(array $credentials):bool
    {
        // Default: check that credentials is not empty
        if (empty($credentials)) {
            return false;
        }
        return true;
    }
 
    /**
     * Sanitize credentials before storing
     *
     * Override to clean/format credentials before storage.
     * Remove whitespace, normalize URLs, etc.
     *
     * @param array $credentials Raw credentials from form
     * @return array Sanitized credentials
     */
    protected function sanitizeCredentials(array $credentials): array
    {
        $sanitized = [];
        foreach ($credentials as $key => $value) {
            if (is_string($value)) {
                $sanitized[$key] = sanitize_text_field($value);
            } else {
                $sanitized[$key] = $value;
            }
        }
        return $sanitized;
    }
 
    /**
     * Test connection to the external service
     *
     * Override to implement service-specific connection testing.
     * This method includes caching by default.
     *
     * @return bool True if connection successful
     */
    public function testConnection(bool $force = false): bool
    {
        if (!$this->isSetUp()) {
            return false;
        }
        $this->ensureInitialized();
 
        if (empty($this->credentials)) {
            return false;
        }
 
        // Cache test results to avoid excessive API calls
        $cacheKey = "connection_test_$this->service_name" . ($this->userID ? "_$this->userID" : '');
        $cached = $this->cache->get($cacheKey);
 
        if ($cached !== false && !$force) {
            return (bool)$cached;
        }
 
        try {
            if ($this->isOAuthService && !$this->hasOAuthCredentials()){
                //If this is an OAuth service, we might only be saving the app credentials first
                $result = true;
            } else {
                $result = $this->performConnectionTest();
            }
 
            $this->updateLastTestedTime();
            $this->cache->set($cacheKey, $result, 300); // Cache for 5 minutes
            return $result;
        } catch (Exception $e) {
            $this->logError('Connection test failed', ['error' => $e->getMessage()]);
            $this->cache->set($cacheKey, false, 60); // Cache failure for 1 minute
            return false;
        }
    }
 
    protected function clearCache():array
    {
        $this->cache->flush();
        return [
            'success'   => true,
        ];
    }
 
    /**
     * Perform actual connection test
     *
     * Override this method to implement the actual connection test logic.
     * Default implementation returns true if credentials exist.
     *
     * @return bool True if connection successful
     * @throws Exception If connection fails
     */
    protected function performConnectionTest(): bool
    {
        // Override in child class with actual test
        // Example: make a simple API call to verify credentials
        return !empty($this->credentials);
    }
 
    /**
     * Register additional WordPress hooks
     *
     * Override to register service-specific hooks beyond the default ones.
     * Called during construction after base hooks are registered.
     *
     * @return void
     */
    protected function registerAdditionalHooks(): void
    {
        // Override in child classes to add service-specific hooks
    }
 
    /******************************************************************
        POST SYNC
     ******************************************************************/
    /**
     * Handle post save for syncing
     *
     * Override to implement custom sync logic when posts are saved.
     * Check the $settings array for post type specific configuration.
     *
     * @param int $postID The post ID
     * @param WP_Post $post The post object
     * @param bool $update Whether this is an update
     * @param array $settings Post type integration settings
     * @return void
     */
    protected function handleTheSavePost(int $postID, WP_Post $post, bool $update, array $settings): void
    {
        // Override in child classes that support post syncing
        // Example implementation:
        /*
        $fields = $this->getSyncFields($postID, 'post', ['schedule_' . $this->service_name]);
        $options = $fields['schedule_' . $this->service_name] !== ''
            ? ['scheduled' => strtotime($fields['schedule_' . $this->service_name])]
            : [];
 
        $this->queueOperation(
            'sync_post',
            ['post_id' => $postID, 'is_update' => $update],
            $options
        );
        */
    }
 
    /*********************************************************************
     * API REQUEST METHODS
     *********************************************************************/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
    /*********************************************************************
     * SYNC METHODS
     *********************************************************************/
 
    /**
     * Queue a sync operation for processing, utilizing the OperationQueue.php
     *
     * @param string $type Operation type (sync_post, delete_post, etc.)
     * @param array $data Operation data
     * @param array $options Operation options (scheduled time, priority, etc.)
     * @return bool True if queued successfully
     */
    public function queueOperation(
        string $type,
        array $data,
        array $options = []
    ):bool {
        $queue = JVB()->queue();
 
        $queued =  $queue->queueOperation(
            $type,
            $this->userID ?? 0,
            array_merge($data, ['service' => $this->service_name, 'user' => $this->userID??0]),
            array_merge([
                'priority' => 'normal',
                'chunk_key' => $options['batch_field'] ?? null,
                'chunk_size' => $options['batch_size'] ?? 10
            ], $options)
        );
        return (!is_wp_error($queued));
    }
 
    /**
     * The filter called by OperationQueue.php processOperation
     * 1) Test if the operation type is the type we set in queueOperation
     *      I usually do a switch ($operation->type) {
     *          case strtolower($this->service_name. '_update_post'):
     *              return $this->processPostUpdate($data);
     *          default:
     *              return $result;
     *      }
     * 2) Process the data
     * 3) Return an array in this format:
     * [
     *      'success'   => true|false,
     *      'result'    => []//anything we should pass to the operation queue. If we have any dependent operations, it will refer to this data to proceed
     * ]
     * @param WP_Error|array $result
     * @param object $operation
     * @param array $data
     * @return WP_Error|array
     */
    public function processOperation(WP_Error|array $result, object $operation, array $data): WP_Error|array
    {
        return $result;
    }
 
    /*********************************************************************
     * UTILITY METHODS
     *********************************************************************/
 
    /**
     * Register WordPress hooks based on capabilities
     */
    protected function registerHooks(): void
    {
        //Handled by IntegrationExecutor now
//      add_filter(BASE . 'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
 
        if (method_exists($this, 'registerOAuthCallbacks')) {
            $this->registerOAuthCallbacks();
        }
        if (method_exists($this, 'registerWebhookEndpoint')) {
            $this->registerWebhookEndpoint();
        }
        // Let child classes register additional hooks if needed
        $this->registerAdditionalHooks();
 
        if (!empty($this->syncPostTypes) && is_null($this->userID)) {
            $this->addSavePost();
            add_action('transition_post_status', [$this, 'handlePostStatusTransition'], 10, 3);
 
            if ($this->canSync['delete']) {
                add_action('before_delete_post', [$this, 'handleDeletePost'], 10, 1);
            }
        }
        if (!empty($this->syncTaxonomies) && is_null($this->userID)) {
            add_action('saved_term', [$this, 'handleSaveTerm'], 20, 5);
            if ($this->canSync['delete']) {
                add_action('pre_delete_term', [$this, 'handleDeleteTerm'], 10, 2);
            }
        }
 
        add_action('init', [$this, 'registerQueueTypes'], 10);
    }
        public function addSavePost():void
        {
            if (!has_action('save_post', [$this, 'handleSavePost'])) {
                add_action('save_post', [$this, 'handleSavePost'], 20, 3);
            }
        }
        public function removeSavePost():void
        {
            remove_action('save_post', [$this, 'handleSavePost'], 20, 3);
        }
 
 
        public function registerQueueTypes():void
        {
            if (empty($this->syncTaxonomies) && empty($this->syncPostTypes)) {
                return;
            }
            $queue = JVB()->queue();
            $executor = new IntegrationExecutor();
 
            $queue->registry()->register(self::$syncTo, new TypeConfig(
                mergeable: new DefaultMerger('items'),
                executor: $executor,
                chunkKey: 'items',
                chunkSize: 50,
                maxRetries: 3,
            ));
 
            if ($this->canSync['delete']) {
                $queue->registry()->register(self::$deleteFrom, new TypeConfig(
                    mergeable: new DefaultMerger('external_ids'),
                    executor: $executor,
                    chunkKey: 'external_ids',
                    chunkSize: 200,
                    maxRetries: 2
                ));
            }
 
            $queue->registry()->register(self::$syncFrom, new TypeConfig(
                executor: $executor,
                maxRetries: 3
            ));
 
            $this->registerAdditionalQueueTypes($executor);
        }
            protected function registerAdditionalQueueTypes(IntegrationExecutor $executor):void
            {
                //Empty. Integration extensions can register additional operation types from here.
            }
 
    /**
     * Handle connection setup and credential storage
     *
     * @param array $credentials The credentials to save
     * @return array Result with 'success' and 'message' keys
     */
    public function handleConnection(array $credentials): array
    {
        try {
            // Sanitize credentials
            $sanitized = $this->sanitizeCredentials($credentials);
 
            // Validate if needed
            if (method_exists($this, 'validateCredentials')) {
                if (!$this->validateCredentials($sanitized)) {
                    return ['success' => false, 'message' => 'Invalid Credentials'];
                }
            }
 
            // Store credentials
            $this->credentials = array_merge($this->credentials ?? [], $sanitized);
            $this->credentials['last_updated'] = time();
 
            // Save to database
            $saved = $this->saveCredentials($this->credentials);
 
            if (!$saved) {
                return [
                    'success' => false,
                    'message' => 'Failed to save credentials to database'
                ];
            }
 
            // Test connection if method exists
            if (method_exists($this, 'testConnection')) {
                if (!$this->testConnection()) {
                    // Still save but warn about connection
                    return [
                        'success' => true,
                        'message' => 'Credentials saved but connection test failed:'
                    ];
                }
            }
 
            return [
                'success' => true,
                'message' => 'Connection established successfully'
            ];
 
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ];
        }
    }
 
    public function getCredentials(): array
    {
        return $this->loadCredentials();
    }
 
 
 
    public function hasOAuthCredentials(?int $userID = null): bool
    {
        if ($userID !== $this->userID) {
            $this->switchUser($userID);
        }
        return $this->hasOAuth && $this->hasValidOAuth();
    }
 
 
    /**
     * Ensure service is initialized
     */
    protected function ensureInitialized(): void
    {
        if (!$this->isSetUp()){
            return;
        }
        $this->initialize();
    }
 
 
    /***************************************************************
        ERROR HANDLING
     ***************************************************************/
    /**
     * Handle error responses
     */
    protected function handleApiError(int $code, string $body, string $endpoint): void
    {
        $message = "API Error ({$code}): ";
        $decoded = json_decode($body, true);
 
        // Extract error details
        $error_details = $this->extractErrorDetails($decoded, $body);
        $message .= $error_details['message'];
 
        // Determine error severity based on HTTP code
        $severity = $this->getErrorSeverity($code);
 
        // Build comprehensive error context
        $error_context = [
            'service' => $this->service_name,
            'endpoint' => $endpoint,
            'http_code' => $code,
            'error_type' => $this->categorizeApiError($code),
            'error_details' => $error_details,
            'user_id' => $this->userID,
            'request_time' => time(),
            'consecutive_errors' => $this->error_stats['consecutive_errors'],
            'is_oauth' => $this->isOAuthService,
            'api_version' => $this->apiVersion,
            'integration_healthy' => $this->is_healthy
        ];
 
        // Add rate limit information if present
        if ($code === 429) {
            $error_context['rate_limit'] = $this->extractRateLimitInfo($decoded, $body);
        }
 
        // Log to ErrorHandler with proper severity
        $this->logError($message, $error_context, $severity);
 
        // Update error statistics
        $this->updateErrorStats($code, $endpoint);
 
        // Store last error for debugging
        $this->lastError = [
            'code' => $code,
            'message' => $message,
            'endpoint' => $endpoint,
            'timestamp' => time(),
            'context' => $error_context
        ];
    }
 
 
    /*****************************************************************
        OAUTH
     *****************************************************************/
 
    /**
     * Get OAuth authorization URL
     */
    public function getOAuthUrl(?string $return_url = null): string
    {
 
        if (!$this->hasOAuth) {
            return '';
        }
 
        if (empty($this->credentials)) {
            $this->ensureInitialized();
        }
 
        if (empty($this->oauth['authorize'])) {
            $this->logError('OAuth authorize URL not configured');
            return '';
        }
 
        // Build base parameters
        $params = [
            'client_id' => $this->credentials['client_id'] ?? $this->credentials['app_id'] ?? '',
            'redirect_uri' => $this->getRedirectUri(),
            'response_type' => 'code',
            'scope' => implode(' ', $this->oauth['scopes'] ?? [])
        ];
        $state_key = wp_generate_password(32, false);
        $user_id = $this->userID??0;
 
        // Store state data in transient (expires in 10 minutes)
        set_transient(
            'oauth_state_' . $state_key,
            [
                'service' => $this->service_name,
                'user_id' => $user_id,
                'created' => time()
            ],
            600
        );
 
        $state_parts = [
            $state_key,
            $user_id
        ];
 
        // Add return URL if provided
        if ($return_url) {
            $state_parts[] = base64_encode($return_url);
        } else {
            $state_parts[] = base64_encode(admin_url('admin.php?page=jvb-integrations'));
        }
 
        $params['state'] = implode('|', $state_parts);
 
        // Allow child classes to modify params (they can override/remove as needed)
        if (method_exists($this, 'addOAuthParams')) {
            $params = $this->addOAuthParams($params);
        }
 
        return $this->oauth['authorize'] . '?' . http_build_query($params);
    }
 
    /**
     * Add service-specific OAuth parameters
     */
    protected function addOAuthParams(array $params): array
    {
        // Override in child classes to add service-specific params
        // e.g., access_type, prompt, etc.
        return $params;
    }
 
 
 
    /**
     * Extract retry-after header from response
     *
     * @param array|WP_Error $response WordPress HTTP response
     * @return int Seconds to wait before retry
     */
    protected function extractRetryAfter($response): int
    {
        if (is_wp_error($response)) {
            return 5;
        }
 
        $headers = wp_remote_retrieve_headers($response);
 
        if (isset($headers['retry-after'])) {
            // Could be seconds or HTTP date
            $retry_after = $headers['retry-after'];
 
            if (is_numeric($retry_after)) {
                return (int) $retry_after;
            }
 
            // Try to parse as date
            $timestamp = strtotime($retry_after);
            if ($timestamp !== false) {
                return max(0, $timestamp - time());
            }
        }
 
        return 5; // Default wait time
    }
 
    /**
     * Exchange OAuth code for tokens
     */
    protected function exchangeOAuthCode(string $code): ?array
    {
        $this->ensureInitialized();
 
        // Build request data
        $request_data = [
            'client_id' => $this->credentials['client_id'] ?? '',
            'client_secret' => $this->credentials['client_secret'] ?? '',
            'code' => $code,
            'grant_type' => 'authorization_code',
            'redirect_uri' => $this->getRedirectUri()
        ];
 
        $oauth_endpoint = $this->oauth['token'];
        $response = $this->makeOAuthRequest('POST', $oauth_endpoint, $request_data);
 
        if (is_wp_error($response)) {
            $this->logError('OAuth token exchange failed', [
                'error' => $response->get_error_message(),
                'code' => $response->get_error_code()
            ]);
            return null;
        }
 
        // Parse response
        if (isset($response['access_token'])) {
            $expires_in = $response['expires_in'] ?? 2592000; // 30 days default
 
            return [
                'access_token' => $response['access_token'],
                'refresh_token' => $response['refresh_token'] ?? '',
                'expires_in' => $expires_in,
                'expires_at' => time() + $expires_in, // Calculate expiry timestamp
                'token_type' => $response['token_type'] ?? 'Bearer',
                'merchant_id' => $response['merchant_id'] ?? '',
                'scope' => $response['scope'] ?? ''
            ];
        }
 
        $this->logError('Failed to obtain access token', ['response' => $response]);
        return null;
    }
 
    /**
     * Add service-specific credential data
     */
    protected function addCredentialData(array $credentials, array $tokens): array
    {
        // Override in child classes to add service-specific data
        return $credentials;
    }
 
    /**
     * Check if token should be proactively refreshed
     * Different from isOAuthValid() which checks if token is actually expired
     */
    protected function shouldRefreshToken(): bool
    {
        if (!$this->hasOAuth || $this->refresh_interval === 0) {
            return false;
        }
 
        // If no expiry info, we can't proactively refresh
        if (empty($this->credentials['expires_at'])) {
            return false;
        }
 
        $expires_at = intval($this->credentials['expires_at']);
        $time_until_expiry = $expires_at - time();
 
        // Refresh if we're within the refresh interval window
        return $time_until_expiry > 0 && $time_until_expiry <= $this->refresh_interval;
    }
    /**
     * Get time until token refresh is recommended
     * Useful for displaying in admin UI
     */
    public function getTimeUntilRefresh(): ?int
    {
        if ($this->refresh_interval === 0 || empty($this->credentials['expires_at'])) {
            return null;
        }
 
        $expires_at = intval($this->credentials['expires_at']);
        $refresh_at = $expires_at - $this->refresh_interval;
        $time_until_refresh = $refresh_at - time();
 
        return max(0, $time_until_refresh);
    }
 
    /**
     * Get token freshness status
     * Returns: 'fresh', 'should_refresh', 'expired', or 'no_expiry_info'
     */
    public function getTokenStatus(): string
    {
        if (!$this->hasOAuth) {
            return 'not_oauth';
        }
 
        if (empty($this->credentials['access_token'])) {
            return 'no_token';
        }
 
        if (empty($this->credentials['expires_at'])) {
            return 'no_expiry_info';
        }
 
        $expires_at = intval($this->credentials['expires_at']);
        $now = time();
 
        if ($expires_at <= $now) {
            return 'expired';
        }
 
        if ($this->shouldRefreshToken()) {
            return 'should_refresh';
        }
 
        return 'fresh';
    }
    /**
     * Refresh OAuth token
     */
    protected function refreshOAuthToken(): bool
    {
        if (!$this->hasOAuth || empty($this->credentials['refresh_token'])) {
            return false;
        }
 
        $request_data = [
            'client_id' => $this->credentials['client_id'],
            'client_secret' => $this->credentials['client_secret'],
            'refresh_token' => $this->credentials['refresh_token'],
            'grant_type' => 'refresh_token'
        ];
 
        $response = $this->makeOAuthRequest('POST', $this->oauth['token'], $request_data);
 
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
 
            if (str_contains($error_message, 'invalid_grant')) {
                $this->logError('OAuth refresh token is invalid - user must re-authorize', [
                    'error' => $error_message
                ], 'critical');
 
                // Mark unhealthy immediately
                $this->error_stats['consecutive_errors'] = $this->error_threshold;
                $this->is_healthy = false;
                $this->saveErrorStats();
            }
 
            $this->logError('Failed to refresh OAuth token for '.$this->service_name, [
                'error' => $error_message
            ]);
            return false;
        }
 
        if (isset($response['access_token'])) {
            $this->credentials['access_token'] = $response['access_token'];
            $this->credentials['expires_at'] = time() + ($response['expires_in'] ?? 2592000); // 30 days
 
            // Note: Some services return the SAME refresh token
            if (isset($response['refresh_token'])) {
                $this->credentials['refresh_token'] = $response['refresh_token'];
            }
 
            $this->saveCredentials($this->credentials);
            return true;
        }
 
        return false;
    }
 
    /**
     * Revoke OAuth access
     */
    public function revokeOAuthAccess(): bool
    {
        if (!$this->hasOAuth || empty($this->oauth['revoke'])) {
            return false;
        }
 
        if (!empty($this->credentials['access_token'])) {
            wp_remote_post($this->oauth['revoke'], [
                'body' => ['token' => $this->credentials['access_token']]
            ]);
        }
 
        return Auth::getInstance()->deleteCredentials($this->service_name, $this->userID);
 
    }
 
    public function handleOAuthDisconnect(): array
    {
        try {
            // Revoke the token with Square using centralized request
            if (!empty($this->credentials['access_token'])) {
                $revoke_data = [
                    'client_id' => $this->credentials['client_id'] ?? '',
                    'access_token' => $this->credentials['access_token']
                ];
 
                // Make revoke request (ignore response as revoke often returns empty)
                $this->makeOAuthRequest('POST', $this->oauth['revoke'], $revoke_data);
            }
 
            // Clear stored credentials (preserve app credentials)
            $this->credentials = [
                'client_id' => $this->credentials['client_id'] ?? '',
                'client_secret' => $this->credentials['client_secret'] ?? '',
                'environment' => $this->credentials['environment'] ?? 'sandbox'
            ];
 
            $this->saveCredentials($this->credentials);
            $this->clearCache();
 
            return [
                'success' => true,
                'message' => 'Successfully disconnected from Square'
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to disconnect: ' . $e->getMessage()
            ];
        }
    }
    /**
     * Generate webhook signature key for services that require it
     * @return string
     */
    protected function generateWebhookSignature(): string
    {
        return wp_generate_password(32, false);
    }
    /**
     * Generate OAuth state parameter
     */
    protected function generateOAuthState(?int $user_id, ?string $return_url = null): string
    {
        $user_id = $user_id ?? 0;
        $state = wp_create_nonce($this->service_name . '_oauth_' . $user_id) . '|' . $user_id;
 
        if ($return_url) {
            $state .= '|' . base64_encode($return_url);
        }
 
        return $state;
    }
 
    protected function getNonce(): string
    {
         return wp_create_nonce($this->service_name . '_oauth_' . $this->userID);
    }
 
    /**
     * Determine return URL after OAuth
     */
    protected function determineReturnUrl(?int $user_id): string
    {
        if ($user_id > 0) {
            return home_url('/dash/integrations/#' . $this->service_name);
        }
 
        return admin_url('admin.php?page=jvb-integrations');
    }
 
 
    /****************************************************************
        POST SYNC
     ****************************************************************/
    /**
     * Get field mapping for a post type
     */
    protected function getFieldMapping(string $post_type): array
    {
        // Apply filter for custom mapping
        return apply_filters(
            "jvb_{$this->service_name}_field_mapping",
            [],
            $post_type,
            $this
        );
    }
 
 
    /**
     * Map WordPress fields to service fields
     */
    protected function mapFieldsToService(int $postID, array $mapping): array
    {
        $meta_manager = Meta::forPost($postID);
        $service_data = [];
 
        foreach ($mapping as $wp_field => $service_field) {
            $value = $meta_manager->get($wp_field);
 
            if ($value !== null && $value !== '') {
                $this->setNestedValue($service_data, $service_field, $value);
            }
        }
 
        return apply_filters(
            "jvb_{$this->service_name}_mapped_data",
            $service_data,
            $postID,
            $mapping
        );
    }
 
    /**
     * Set nested array value using dot notation
     */
    protected function setNestedValue(array &$array, string $path, $value): void
    {
        $keys = explode('.', $path);
        $current = &$array;
 
        foreach ($keys as $i => $key) {
            if ($i === count($keys) - 1) {
                $current[$key] = $value;
            } else {
                if (!isset($current[$key])) {
                    $current[$key] = [];
                }
                $current = &$current[$key];
            }
        }
    }
    /**
     * Handle post save
     */
    public function handleSavePost(int $postID, WP_Post $post, bool $update): void
    {
        if (!is_null($this->userID)) {
            return;
        }
        error_log('=== ['.$this->service_name.']::handleSavePost called');
 
        if (!$postID || $postID === 0) {
            return;
        }
        $postType = jvbNoBase($post->post_type);
 
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (wp_is_post_revision($postID)) return;
 
 
        if (empty($this->syncPostTypes) || !in_array(jvbNoBase($postType), $this->syncPostTypes)) {
            error_log('Not handling save for '.$this->service_name.' because there are no syncPostTypes: '.print_r($this->syncPostTypes, true));
            return;
        }
 
        $registrar = Registrar::getInstance($postType);
        if (!$registrar){
            return;
        }
 
        $settings = $registrar->hasIntegration($this->service_name)??null;
        if (!$settings) {
            error_log('Not handling save for '.$this->service_name.' because of no registrar settings');
            return;
        }
 
        $settings = $registrar->getIntegrationConfig($this->service_name);
        if (!$settings){
            error_log('Not handling save for '.$this->service_name.' because of no integration config '.print_r($settings, true));
            return;
        }
 
 
        $fields = $this->getSyncFields($postID, 'post', ['schedule_'.$this->service_name]);
        if (!$fields['share_to_'.$this->service_name]) {
            error_log('Not handling save for '.$this->service_name.' because of no share_to_'.$this->service_name.' '.print_r($fields, true));
            return;
        }
 
        $isShared = isset($fields["_{$this->service_name}_item_id"]);
        if ($update && $isShared && !$fields['_keep_synced_'.$this->service_name]) {
            error_log('Not handling save for '.$this->service_name.' because it is already shared, and not set to keep synced. ');
            return;
        }
 
        if ($post->post_status !== 'publish' && !$isShared) {
            error_log('Not handling save for '.$this->service_name.' because post status is not publish, and it is not already shared.');
            return;
        }
        error_log('==== Sending to integration\'s handleTheSavePost '.$this->service_name.' ====');
        $this->removeSavePost();
        $this->handleTheSavePost($postID, $post, $update, $settings);
        $this->addSavePost();
    }
 
 
    protected function getSyncFields(int $postID, string $type, array $additional = []):array
    {
        $meta = new Meta($postID, $type);
        $fieldsToCheck = [
            'share_to_' . $this->service_name,
            '_keep_synced_' . $this->service_name,
            "_{$this->service_name}_item_id",
            "_{$this->service_name}_last_sync",
            "_{$this->service_name}_shared_at",
            "_{$this->service_name}_sync_status",
            ... $additional
        ];
        return $meta->getAll($fieldsToCheck);
    }
 
    /**
     * Handle post status transitions
     */
    public function handlePostStatusTransition(string $new_status, string $old_status, WP_Post $post): void
    {
        if (empty($this->syncPostTypes)) {
            return;
        }
 
        if (!in_array(jvbNoBase($post->post_type), $this->syncPostTypes)) {
            return;
        }
 
        //Map fields from our custom post types to the fields expected by the integration
        $mappedFields = $this->getFieldMapping($post->post_type);
 
        $fields = $this->getSyncFields($post->ID, 'post', $mappedFields);
 
        // Handle unpublish action
        if ($old_status === 'publish' && $new_status !== 'publish') {
 
            if ($fields["_{$this->service_name}_item_id"] && $this->canSync['delete']) {
                try {
                    $this->queueOperation(
                        'delete_post',
                        [
                            $post,
                            $fields["_{$this->service_name}_item_id"]
                        ]
                    );
                } catch (Exception $e) {
                    $this->logError("Failed to handle unpublish for post {$post->ID}: " . $e->getMessage());
                }
            }
        }
    }
 
    /**
     * Handle post deletion
     */
    public function handleDeletePost(int $postID): void
    {
        if (!$this->canSync['delete']) {
            return;
        }
 
        $post = get_post($postID);
        if (!$post || !in_array($post->post_type, $this->syncPostTypes)) {
            return;
        }
 
        $fields = $this->getSyncFields($postID, 'post');
 
        if ($fields["_{$this->service_name}_item_id"] !== '') {
 
            $this->queueOperation(
                'delete_post',
                [
                    'post_id'   => $post->ID,
                ]
            );
        }
    }
 
    protected function handleSaveTerm($term_id, $tt_id, $taxonomy, $update, $args): void
    {
        $noBase = jvbNoBase($taxonomy);
        if (!in_array($noBase, $this->syncTaxonomies)) {
            return;
        }
        $registrar = Registrar::getInstance($noBase);
        if (!$registrar->hasFeature('is_content')) {
            return;
        }
 
 
        $settings = $registrar->getIntegrationConfig($this->service_name);
        if (!$settings) {
            return;
        }
 
        // Similar sync logic as handleSavePost but for terms
        $this->handleTheTermSave($term_id, $taxonomy, $update, $settings);
    }
 
    protected function handleTheTermSave($term_id, $taxonomy, $update, $settings) {
 
    }
 
 
    /*******************************************************************
     * UTILITIES
     *******************************************************************/
 
    /**
     * Get API URL for endpoint
     */
    protected function getApiUrl(string $endpoint, ?string $baseKey = null): string|false
    {
        if ($this->hasOAuth && in_array($endpoint, $this->oauth)) {
            return $endpoint;
        }
        if (is_array($this->apiBase)) {
            if ($baseKey && array_key_exists($baseKey, $this->apiBase)) {
                $base = $this->apiBase[$baseKey];
            } else {
                $base = ($this->apiBase['base'] ?? reset($this->apiBase));
            }
        } else {
            $base = $this->apiBase;
        }
 
        if (!$base || $base === '') {
            $this->logError('API base URL not configured for {$this->>service_name}');
            return false;
        }
 
        // Handle named endpoints
        if (!$this->isValidEndpoint($endpoint)) {
            $this->logError("{$endpoint} is not a valid endpoint for {$this->service_name}");
            return false;
        }
 
        // Build full URL
        $base = rtrim($base, '/');
        $endpoint = ltrim($endpoint, '/');
 
        return "{$base}/{$endpoint}";
    }
 
    /**
     * Check if an endpoint is valid, supporting both exact matches and patterns
     *
     * @param string $endpoint
     * @return bool
     */
    protected function isValidEndpoint(string $endpoint): bool
    {
        // Remove query parameters for validation
        $endpointPath = parse_url($endpoint, PHP_URL_PATH);
        if ($endpointPath === false) {
            $endpointPath = $endpoint;
        }
 
        foreach ($this->apiEndpoints as $pattern) {
            // Check for exact match first
            if ($endpointPath === $pattern) {
                return true;
            }
 
            if (str_starts_with($endpointPath, $pattern)) {
                return true;
            }
 
            // Check if pattern contains wildcards (indicated by square brackets)
            if (strpos($pattern, '[') !== false) {
                // Convert the pattern to a regex
                $regexPattern = '#^' . str_replace(['[^/]+'], ['[^/]+'], $pattern) . '(?:\?.*)?$#';
                if (preg_match($regexPattern, $endpoint)) {
                    return true;
                }
            }
        }
 
        return false;
    }
 
 
 
    /**
     * Categorize API errors for better tracking
     */
    protected function categorizeApiError(int $code): string
    {
        return match(true) {
            $code >= 400 && $code < 404 => 'client_error',
            $code === 404 => 'not_found',
            $code === 401 => 'authentication',
            $code === 403 => 'authorization',
            $code === 429 => 'rate_limit',
            $code >= 500 && $code < 600 => 'server_error',
            default => 'unknown'
        };
    }
 
    /**
     * Determine error severity based on HTTP code
     */
    protected function getErrorSeverity(int $code): string
    {
        return match(true) {
            $code === 429 => 'warning', // Rate limiting
            $code >= 400 && $code < 500 => 'error', // Client errors
            $code >= 500 => 'critical', // Server errors
            default => 'error'
        };
    }
 
    /**
     * Extract error details from response
     */
    protected function extractErrorDetails($decoded, string $body): array
    {
        $details = [
            'message' => 'Unknown error',
            'code' => null,
            'details' => null
        ];
 
        if ($decoded && isset($decoded['error'])) {
            if (is_array($decoded['error'])) {
                $details['message'] = $decoded['error']['message'] ?? json_encode($decoded['error']);
                $details['code'] = $decoded['error']['code'] ?? null;
                $details['details'] = $decoded['error']['details'] ?? null;
            } else {
                $details['message'] = $decoded['error'];
            }
        } elseif ($decoded && isset($decoded['message'])) {
            $details['message'] = $decoded['message'];
        } elseif (!empty($body)) {
            $details['message'] = $body;
        }
 
        return $details;
    }
 
    /**
     * Extract rate limit information from response
     */
    protected function extractRateLimitInfo($decoded, string $body): array
    {
        $info = [
            'retry_after' => null,
            'limit' => null,
            'remaining' => null,
            'reset' => null
        ];
 
        // Try to extract from decoded response
        if ($decoded) {
            $info['retry_after'] = $decoded['retry_after'] ?? $decoded['retry-after'] ?? null;
            $info['limit'] = $decoded['x-rate-limit-limit'] ?? null;
            $info['remaining'] = $decoded['x-rate-limit-remaining'] ?? null;
            $info['reset'] = $decoded['x-rate-limit-reset'] ?? null;
        }
 
        return $info;
    }
 
    /**
     * Update error statistics
     */
    protected function updateErrorStats(int $code, string $endpoint): void
    {
        $this->error_stats['total_errors']++;
        $this->error_stats['consecutive_errors']++;
 
        // Track error types
        $error_type = $this->categorizeApiError($code);
        if (!isset($this->error_stats['error_types'][$error_type])) {
            $this->error_stats['error_types'][$error_type] = 0;
        }
        $this->error_stats['error_types'][$error_type]++;
 
        // Save stats to cache
        $this->saveErrorStats();
    }
 
 
 
 
    /**
     * Get service name
     */
    public function getServiceName(): string
    {
        return $this->service_name;
    }
 
    public function getTitle():string
    {
        return $this->title;
    }
 
    public static function title():string
    {
        return static::getInstance()->getTitle();
    }
    public static function icon():string
    {
        return static::getInstance()->getIcon();
    }
 
    public static function hasExtraOptions():bool
    {
        return static::getInstance()::$hasExtraOptions;
    }
 
    /*********************************************************************
        RENDERING
     *********************************************************************/
//  public function renderAdditionalOptions()
//  {
//      //Default: nothing.
//  }
 
    /**
     * Render additional action buttons (optional)
     * Override in integration classes that need extra actions
     */
//  public function renderAdditionalActions(): void
//  {
//      // Default: no additional actions
//      // Override in extensions for service-specific actions
//  }
 
    /**
     * Get service description (optional)
     * Override in integration classes for custom descriptions
     */
    public function getServiceDescription(): string
    {
        return "Manage your {$this->getServiceName()} integration settings.";
    }
 
 
    /**
     * Validate webhook signature
     * @param string $payload Raw payload body
     * @param string $signature Signature from headers
     * @param string $secret Secret key
     * @param string $algorithm Algorithm used (default: sha256)
     * @return bool
     */
    protected function verifyWebhookSignature(string $payload, string $signature, string $secret, string $algorithm = 'sha256'): bool
    {
        if (empty($signature) || empty($secret)) {
            return false;
        }
 
        $expected = hash_hmac($algorithm, $payload, $secret);
 
        // Use hash_equals for timing-safe comparison
        return hash_equals($expected, $signature);
    }
 
 
 
 
 
 
    public function renderConnection(bool $return = false):string
    {
 
        if ($this->userID && !JVB()->userCanConnect($this->service_name, $this->userID)) {
            return '';
        }
 
        $meta = Meta::forOptions($this->userID.'_integrations');
        $is_connected = $this->isSetUp();
        $credentials = $this->getCredentials();
 
        $admin_only = $this->isOAuthService ? [
            'client_id',
            'client_secret',
        ] : [];
 
        ob_start();
        ?>
        <form id="<?=$this->service_name?>" class="integration <?php echo $is_connected ? 'connected' : 'disconnected'; ?>"
             data-service="<?php echo esc_attr($this->service_name); ?>">
            <div class="header row x-btw">
                <h3><?php echo esc_html($this->title); ?></h3>
                <div class="setup">
                    <?php if ($is_connected): ?>
                        <span class="indicator connected">●</span>
                        <span class="text">Set Up</span>
                    <?php else: ?>
                        <span class="indicator disconnected">●</span>
                        <span class="text">Not Set Up</span>
                    <?php endif; ?>
                </div>
            </div>
 
            <?php if ($is_connected && array_key_exists('updated_at', $credentials) && $credentials['updated_at'] > 0): ?>
                <div class="meta">
                    <small>Last updated: <?php echo human_time_diff($credentials['updated_at']) . ' ago'; ?></small>
                </div>
            <?php endif; ?>
 
            <?php
            if (!empty($this->instructions)) {
                ?>
                <details>
                    <summary>
                        Instructions
                    </summary>
                    <ol>
                        <?php
                        foreach ($this->instructions as $instruction) {
                            echo '<li>'.$instruction.'</li>';
                        }
                        ?>
                    </ol>
                </details>
                <?php
            }
?>
            <details class="initial-setup"<?= $is_connected?'' : ' open'?>>
                <summary>Initial Setup</summary>
                <?php
                foreach ($this->fields as $name => $config) {
                    if ($is_connected && !empty($credentials[$name])) {
                    if (in_array($name, $admin_only) && !current_user_can('manage_options')) {
                        continue;
                    }
                    ?>
                    <span class="label"><?=$config['label']?>:</span>
                    <code>
                        <?php
                        if (str_contains($name, 'secret')) {
                            for ($i = 1; $i<=strlen($credentials[$name]) - 8; $i++) {
                                echo '*';
                            }
                            echo substr($credentials[$name], -8);
                        } else {
                            echo $credentials[$name];
                        }
                        ?>
                    </code>
                    <?php
                    } else {
                        $config['value'] = $credentials[$name]??'';
                        $config['autocomplete'] = 'off';
                        $config['base'] = $this->service_name.'_';
                        echo Form::render($name, '', $config);
                    }
                }
                if ($this->hasWebhooks) {
                    echo $this->renderWebhookUrl();
                }
                ?>
            </details>
            <?php
 
            if ($this->isOAuthService) {
                $this->renderConnectedOAuthStatus();
            }
 
            ?>
 
            <div class="integration-content">
 
                <?php
 
 
 
                if (!empty($this->advanced)) {
                    ?>
                    <details>
                        <summary>Advanced Settings</summary>
                        <?php
                        foreach ($this->advanced as $name => $config) {
                            $config['value'] = $credentials[$name]??'';
                            $config['base'] = $this->service_name.'_';
                            $config['autocomplete'] = 'off';
                            Form::render($name,null, $config);
                        }
                        ?>
                    </details>
                    <?php
                }
                if (!empty($this->defaults)) {
                    ?>
                    <a href="<?php echo admin_url('admin.php?page=jvb-integration-' . $this->service_name); ?>"
                       class="button">
                        More Settings
                    </a>
                    <?php
                }
                ?>
            </div>
            <div class="actions row x-btw wrap">
                <?php
                foreach ($this->buttons as $action => $label) {
                    if (!$is_connected && $action !== 'save_credentials') {
                        continue;
                    }
                    $title = $confirm = '';
                    switch ($action) {
                        case 'save_credentials':
                            $title = $label;
                            $label = jvbIcon('floppy-disk');
                            break;
                        case 'clear_credentials':
                            $title = $label;
                            $label = jvbIcon('plugs');
                            $confirm = ' data-confirm="Are you sure you want to delete these credentials?"';
                            break;
                        case 'clear_cache':
                            $title = $label;
                            $label = jvbIcon('arrows-clockwise');
                            break;
                    }
                    $title = $title === '' ? '' : ' title ="'.$title.'"';
                    ?>
                    <button type="button" data-action="<?=$action?>"<?=$title?><?=$confirm?>><?=$label?></button>
                    <?php
                }
                ?>
            </div>
        </form>
        <?php
        $result = ob_get_clean();
        if(!$return) {
            echo $result;
        }
        return $result;
    }
 
    protected function renderConnectedOAuthStatus(): void
    {
        if (!$this->isSetup()) {
            return;
        }
        $credentials = $this->getCredentials();
        $hasCredentials = $this->hasOAuthCredentials();
        $returnURL = is_admin() ? admin_url('admin.php?page=jvb-integrations') : (get_the_permalink() ?: home_url());
        ?>
 
        <details <?= $hasCredentials?' open':''?>>
            <summary>
                <?php if ($hasCredentials) { ?>
                    Connected Account
                <?php } else { ?>
                    <div class="oauth-connect">
                        <a href="<?php echo esc_url($this->getOAuthUrl($returnURL)); ?>"
                           class="button button-primary jvb-oauth-connect"
                           data-service="<?php echo esc_attr($this->service_name); ?>">
                            <?php echo jvbIcon($this->icon); ?>
                            Authorize Connection
                        </a>
                    </div>
                <?php } ?>
                <div class="connection-status <?= $hasCredentials ? 'connected' : 'disconnected' ?>">
                    <span class="status-indicator">●</span>
                    <span><?= $hasCredentials ? 'Connected' : 'Not Connected' ?></span>
                </div>
            </summary>
            <label>OAuth Redirect URL:</label>
            <code>
                <?= $this->getRedirectUri(); ?>
            </code>
 
 
        <?php if (!empty($credentials['updated_at'])): ?>
        <div class="oauth-meta">
            <small>Token expires: <?php
                echo isset($credentials['expires_at'])
                    ? human_time_diff($credentials['expires_at'])
                    : 'Never';
                ?></small>
        </div>
        <?php endif;
        // Allow child classes to add service-specific connected UI
        $this->renderOAuthConnectedOptions();
        ?>
        </details>
        <?php
    }
 
    protected function renderOAuthConnectedOptions():void
    {
 
    }
 
 
    /**
     * Update last tested time
     */
    public function updateLastTestedTime(): void
    {
        $cred = Auth::getInstance();
        $cred->updateTested($this->service_name, $this->userID);
    }
 
    public function handleAdminPost(): void
    {
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions');
        }
 
        $service = $this->getServiceName();
 
        // Verify nonce
        $nonce_field = 'jvb_integration_nonce_' . $service;
        $nonce_action = 'jvb_integration_save_' . $service;
        if (!isset($_POST[$nonce_field]) || !wp_verify_nonce($_POST[$nonce_field], $nonce_action)) {
            wp_die('Security check failed');
        }
 
        // Get the action type
        $action_type = sanitize_text_field($_POST['action_type'] ?? 'save');
 
        // Prepare the request in the format handleAjaxRequest expects
        $_REQUEST['action'] = $action_type;
        $_REQUEST['service'] = $service;
 
        // Copy all POST data to REQUEST
        foreach ($_POST as $key => $value) {
            $_REQUEST[$key] = $value;
        }
 
        // Set up for JSON response capture
        ob_start();
 
        try {
            // Call the existing AJAX handler
            $this->handleAjaxRequest();
            $response = ob_get_clean();
 
            // Parse the JSON response
            $result = json_decode($response, true);
 
            if ($result && isset($result['success'])) {
                if ($result['success']) {
                    $message = $result['message'] ?? ucfirst($service) . ' settings saved successfully!';
                    $this->setAdminNotice($message, 'success');
                } else {
                    $message = $result['message'] ?? 'Failed to save ' . ucfirst($service) . ' settings.';
                    $this->setAdminNotice($message, 'error');
                }
            } else {
                // If no proper JSON response, check if connection worked
                if ($action_type === 'test') {
                    $connected = $this->testConnection();
                    $message = $connected ? 'Connection successful!' : 'Connection failed. Please check your credentials.';
                    $this->setAdminNotice($message, $connected ? 'success' : 'error');
                }
            }
        } catch (Exception $e) {
            ob_end_clean();
            $this->setAdminNotice('Error: ' . $e->getMessage(), 'error');
        }
 
        // Redirect back to integrations page
        wp_redirect(admin_url('admin.php?page=jvb-integrations'));
        exit;
    }
 
    /**
     * Set admin notice using transients for redirect
     */
    protected function setAdminNotice(string $message, string $type = 'info'): void
    {
        $notices = get_transient('jvb_admin_notices') ?: [];
        $notices[] = [
            'message' => $message,
            'type' => $type === 'success' ? 'updated' : 'error'
        ];
        set_transient('jvb_admin_notices', $notices, 30);
    }
 
    /**
     * Display admin notices from transient
     */
    public static function displayAdminNotices(): void
    {
        $notices = get_transient('jvb_admin_notices');
 
        if ($notices) {
            foreach ($notices as $notice) {
                ?>
                <div class="notice notice-<?php echo esc_attr($notice['type']); ?> is-dismissible">
                    <p><?php echo esc_html($notice['message']); ?></p>
                </div>
                <?php
            }
            delete_transient('jvb_admin_notices');
        }
    }
 
    public function hasDefaults():bool
    {
        return !empty($this->defaults);
    }
 
    public function renderDefaults():void
    {
        $types = $this->enabledContentTypes();
        if (empty($types)) {
            return;
        }
        $meta = Meta::forOptions($this->userID.'_integrations');
        ?>
        <form>
            <h1><?= $this->title?> Defaults:</h1>
            <p>Find yourself constantly repeating yourself?</p>
            <p>Set defaults for different content types and <?=$this->title?>!</p>
            <?php
            foreach ($this->defaults as $name => $config) {
                $config['required'] = false;
 
                $config['base'] = $this->service_name.'_';
                $config['autocomplete'] = 'off';
                echo Form::render($name, null, $config);
            }
            foreach ($this->syncPostTypes as $type) {
                $registrar = Registrar::getInstance($type);
 
                $icon = $registrar->getIcon();
                $icon = $icon === '' ? jvbDefaultIcon() : $icon;
                ?>
                <details>
                    <summary><?= jvbIcon($icon) ?><?= $registrar->getSingular()?> Defaults</summary>
                    <?php
                    $fields = new AddIntegrationFields($this->service_name);
                    $fields = $fields->getIntegrationFields();
                    foreach($fields as $name=>$c) {
                        $c['required'] = false;
                        if ($c['type'] === 'number') {
                            $c['type'] = 'text';
                            $c['subtype'] = 'number';
                        }
                        if (array_key_exists('description', $c)) {
                            $c['hint'] = $c['description'];
                            unset($c['description']);
                        }
                        echo Form::render($name, null, $c);
                    }
                    ?>
                </details>
                <?php
            }
            ?>
        </form>
        <?php
    }
 
    public function hasContent():bool
    {
        return $this->has_content;
    }
    public function getDefaultContentType():string
    {
        return $this->defaultContent;
    }
 
    public function enabledContentTypes():array
    {
        if (!$this->has_content) {
            return [];
        }
 
        return array_filter(array_map(function($registrar) {
            $registrar = Registrar::getInstance($registrar);
            return $registrar->getIntegration($this->service_name)->getContentType();
        }, Registrar::withIntegration($this->service_name)));
    }
 
    protected function getSupportedImage(int $imgID):int
    {
        //If this integration supports webp, we can just send the original image id
        if ($this->supportsWebp) {
            return $imgID;
        }
        //Test if it is in webp format
        $mimeType = get_post_mime_type($imgID);
        if ($mimeType !== 'image/webp') {
            return $imgID;
        }
 
        //Test if we already have converted this image
        $jpegVersion = get_post_meta($imgID, BASE.'jpeg_version', true);
        if ($jpegVersion !== '' && is_int($jpegVersion)) {
            return $jpegVersion;
        }
        $uploader = new UploadManager();
        $converted = $uploader->convertImageTo($imgID, 'jpeg', 80, false);
        if ($converted && !is_wp_error($converted)) {
            update_post_meta($imgID, BASE . 'jpeg_version', $converted['attachment_id']);
            return $converted['attachment_id'];
        }
 
        return $imgID;
    }
 
 
    public function getAllowedContent():array
    {
        return $this->allowedContent;
    }
 
    /**
     * Used by JVBase\registrar\helpers\AddIntegrationFields.php
     * @return array
     */
    public function getAdditionalFields(?string $content_type = null):array
    {
        return [];
    }
 
    public function getIcon():string
    {
        return $this->icon;
    }
 
 
 
    public function canBatchUpdate():bool
    {
        return $this->hasBatchUpdate;
    }
    public function canBatchCreate():bool
    {
        return $this->hasBatchCreate;
    }
    public function canBatchDelete():bool
    {
        return $this->hasBatchDelete;
    }
}