Jake Vanderwerf
2026-07-12 c204185ae86a98994f80010abf35a190c9406739
inc/integrations/Integrations.php
@@ -3,15 +3,17 @@
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\managers\ErrorHandler;
use JVBase\registrar\helpers\AddIntegrationFields;
use JVBase\registrar\Registrar;
use WP_Error;
use WP_Post;
use WP_REST_Request;
use WP_REST_Response;
if (!defined('ABSPATH')) {
   exit;
@@ -28,70 +30,30 @@
 */
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 $service_name;      // Unique identifier for this service (e.g., 'square', 'facebook')
   protected string|array $apiBase = ''; // Base URL(s) for API endpoints. Array format: ['base' => '', 'auth' => '']
   protected array $apiEndpoints = [];   // Valid endpoint paths for this service
   protected string $apiVersion = '';     // API version string (e.g., 'v2', '2024-01-01')
   protected int $refresh_interval = 0; //seconds before expiry to refresh tokens. 0 to disable
   /**
    * OAuth Configuration
    * Set these properties if your service uses OAuth authentication
    */
   protected bool $isOAuthService = false;
   protected array $oauth = [
      'authorize' => '',    // OAuth authorization endpoint
      'token' => '',        // Token exchange endpoint
      'revoke' => '',       // Token revocation endpoint (optional)
      'scopes' => [],       // Required OAuth scopes
      'redirect_uri' => '', // OAuth callback URL
   ];
   /**
    * Display Properties
    * Used for UI rendering in admin interfaces
    */
   public string $title;  // Human-readable service name (e.g., 'Google My Business')
   public string $icon;   // Phosphoricons icon slug
   /**
    * Credentials & State
    */
   protected array $credentials = [];      // Service credentials (API keys, tokens, etc.)
   protected ?int $userID = null;          // User context for user-specific integrations
   private bool $token_refresh_attempted = false;  // Circuit breaker for token refresh
   protected array $fields = [];       // The fields to generate that become credentials
   protected array $advanced = [];  // The fields that are optional settings
   protected array $defaults = [];     // Default overrides
   protected string $defaultContent = 'post'; //Default integration content type, is none is set. MUST EXIST as array key in $this->>getContentTypes
   protected array $instructions = []; // Each item in array becomes an item in the list of instructions
   protected bool $supportsWebp = true;
   /**
    * Client Management
    * For services that benefit from persistent connections
    */
   protected ?object $client = null;               // Persistent client instance
   protected array $actions = [
      'save_credentials'   => 'saveCredentials',
      'clear_credentials'  => 'deleteCredentials',
      'clear_cache'     => 'clearCache',
      'test_connection' => 'testConnection',
   ];
   protected array $buttons = [
      'save_credentials' => 'Save Changes',
      'clear_credentials' => 'Clear Credentials',
      'clear_cache'=> 'Clear Cache',
      'test_connection' => 'Test Connection',
   ];
   protected array $allowedContent = [];
@@ -106,24 +68,6 @@
      'minimal' => 60,       // 1 minute for frequently changing data
      'none' => 0           // No caching for real-time data
   ];
   protected int $ttl = 3600; // Default cache TTL in seconds
   /**
    * Rate Limiting Configuration
    * Override these values based on service-specific limits
    */
   protected array $rate_limits = [
      'per_second' => 2,
      'per_minute' => 30,
      'per_hour' => 1000
   ];
   protected array $oauth_rate_limits = [
         'per_second' => 1,    // Max 1 OAuth request per second
         'per_minute' => 10,   // Max 10 OAuth requests per minute
         'per_hour' => 100,    // Max 100 OAuth requests per hour
      ];
   protected array $request_history = [];
   protected int $max_history_size = 100;
   /**
    * Post Syncing Capabilities
@@ -142,63 +86,51 @@
    * Error Handling Configuration
    */
   protected array $lastError = [];
   protected int $maxRetries = 3;
   protected array $retryDelays = [1, 2, 5]; // Exponential backoff in seconds
   /**
    * Validation Rules
    * Define validation rules for credentials and data
    */
   protected array $validationRules = [];
   /**
    * Error tracking properties
    */
   protected array $error_stats = [
      'total_errors' => 0,
      'consecutive_errors' => 0,
      'last_success' => null,
      'error_types' => []
   ];
   protected ?ErrorHandler $errorHandler = null;
   protected int $error_threshold = 5; // Consecutive errors before marking unhealthy
   protected bool $is_healthy = true;
   protected bool $handleWebhooks = false;
   public function __construct(?int $userID = null)
   protected function __construct(?int $userID = null)
   {
      $this->cacheName = $this->cacheName ?: $this->service_name;
      $this->userID = $userID;
      $this->cache = Cache::for('integrations_' . $this->cacheName, $this->ttl);
      // Load error stats from cache
      $this->loadErrorStats();
      $this->cache = Cache::for('integrations_' . $this->cacheName);
      $this->getPostTypes();
      $this->getTaxonomies();
      $this->setContentTypes();
      $this->registerHooks();
      if ($this->isOAuthService) {
         $this->actions['get_oauth_url'] = 'getOAuthUrlAction';
         $this->actions['connect_oauth'] = 'handleOAuthConnect';
            $this->actions['disconnect_oauth'] = 'handleOAuthDisconnect';
         $this->actions['refresh_token'] = 'refreshOAuthToken';
         $this->buttons['refresh_token'] = 'Refresh OAuth Connection';
         $this->buttons['disconnect_oauth'] = 'Disconnect OAuth';
      if (method_exists($this, 'setQueueTypes')) {
         $this->setQueueTypes();
      }
      if ($this->handleWebhooks) {
         $this->advanced['webhook_signature_key'] = [
            'label' => 'Webhook Signature Key',
            'type' => 'text',
            'subtype' => 'password',
            'placeholder' => 'Enter webhook signature key',
            'hint' => 'Used to verify webhook authenticity (recommended)'
         ];
      $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
   {
@@ -206,7 +138,6 @@
   }
   public function getContentTypes(string $type):array
   {
      return (array_key_exists($type, $this->contentTypes)) ? $this->contentTypes[$type] : $this->contentTypes;
   }
@@ -224,7 +155,7 @@
   public function handleOAuthConnect(): array
   {
      if (!$this->isOAuthService) {
      if (!$this->hasOAuth) {
         return ['success' => false, 'message' => 'Not an OAuth service'];
      }
@@ -294,21 +225,7 @@
   protected function getPostTypes(): void
   {
      $key = BASE . $this->service_name . '_sync_post_types';
      $postTypes = get_option($key, false);
      if (!$postTypes) {
         $postTypes = [];
         foreach (Registrar::getRegistered('post') as $registrar) {
            $registrar = Registrar::getInstance($registrar);
            if ($registrar->hasIntegration($this->service_name)) {
               $postTypes[] = $registrar->getSlug();
            }
         }
         update_option($key, $postTypes);
      }
      $this->syncPostTypes = $postTypes;
      $this->syncPostTypes = Registrar::withIntegration($this->service_name);
   }
   protected function getTaxonomies():void
@@ -319,7 +236,8 @@
      if (!$taxonomies) {
         // Combine both content and taxonomy filtering
         $taxonomies = [];
         foreach (Registrar::getFeatured('is_content', 'term') as $registrar) {
         foreach (Registrar::withFeature('is_content', 'term') as $type) {
            $registrar = Registrar::getInstance($type);
            if ($registrar->hasIntegration($this->service_name)) {
               $taxonomies[] = $registrar->getSlug();
            }
@@ -336,7 +254,7 @@
//    if (!empty($this->oauth['redirect_uri'])) {
//       return $this->oauth['redirect_uri'];
//    }
      if ($this->isOAuthService) {
      if ($this->hasOAuth) {
         return admin_url('admin-ajax.php?action=' . BASE . $this->service_name . '_oauth_callback');
      }
      // Changed from admin-ajax.php to REST endpoint
@@ -374,71 +292,6 @@
      }
   }
   /**
    * @param string $action
    * @param mixed|null $data
    * @return array [
    *       'success'   => {bool},
    *       'message'   => {string} optional message,
    *    'data'      => {mixed} optional data to return
    * ]
    */
   public function processAction(string $action, mixed $data = null):array
   {
      if (!$this->checkCapabilities($action, $this->userID)) {
         $this->logError('User cannot perform this action');
         return [
            'success'   => false,
            'message'   => 'Insufficient permissions'
         ];
      }
      if (!array_key_exists($action, $this->actions)) {
         $this->logError('Attempted action not set up', [
            'action' => $action,
            'stored' => $this->actions,
            'service'   => $this->service_name,
            'method' => 'processAction'
         ]);
         return [
            'success'   => false,
            'message'   => 'Invalid action'
         ];
      }
      if (!method_exists($this, $this->actions[$action])) {
         $this->logError('Attempted method not set up', [
            'attempted' => $this->actions['action'],
            'service'   => $this->service_name,
            'method' => 'processAction'
         ]);
         return [
            'success'   => false,
            'message'   => 'Action not set up'
         ];
      }
      $method = $this->actions[$action];
      // Log the action for debugging
      $this->logDebug("Processing action", [
         'action' => $action,
         'method' => $method,
         'data' => $data
      ]);
      if ($data !== null) {
         $result = $this->$method($data);
      } else {
         $result =  $this->$method();
      }
      if (is_wp_error($result)) {
         return [
            'success' => false,
            'message' => $result->get_error_message()
         ];
      }
      return is_array($result) ? $result : ['success' => true, 'data' => $result];
   }
   /*********************************************************************
    * ABSTRACT METHODS - MUST BE IMPLEMENTED BY CHILD CLASSES
@@ -456,22 +309,6 @@
    */
   abstract protected function initialize(): void;
   /**
    * Get request headers for API calls
    *
    * Return an associative array of headers required for API requests.
    * Common headers include Authorization, Content-Type, Accept, etc.
    *
    * Example:
    * return [
    *     'Authorization' => 'Bearer ' . $this->credentials['access_token'],
    *     'Content-Type' => 'application/json',
    *     'Accept' => 'application/json',
    * ];
    *
    * @return array Associative array of header names and values
    */
   abstract protected function getRequestHeaders(): array;
   /**
    * Render the connection settings form
@@ -494,7 +331,7 @@
    * OPTIONAL OVERRIDE METHODS - IMPLEMENT AS NEEDED
    *********************************************************************/
   /**
    * Save credentials using CredentialsManager
    * Save credentials using Auth
    */
   public function saveCredentials(array $credentials, bool $test = true):array
   {
@@ -533,7 +370,7 @@
         // Connection successful, save credentials
         $stored = CredentialsManager::getInstance()->storeCredentials(
         $stored = Auth::getInstance()->storeCredentials(
            $this->service_name,
            $credentials,
            $this->userID
@@ -557,7 +394,7 @@
      } catch (\Exception $e) {
         // Revert to old credentials on any error
         $old = CredentialsManager::getInstance()->getCredentials(
         $old = Auth::getInstance()->getCredentials(
            $this->service_name,
            $this->userID
         );
@@ -576,7 +413,7 @@
    */
   public function deleteCredentials():array
   {
      $success = CredentialsManager::getInstance()->deleteCredentials($this->service_name, $this->userID);
      $success = Auth::getInstance()->deleteCredentials($this->service_name, $this->userID);
      return [
         'success'   => $success
      ];
@@ -668,9 +505,9 @@
   protected function clearCache():array
   {
      $success = $this->cache->flush();
      $this->cache->flush();
      return [
         'success'   => $success,
         'success'   => true,
      ];
   }
@@ -740,285 +577,18 @@
    * API REQUEST METHODS
    *********************************************************************/
   /**
    * Make an API request with automatic retry and error handling
    * @param string $method
    * @param string $endpoint
    * @param array $data
    * @param string|null $baseKey array key for the $this->apiEndpoints
    * @param array $options
    * @return WP_Error|array
    */
   protected function makeRequest(
      string $method,
      string $endpoint,
      array  $data = [],
      ?string $baseKey = null,
      array  $options = []
   ): array|WP_Error
   {
      if (!$this->is_healthy) {
         return new WP_Error('unhealthy', 'Connection marked unhealthy. Skipping fetch');
      }
      $this->ensureInitialized();
      if (!$this->isSetUp()){
         $this->logError('Connection not setup for '.$this->service_name, [
            'method' => 'makeRequest',
         ]);
         return new WP_Error('Error', 'Connection is not set up to make request');
      }
      // Rate limiting check
      if (!$this->checkRateLimit()) {
         return new WP_Error('rate_limit', 'Rate limit exceeded. Please try again later.');
      }
      $attempt = 0;
      $lastError = null;
      while ($attempt < $this->maxRetries) {
         try {
//          $this->logDebug('[Integrations] Making request to '.$this->service_name);
            $result = $this->executeRequest($method, $endpoint, $data, $baseKey, $options);
            if (!$result) {
               return new WP_Error('Request Error');
            }
            $this->recordRequest($method, $endpoint);
//          $this->logDebug('[Integrations]', [
//             'response' => $result
//          ]);
            // Reset error stats on success
            $this->resetErrorStats();
            return $result;
         } catch (Exception $e) {
            $lastError = $e;
            $this->recordRequest($method, $endpoint);
            $attempt++;
            // Retry with backoff for server errors
            if ($attempt < $this->maxRetries && !$this->isClientError($e)) {
               $delay = pow(2, $attempt) * 1000000; // 2^attempt seconds in microseconds
               $jitter = rand(0, $delay * 0.3); // Add 0-30% jitter
               usleep($delay + $jitter);
            } else {
               break;
            }
         }
      }
      $this->logError('API request failed after retries', [
         'method' => $method,
         'endpoint' => $endpoint,
         'attempts' => $attempt,
         'error' => $lastError ? $lastError->getMessage() : 'Unknown error'
      ]);
      return new WP_Error('api_error', $lastError ? $lastError->getMessage() : 'API request failed');
   }
   /**
    * Execute the actual request
    */
   protected function executeRequest(
      string $method,
      string $endpoint,
      array  $data = [],
      ?string $baseKey = null,
      array  $options = []
   ): ?array
   {
      $args = $this->buildRequestArgs($method, $data, $options);
      $url = $this->getApiUrl($endpoint, $baseKey);
      if (!$url) {
         return null;
      }
//    $this->logDebug("$method request to: $url: ".print_r($args, true));
      // Make the request
      $response = match($method) {
         'GET' => wp_remote_get($url, $args),
         'POST' => wp_remote_post($url, $args),
         'PUT', 'PATCH', 'DELETE' => wp_remote_request($url, array_merge($args, ['method' => $method])),
         default => null
      };
      if (!$response) {
         $this->logError("Unsupported HTTP method $method for $this->service_name");
         return null;
      }
      if (is_wp_error($response)) {
         $this->logError("Error for: $this->service_name in executeRequest", ['message' => $response->get_error_message()]);
         return null;
      }
      $response_code = wp_remote_retrieve_response_code($response);
      $body = wp_remote_retrieve_body($response);
      // Handle 401 - try to refresh token and retry once
      if ($response_code === 401 && $this->isOAuthService && !empty($this->credentials['refresh_token'])) {
         // Avoid infinite retry loop - only retry once
         static $retry_count = 0;
         if ($retry_count === 0) {
            $retry_count++;
//          $this->logDebug('Got 401, attempting token refresh...');
            if ($this->refreshOAuthToken()) {
//             $this->logDebug('Token refreshed successfully, retrying request...');
               // Rebuild request args with new token
               $args = $this->buildRequestArgs($method, $data, $options);
               // Retry the request
               $response = match($method) {
                  'GET' => wp_remote_get($url, $args),
                  'POST' => wp_remote_post($url, $args),
                  'PUT', 'PATCH', 'DELETE' => wp_remote_request($url, array_merge($args, ['method' => $method])),
                  default => null
               };
               if ($response && !is_wp_error($response)) {
                  $response_code = wp_remote_retrieve_response_code($response);
                  $body = wp_remote_retrieve_body($response);
               }
            }
            $retry_count = 0; // Reset for next request
         }
      }
      if ($response_code >= 400) {
         $this->handleApiError($response_code, $body, $endpoint);
      }
      $decoded = json_decode($body, true);
      if (json_last_error() !== JSON_ERROR_NONE) {
         return ['raw_response' => $body];
      }
      $this->updateLastTestedTime();
      return $decoded;
   }
   /**
    * GET request with caching
    */
   protected function getRequest(
      string $endpoint,
      array  $params = [],
      ?string $baseKey = null,
      string $cacheStrategy = 'moderate',
      bool   $force = false
   ): ?array
   {
      $cacheKey = $this->buildCacheKey('GET', $endpoint, $params, $baseKey);
      $ttl = is_int($cacheStrategy)
         ? max(0, $cacheStrategy)
         : ($this->cacheStrategy[$cacheStrategy] ?? $this->ttl);
      if (!$force && $ttl > 0) {
         $cached = $this->cache->get($cacheKey);
         if ($cached !== false) {
//          $this->logDebug("Cache hit for: $cacheKey");
            return $cached;
         }
      }
      $result = $this->makeRequest('GET', $endpoint, $params, $baseKey);
      // Only cache successful responses (not WP_Error and not error objects)
      if ($result && !is_wp_error($result) && !$this->isErrorResponse($result) && $ttl > 0) {
         $this->cache->set($cacheKey, $result, $ttl);
      }
      return $result;
   }
   /**
    * Check if response contains an error
    * Override in child classes for service-specific error detection
    */
   protected function isErrorResponse(array $response): bool
   {
      // Common error patterns across APIs
      return isset($response['error'])
         || isset($response['errors'])
         || isset($response['error_description']);
   }
   /**
    * POST request
    */
   protected function postRequest(string $endpoint, array $data = [], ?string $baseKey = null): ?array
   {
      return $this->makeRequest('POST', $endpoint, $data, $baseKey);
   }
   /**
    * PUT request
    */
   protected function putRequest(string $endpoint, array $data = [], ?string $baseKey = null): ?array
   {
      return $this->makeRequest('PUT', $endpoint, $data, $baseKey);
   }
   /**
    * DELETE request
    */
   protected function deleteRequest(string $endpoint, array $data = [], ?string $baseKey = null): ?array
   {
      return $this->makeRequest('DELETE', $endpoint, $data, $baseKey);
   }
   /**
    * PATCH request
    */
   protected function patchRequest(string $endpoint, array $data = [], ?string $baseKey = null): WP_Error|array
   {
      return $this->makeRequest('PATCH', $endpoint, $data, $baseKey);
   }
   /**
    * Build request arguments
    */
   protected function buildRequestArgs(string $method, array $data, array $options): array
   {
      $args = [
         'method' => $method,
         'headers' => $this->getRequestHeaders(),
         'timeout' => $options['timeout'] ?? 30,
         'sslverify' => $options['sslverify'] ?? true,
         'redirection' => $options['redirection'] ?? 5,
         'blocking' => $options['blocking'] ?? true,
         'compress' => $options['compress'] ?? true,
         'decompress' => $options['decompress'] ?? true,
      ];
      if ($method === 'GET' && !empty($data)) {
         // Add query parameters for GET requests
         $args['body'] = $data;
      } elseif (!empty($data)) {
         $content_type = $args['headers']['Content-Type'] ?? 'application/json';
         if (str_contains($content_type, 'application/json')) {
            $args['body'] = json_encode($data);
         } elseif (str_contains($content_type, 'application/x-www-form-urlencoded')) {
            $args['body'] = http_build_query($data);
         } else {
            $args['body'] = $data;
         }
      }
      return $args;
   }
   /*********************************************************************
    * SYNC METHODS
@@ -1039,11 +609,8 @@
   ):bool {
      $queue = JVB()->queue();
      // Add service prefix to operation type
      $operation_type = strtolower($this->service_name) . '_' . $type;
      $queued =  $queue->queueOperation(
         $operation_type,
         $type,
         $this->userID ?? 0,
         array_merge($data, ['service' => $this->service_name, 'user' => $this->userID??0]),
         array_merge([
@@ -1085,187 +652,89 @@
    *********************************************************************/
   /**
    * Get cache duration based on endpoint
    *
    * @param string $endpoint The API endpoint
    * @return int Cache duration in seconds
    */
   protected function getCacheDuration(string $endpoint): int
   {
      // Override in child classes for endpoint-specific caching
      // Example: user profiles = aggressive, posts = moderate, analytics = minimal
      return $this->ttl;
   }
   /**
    * Check if we're within rate limits
    *
    * @return bool True if within limits
    */
   protected function checkRateLimit(): bool
   {
      $now = time();
      // Clean old history
      $this->request_history = array_filter($this->request_history, function($timestamp) use ($now) {
         return ($now - $timestamp) < 3600; // Keep last hour
      });
      // Trim to max size
      if (count($this->request_history) > $this->max_history_size) {
         $this->request_history = array_slice($this->request_history, -$this->max_history_size);
      }
      // Check limits
      $recent_counts = [
         'second' => 0,
         'minute' => 0,
         'hour' => count($this->request_history)
      ];
      foreach ($this->request_history as $timestamp) {
         if ($now - $timestamp <= 1) $recent_counts['second']++;
         if ($now - $timestamp <= 60) $recent_counts['minute']++;
      }
      if ($recent_counts['second'] >= $this->rate_limits['per_second']) return false;
      if ($recent_counts['minute'] >= $this->rate_limits['per_minute']) return false;
      if ($recent_counts['hour'] >= $this->rate_limits['per_hour']) return false;
      return true;
   }
   protected function checkOAuthRateLimit(): bool
   {
      $cache_key = 'oauth_rate_limit_' . $this->service_name . '_' . $this->userID;
      $attempts = get_transient($cache_key) ?: [];
      $now = time();
      // Clean old attempts
      $attempts = array_filter($attempts, function($timestamp) use ($now) {
         return ($now - $timestamp) < 3600; // Keep last hour
      });
      // Check per-minute limit
      $recent = array_filter($attempts, function($timestamp) use ($now) {
         return ($now - $timestamp) < 60;
      });
      if (count($recent) >= 5) { // Max 5 OAuth attempts per minute
         return false;
      }
      // Add current attempt
      $attempts[] = $now;
      // Save updated attempts
      set_transient($cache_key, $attempts, 3600);
      return true;
   }
   /**
    * Record a request for rate limiting
    *
    * @param string $method HTTP method
    * @param string $endpoint API endpoint
    * @return void
    */
   protected function recordRequest(string $method, string $endpoint): void
   {
      $this->request_history[] = time();
   }
   /**
    * Register WordPress hooks based on capabilities
    */
   protected function registerHooks(): void
   {
      add_filter(BASE . 'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
      add_action( 'wp_ajax_'.BASE.$this->service_name.'_oauth_callback', [$this, 'handleAjaxResponse'] );
      add_action( 'wp_ajax_nopriv_'.BASE.$this->service_name.'_oauth_callback', [$this, 'handleAjaxResponse'] );
      if ($this->handleWebhooks){
      //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)) {
         add_action('save_post', [$this, 'handleSavePost'], 20, 3);
      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)) {
      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 handleAjaxResponse()
   {
      $code = $_GET['code'];
      $state =  $_GET['state'];
      $state_parts = explode('|', $state);
      $state_key = $state_parts[0] ?? '';
      $user_id = intval($state_parts[1] ?? 0);
      $user_id = ($user_id === 0) ? null : $user_id;
      $return_url = isset($state_parts[2]) ? base64_decode($state_parts[2]) : admin_url('admin.php?page=jvb-integrations');
      $state_data = get_transient('oauth_state_' . $state_key);
      if (!$state_data || $state_data['service'] !== $this->service_name) {
         wp_die('Invalid state parameter', 'OAuth Error');
      public function addSavePost():void
      {
         if (!has_action('save_post', [$this, 'handleSavePost'])) {
            add_action('save_post', [$this, 'handleSavePost'], 20, 3);
         }
      }
      // Delete the transient to prevent reuse
      delete_transient('oauth_state_' . $state_key);
      // Handle error from OAuth provider
      if (array_key_exists('error', $_GET)) {
         $error_description = $_GET['error_description'] ?? 'Authorization denied';
         wp_redirect(add_query_arg([
            'error' => 'OAuth authorization denied: ' . $error_description
         ], $return_url));
         exit;
      }
      // Get integration instance
      $integration = JVB()->connect($this->service_name, $user_id);
      if (!$integration) {
         wp_die('Invalid service: ' . esc_html($this->service_name), 'OAuth Error');
      public function removeSavePost():void
      {
         remove_action('save_post', [$this, 'handleSavePost'], 20, 3);
      }
      // Exchange code for tokens
      $result = $integration->handleOAuthCode($code, $state);
      public function registerQueueTypes():void
      {
         if (empty($this->syncTaxonomies) && empty($this->syncPostTypes)) {
            return;
         }
         $queue = JVB()->queue();
         $executor = new IntegrationExecutor();
      // Redirect back with result
      if ($result['success']) {
         wp_redirect(add_query_arg([
            'success' => 'Successfully connected to ' . $integration->title
         ], $return_url));
      } else {
         // Handle failure
         $error_message = $result['message'] ?? 'Failed to complete OAuth authorization';
         $queue->registry()->register(self::$syncTo, new TypeConfig(
            mergeable: new DefaultMerger('items'),
            executor: $executor,
            chunkKey: 'items',
            chunkSize: 50,
            maxRetries: 3,
         ));
         wp_redirect(add_query_arg([
            'error' => $error_message
         ], $return_url));
         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);
      }
      exit;
   }
         protected function registerAdditionalQueueTypes(IntegrationExecutor $executor):void
         {
            //Empty. Integration extensions can register additional operation types from here.
         }
   /**
    * Handle connection setup and credential storage
    *
@@ -1323,45 +792,19 @@
      }
   }
   /**
    * Load credentials from secure storage
    */
   protected function loadCredentials(): void
   {
      $this->credentials = CredentialsManager::getInstance()->getCredentials($this->service_name, $this->userID);
   }
   public function getCredentials(): array
   {
      $this->ensureInitialized();
      return $this->credentials;
      return $this->loadCredentials();
   }
   /**
    * Check if integration is properly configured
    */
   public function isSetUp(): bool
   public function hasOAuthCredentials(?int $userID = null): bool
   {
      if (empty($this->credentials)) {
         $this->loadCredentials();
      if ($userID !== $this->userID) {
         $this->switchUser($userID);
      }
      return !empty($this->credentials);
   }
   public function hasOAuthCredentials(): bool
   {
      if (!$this->isOAuthService){
         return false;
      }
      $required = ['client_id', 'client_secret', 'access_token'];
      foreach ($required as $field) {
         if (empty($this->credentials[$field]) || !is_string($this->credentials[$field]) || $this->credentials[$field] === '') {
            return false;
         }
      }
      return true;
      return $this->hasOAuth && $this->hasValidOAuth();
   }
@@ -1373,87 +816,7 @@
      if (!$this->isSetUp()){
         return;
      }
      if (empty($this->credentials)) {
         $this->loadCredentials();
      }
      if (!empty($this->credentials)) {
         if ($this->isOAuthService && $this->hasOAuthCredentials()) {
            // Check if token is expired first
            if (!$this->isOAuthValid()) {
               // Only attempt refresh once per request
               if (!$this->token_refresh_attempted) {
                  $this->token_refresh_attempted = true;
//                $this->logDebug('OAuth token expired, attempting refresh');
                  if (!$this->refreshOAuthToken()) {
                     $this->logError('Failed to refresh expired OAuth token - stopping execution');
                     // Token refresh failed - DO NOT continue making API requests
                     return;
                  }
               } else {
                  // Already attempted refresh in this request
//                $this->logDebug('Token refresh already attempted, skipping');
                  return;
               }
            }
            // Check if we should proactively refresh (before expiry)
            elseif ($this->shouldRefreshToken() && !$this->token_refresh_attempted) {
               $this->token_refresh_attempted = true;
//             $this->logDebug('OAuth token should be refreshed proactively');
               if (!$this->refreshOAuthToken()) {
                  $this->logError('Failed to proactively refresh OAuth token');
                  // Not critical - token is still valid, so continue
               }
            }
         }
         $this->initialize();
      }
   }
   /**
    * Switch user context
    */
   public function switchUser(int $user_id): void
   {
      if ($this->userID === $user_id) {
         return;
      }
      // Clean up current context
      $this->cleanup();
      // Switch context
      $this->userID = $user_id;
      $this->credentials = [];
      $this->resetTokenRefreshFlag();  // ADD THIS LINE
      $this->ensureInitialized();
   }
   public function getAsUser(int $user_id) {
      return new $this($user_id);
   }
   /**
    * Clean up resources
    */
   protected function cleanup(): void
   {
      // Clear sensitive data
      $this->credentials = [];
      // Clear request history
      $this->request_history = [];
   }
   /**
    * Destructor - ensure cleanup
    */
   public function __destruct()
   {
      $this->cleanup();
      $this->initialize();
   }
@@ -1501,9 +864,6 @@
      // Update error statistics
      $this->updateErrorStats($code, $endpoint);
      // Check if integration should be marked unhealthy
      $this->checkIntegrationHealth();
      // Store last error for debugging
      $this->lastError = [
         'code' => $code,
@@ -1514,57 +874,10 @@
      ];
   }
   /**
    * Check if error is a client error (4xx)
    */
   protected function isClientError(Exception $e): bool
   {
      $code = $e->getCode();
      return $code >= 400 && $code < 500;
   }
   /**
    * Get last error details
    */
   public function getLastError(): array
   {
      return $this->lastError;
   }
   /*****************************************************************
      OAUTH
    *****************************************************************/
   /**
    * Check user capabilities for specific actions
    * Can be overridden by child classes for custom logic
    */
   protected function checkCapabilities(string $action, ?int $userID = null): bool
   {
      // Default: require manage_options for admin actions
      $admin_actions = ['disconnect', 'update_credentials', 'clear_cache'];
      if (in_array($action, $admin_actions)) {
         return current_user_can('manage_options');
      }
      // User-specific actions
      return is_user_logged_in();
   }
   /*****************************************************************
      OAUTH
    *****************************************************************/
   protected function initializeOAuth():void
   {
      $this->oauth = array_merge([
         'authorize' => '',
         'token'     => '',
         'revoke' => '',
         'scopes' => [],
         'redirect_uri' => admin_url('admin-ajax.php?action=' . $this->service_name . '_oauth_callback')
      ], $this->oauth);
   }
   /**
    * Get OAuth authorization URL
@@ -1572,7 +885,7 @@
   public function getOAuthUrl(?string $return_url = null): string
   {
      if (!$this->isOAuthService) {
      if (!$this->hasOAuth) {
         return '';
      }
@@ -1638,119 +951,7 @@
      return $params;
   }
   protected function makeOAuthRequest(string $method, string $url, array $data = []): array|WP_Error
   {
      // Check rate limits before making request
      if (!$this->checkOAuthRateLimit()) {
         // For OAuth, we might want to be more lenient with rate limits
         // since these are critical authentication flows
         $this->logError('OAuth request rate limited, waiting before retry');
         sleep(2); // Brief pause before critical OAuth request
         // Check again after wait
         if (!$this->checkRateLimit()) {
            return new WP_Error(
               'rate_limit',
               'OAuth rate limit exceeded. Please try again in a few moments.'
            );
         }
      }
      // Record the request for rate limiting
      $this->recordRequest($method, $url);
      // Build OAuth-specific headers
      $headers = [
         'Content-Type' => 'application/json',
         'Accept' => 'application/json',
      ];
      // Add API version for services that require it (like Square)
      if (!empty($this->apiVersion)) {
         $headers['Square-Version'] = $this->apiVersion;
      }
      // Build request arguments
      $args = [
         'method' => $method,
         'headers' => $headers,
         'timeout' => 30,
         'sslverify' => true,
         'body' => json_encode($data)
      ];
      // Make the request with retry logic
      $attempt = 0;
      $max_attempts = 2; // Fewer retries for OAuth to avoid code expiry
      while ($attempt < $max_attempts) {
         $attempt++;
         // Make the actual request
         $response = wp_remote_request($url, $args);
         // Check for WordPress errors
         if (is_wp_error($response)) {
            if ($attempt >= $max_attempts) {
               return $response;
            }
            // Wait before retry
            sleep($this->retryDelays[$attempt - 1] ?? 1);
            continue;
         }
         // Get response code and body
         $code = wp_remote_retrieve_response_code($response);
         $body = wp_remote_retrieve_body($response);
         // Parse JSON response
         $data = json_decode($body, true);
         // Check for successful response
         if ($code >= 200 && $code < 300) {
            // Reset error stats on success
            $this->resetErrorStats();
            // Return parsed data
            return $data ?: [];
         }
         // Handle specific OAuth error codes
         if ($code === 401) {
            // Invalid credentials - don't retry
            $this->handleApiError($code, $body, $url);
            return new WP_Error('invalid_credentials', 'Invalid OAuth credentials');
         }
         if ($code === 429) {
            // Rate limited - wait longer before retry
            if ($attempt < $max_attempts) {
               $retry_after = $this->extractRetryAfter($response);
               sleep($retry_after ?: 5);
               continue;
            }
         }
         // Check if we should retry
         if ($attempt >= $max_attempts || $code >= 400 && $code < 500) {
            // Client errors (4xx) typically shouldn't be retried
            $this->handleApiError($code, $body, $url);
            $error_message = $data['error_description'] ??
               $data['error'] ??
               "OAuth request failed with status {$code}";
            return new WP_Error('oauth_error', $error_message, ['code' => $code]);
         }
         // Server error - retry after delay
         sleep($this->retryDelays[$attempt - 1] ?? 1);
      }
      // Shouldn't reach here, but handle it
      return new WP_Error('oauth_error', 'OAuth request failed after retries');
   }
   /**
    * Extract retry-after header from response
@@ -1845,7 +1046,7 @@
    */
   protected function shouldRefreshToken(): bool
   {
      if (!$this->isOAuthService || $this->refresh_interval === 0) {
      if (!$this->hasOAuth || $this->refresh_interval === 0) {
         return false;
      }
@@ -1883,7 +1084,7 @@
    */
   public function getTokenStatus(): string
   {
      if (!$this->isOAuthService) {
      if (!$this->hasOAuth) {
         return 'not_oauth';
      }
@@ -1913,7 +1114,7 @@
    */
   protected function refreshOAuthToken(): bool
   {
      if (!$this->isOAuthService || empty($this->credentials['refresh_token'])) {
      if (!$this->hasOAuth || empty($this->credentials['refresh_token'])) {
         return false;
      }
@@ -1967,7 +1168,7 @@
    */
   public function revokeOAuthAccess(): bool
   {
      if (!$this->isOAuthService || empty($this->oauth['revoke'])) {
      if (!$this->hasOAuth || empty($this->oauth['revoke'])) {
         return false;
      }
@@ -1977,7 +1178,7 @@
         ]);
      }
      return CredentialsManager::getInstance()->deleteCredentials($this->service_name, $this->userID);
      return Auth::getInstance()->deleteCredentials($this->service_name, $this->userID);
   }
@@ -2123,6 +1324,11 @@
    */
   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;
      }
@@ -2131,40 +1337,50 @@
      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;
      }
      if (empty($this->syncPostTypes)) {
         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();
   }
@@ -2272,93 +1488,6 @@
   }
   protected function getTermFieldMapping(string $taxonomy): array
   {
      return apply_filters(
         "jvb_{$this->service_name}_term_field_mapping",
         [],
         $taxonomy,
         $this
      );
   }
   /**
    * Share post to external service (override in child classes)
    */
   protected function sharePost(WP_Post $post): ?string
   {
      throw new Exception('sharePost must be implemented by child class');
   }
   /**
    * Update shared post on external service (override in child classes)
    */
   protected function updateSharedPost(WP_Post $post, string $external_id): void
   {
      throw new Exception('updateSharedPost must be implemented by child class');
   }
   /**
    * Remove post from external service (override in child classes)
    */
   protected function unsharePost(WP_Post $post, string $external_id): void
   {
      throw new Exception('unsharePost must be implemented by child class');
   }
   /**
    * Get sync capabilities
    */
   public function getSyncCapabilities(): array
   {
      return $this->canSync;
   }
   /**
    * Check if a specific sync capability is supported
    */
   public function supportsSyncCapability(string $capability): bool
   {
      return $this->canSync[$capability] ?? false;
   }
   /**
    * Get posts shared to this service
    */
   public function getSharedPosts(array $args = []): array
   {
      $defaults = [
         'post_type' => $this->syncPostTypes,
         'meta_query' => [
            [
               'key' => BASE."_{$this->service_name}_item_id",
               'compare' => 'EXISTS'
            ]
         ],
         'posts_per_page' => -1
      ];
      $args = wp_parse_args($args, $defaults);
      return get_posts($args);
   }
   /**
    * Check if post is shared to this service
    */
   public function isPostShared(int $postID): bool
   {
      $external_id = get_post_meta($postID, BASE."_{$this->service_name}_item_id", true);
      return $external_id !== '';
   }
   /**
    * Get external ID for a post
    */
   public function getPostExternalId(int $postID): ?string
   {
      $external_id = get_post_meta($postID, BASE."_{$this->service_name}_item_id", true);
      return $external_id ?: null;
   }
   /*******************************************************************
    * UTILITIES
@@ -2369,7 +1498,7 @@
    */
   protected function getApiUrl(string $endpoint, ?string $baseKey = null): string|false
   {
      if ($this->isOAuthService && in_array($endpoint, $this->oauth)) {
      if ($this->hasOAuth && in_array($endpoint, $this->oauth)) {
         return $endpoint;
      }
      if (is_array($this->apiBase)) {
@@ -2437,65 +1566,7 @@
      return false;
   }
   /**
    * Build cache key
    */
   protected function buildCacheKey(string $method, string $endpoint, array $params = []): string
   {
      $key_parts = [
         $this->service_name,
         $method,
         $endpoint
      ];
      if ($this->userID) {
         $key_parts[] = "user_{$this->userID}";
      }
      if (!empty($params)) {
         $key_parts[] = md5(serialize($params));
      }
      return implode('_', $key_parts);
   }
   /**
    * Log error message
    */
   protected function logError(string $message, array $context = [], ?string $severity = null): void
   {
      if (!$this->errorHandler) {
         $this->errorHandler = JVB()->error();
      }
      // Determine severity if not provided
      if ($severity === null) {
         $severity = 'error';
      }
      // Add integration-specific context
      $context = array_merge($context, [
         'component' => 'Integration:' . $this->service_name,
         'user_id' => $this->userID,
         'service' => $this->service_name,
         'timestamp' => current_time('mysql'),
         'memory_usage' => memory_get_usage(true),
         'peak_memory' => memory_get_peak_usage(true),
         'integration_health' => [
            'is_healthy' => $this->is_healthy,
            'consecutive_errors' => $this->error_stats['consecutive_errors'],
            'total_errors' => $this->error_stats['total_errors'],
            'last_success' => $this->error_stats['last_success']
         ]
      ]);
      // Log through ErrorHandler
      $this->errorHandler->log(
         'Integration:' . $this->service_name,
         $message,
         $context,
         $severity
      );
   }
   /**
    * Categorize API errors for better tracking
@@ -2596,100 +1667,8 @@
      $this->saveErrorStats();
   }
   /**
    * Reset error statistics on successful request
    */
   protected function resetErrorStats(): void
   {
      $this->error_stats['consecutive_errors'] = 0;
      $this->error_stats['last_success'] = time();
      $this->is_healthy = true;
      $this->saveErrorStats();
   }
   /**
    * Get integration health status
    */
   public function getHealthStatus(): array
   {
      return [
         'is_healthy' => $this->is_healthy,
         'consecutive_errors' => $this->error_stats['consecutive_errors'],
         'total_errors' => $this->error_stats['total_errors'],
         'last_success' => $this->error_stats['last_success'],
         'error_types' => $this->error_stats['error_types'],
         'threshold' => $this->error_threshold
      ];
   }
   /**
    * Manually reset integration health
    */
   public function resetHealth(): void
   {
      $this->error_stats = [
         'total_errors' => 0,
         'consecutive_errors' => 0,
         'last_success' => time(),
         'error_types' => []
      ];
      $this->is_healthy = true;
      $this->saveErrorStats();
   }
   /**
    * Check integration health based on error patterns
    */
   protected function checkIntegrationHealth(): void
   {
      // Mark unhealthy if too many consecutive errors
      if ($this->error_stats['consecutive_errors'] >= $this->error_threshold) {
         $this->is_healthy = false;
         // Log critical health issue
         $this->logError(
            "Integration marked unhealthy after {$this->error_stats['consecutive_errors']} consecutive errors",
            [
               'error_stats' => $this->error_stats,
               'threshold' => $this->error_threshold
            ],
            'critical'
         );
      }
   }
   /**
    * Load error statistics from cache
    */
   protected function loadErrorStats(): void
   {
      $cache_key = "error_stats_{$this->service_name}_{$this->userID}";
      $cached_stats = $this->cache->get($cache_key);
      if ($cached_stats) {
         $this->error_stats = array_merge($this->error_stats, $cached_stats);
         // Check if integration was marked unhealthy
         if ($this->error_stats['consecutive_errors'] >= $this->error_threshold) {
            $this->is_healthy = false;
         }
      }
   }
   /**
    * Save error statistics to cache
    */
   protected function saveErrorStats(): void
   {
      $cache_key = "error_stats_{$this->service_name}_{$this->userID}";
      $this->cache->set($cache_key, $this->error_stats, 86400); // 24 hours
   }
   protected function logDebug(string $message, array $context = []): void
   {
      error_log('[Integration: '.$this->service_name.']'.$message.': '.print_r($context, true));
   }
   /**
    * Get service name
@@ -2704,6 +1683,20 @@
      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
    *********************************************************************/
@@ -2731,77 +1724,6 @@
      return "Manage your {$this->getServiceName()} integration settings.";
   }
   /**
    * Get service key for consistency
    */
   public function getServiceKey(): string
   {
      return strtolower($this->service_name);
   }
   /**
    * Refresh credentials from storage and re-initialize
    */
   public function refreshCredentials(): void
   {
      $this->credentials = [];
      $this->ensureInitialized();
   }
   /**
    * Enhanced webhook handling with common patterns
    */
   public function handleWebhook(array $payload): bool
   {
      // Log incoming webhook for debugging
      $this->logDebug('Webhook received', [
         'payload_keys' => array_keys($payload),
         'timestamp' => time()
      ]);
      // Validate webhook signature/authenticity
      if (!$this->validateWebhook($payload)) {
         $this->logError('Webhook validation failed', [
            'webhook_type' => 'validation_error',
            'payload_sample' => array_slice($payload, 0, 5) // Log partial payload for debugging
         ], 'warning');
         return false;
      }
      // Check for duplicate processing (idempotency)
      if ($this->isWebhookProcessed($payload)) {
         return true; // Return true to prevent retries
      }
      try {
         // Process the webhook
         $result = $this->processWebhook($payload);
         // Mark as processed if successful
         if ($result) {
            $this->markWebhookProcessed($payload);
            $this->resetErrorStats();
         } else {
            $this->logError('Webhook processing returned false', [
               'webhook_id' => $this->extractWebhookId($payload)
            ], 'warning');
         }
         return $result;
      } catch (Exception $e) {
         $this->logError('Webhook processing failed', [
            'error' => $e->getMessage(),
            'webhook_id' => $this->extractWebhookId($payload),
            'trace' => $e->getTraceAsString()
         ], 'critical');
         // Update error stats
         $this->updateErrorStats($e->getCode() ?: 500, 'webhook');
         $this->checkIntegrationHealth();
         return false;
      }
   }
   /**
    * Validate webhook signature
@@ -2823,110 +1745,14 @@
      return hash_equals($expected, $signature);
   }
   protected function validateWebhook(array $payload):bool
   {
      //Handled by child classes
      return false;
   }
   protected function processWebhook(array $payload):bool
   {
      //Handled by child classes
      return false;
   }
   /**
    * Check if webhook was already processed (prevent duplicates)
    */
   protected function isWebhookProcessed(array $payload): bool
   {
      $webhook_id = $this->extractWebhookId($payload);
      if (!$webhook_id) {
         return false;
      }
      $cache_key = "webhook_processed_{$this->service_name}_{$webhook_id}";
      return $this->cache->get($cache_key) !== null;
   }
   /**
    * Mark webhook as processed
    */
   protected function markWebhookProcessed(array $payload): void
   {
      $webhook_id = $this->extractWebhookId($payload);
      if ($webhook_id) {
         $cache_key = "webhook_processed_{$this->service_name}_{$webhook_id}";
         $this->cache->set($cache_key, time(), 86400); // Store for 24 hours
      }
   }
   /**
    * Extract unique webhook ID (override in child classes)
    */
   protected function extractWebhookId(array $payload): ?string
   {
      // Common patterns - child classes can override
      return $payload['id'] ??
         $payload['event_id'] ??
         $payload['webhook_id'] ??
         md5(serialize($payload));
   }
   /**
    * Register webhook endpoint
    */
   protected function registerWebhookEndpoint(): void
   {
      // Register REST API endpoint for webhooks
      add_action('rest_api_init', function() {
         register_rest_route('jvb/v1', '/webhooks/' . $this->service_name, [
            'methods' => 'POST',
            'callback' => [$this, 'handleWebhookRequest'],
            'permission_callback' => '__return_true', // Webhooks come from external services
         ]);
      });
   }
   /**
    * Handle webhook REST API request
    */
   public function handleWebhookRequest(WP_REST_Request $request): WP_REST_Response
   {
      $payload = $request->get_params();
      $headers = $request->get_headers();
      // Include headers in payload for signature validation
      $payload['_headers'] = $headers;
      $success = $this->handleWebhook($payload);
      return new WP_REST_Response([
         'success' => $success
      ], $success ? 200 : 400);
   }
   protected function renderWebhookUrl(): string
   {
      if (!$this->handleWebhooks || !$this->isSetUp()) {
         return '';
      }
      $webhook_url = rest_url('jvb/v1/webhooks/' . $this->service_name);
      return sprintf(
         '<div class="webhook-info">
            <h4>Webhook URL</h4>
            <code id="webhook-url-%s">%s</code>
            <p class="hint">Add this URL to your %s webhook settings</p>
        </div>',
         esc_attr($this->service_name),
         esc_html($webhook_url),
         esc_html($this->title)
      );
   }
   public function renderConnection(bool $return = false):string
   {
      if ($this->userID && !JVB()->userCanConnect($this->service_name, $this->userID)) {
         return '';
      }
@@ -2944,7 +1770,7 @@
      ?>
      <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 btw">
         <div class="header row x-btw">
            <h3><?php echo esc_html($this->title); ?></h3>
            <div class="setup">
               <?php if ($is_connected): ?>
@@ -3011,7 +1837,7 @@
                  echo Form::render($name, '', $config);
               }
            }
            if ($this->handleWebhooks) {
            if ($this->hasWebhooks) {
               echo $this->renderWebhookUrl();
            }
            ?>
@@ -3055,7 +1881,7 @@
            }
            ?>
         </div>
         <div class="actions row btw wrap">
         <div class="actions row x-btw wrap">
            <?php
            foreach ($this->buttons as $action => $label) {
               if (!$is_connected && $action !== 'save_credentials') {
@@ -3149,26 +1975,14 @@
   }
   /**
    * Get last tested timestamp - extends your existing pattern
    */
   protected function getLastTestedTime(): ?int
   {
      $key = $this->userID
         ? "jvb_integration_{$this->service_name}_last_test_user_{$this->userID}"
         : "jvb_integration_{$this->service_name}_last_test";
      return get_option($key, null);
   }
   /**
    * Update last tested time
    */
   public function updateLastTestedTime(): void
   {
      $key = $this->userID
         ? "jvb_integration_{$this->service_name}_last_test_user_{$this->userID}"
         : "jvb_integration_{$this->service_name}_last_test";
      update_option($key, time());
      $cred = Auth::getInstance();
      $cred->updateTested($this->service_name, $this->userID);
   }
   public function handleAdminPost(): void
@@ -3339,27 +2153,10 @@
         return [];
      }
      $key = BASE.$this->service_name.'_enabled_content_types';
      $enabled = get_option($key);
      if (!$enabled) {
         $enabled = [];
         foreach (Registrar::getRegistered() as $registrar) {
            $registrar = Registrar::getInstance($registrar);
            if (!$registrar->hasIntegration($this->service_name)) {
               continue;
            }
            $type = $registrar->getIntegration($this->service_name)->getContent_type();
            if (!$type) {
               continue;
            }
            if (!in_array($type, $enabled)) {
               $enabled[] = $type;
            }
         }
         update_option($key, $enabled);
      }
      return $enabled;
      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
@@ -3379,155 +2176,16 @@
      if ($jpegVersion !== '' && is_int($jpegVersion)) {
         return $jpegVersion;
      }
      $converted = $this->convertWebpToJpeg($imgID);
      if ($converted) {
         update_post_meta($imgID, BASE . 'jpeg_version', $converted);
         return $converted;
      $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;
   }
   /**
    * Convert WebP image to JPEG
    *
    * @param int $webpAttachmentId
    * @return int|false Image ID on success, false on failure.
    */
   protected function convertWebpToJpeg(int $webpAttachmentId):int|false
   {
      try {
         $webpPath = get_attached_file($webpAttachmentId);
         if (!file_exists($webpPath)) {
            throw new Exception('WebP file not found');
         }
         // Generate JPEG filename
         $pathInfo = pathinfo($webpPath);
         $jpegPath = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '_jpeg.jpg';
         // Check if already exists (shouldn't happen due to meta check, but safety first)
         if (file_exists($jpegPath)) {
            // Try to find existing attachment
            global $wpdb;
            $existingId = $wpdb->get_var($wpdb->prepare(
               "SELECT ID FROM {$wpdb->posts} WHERE guid = %s",
               str_replace(ABSPATH, site_url('/'), $jpegPath)
            ));
            if ($existingId) {
               return (int)$existingId;
            }
         }
         // Perform conversion based on available libraries
         if (extension_loaded('imagick')) {
            $this->convertWebpToJpegImagick($webpPath, $jpegPath);
         } else {
            $this->convertWebpToJpegGd($webpPath, $jpegPath);
         }
         // Create attachment for the JPEG
         $attachmentData = [
            'post_mime_type' => 'image/jpeg',
            'post_title' => get_the_title($webpAttachmentId) . ' (JPEG)',
            'post_content' => '',
            'post_status' => 'inherit'
         ];
         $jpegAttachmentId = wp_insert_attachment($attachmentData, $jpegPath);
         if (is_wp_error($jpegAttachmentId)) {
            throw new Exception('Failed to create JPEG attachment: ' . $jpegAttachmentId->get_error_message());
         }
         // Generate metadata
         require_once(ABSPATH . 'wp-admin/includes/image.php');
         $attachData = wp_generate_attachment_metadata($jpegAttachmentId, $jpegPath);
         wp_update_attachment_metadata($jpegAttachmentId, $attachData);
         // Copy alt text and other meta
         $altText = get_post_meta($webpAttachmentId, '_wp_attachment_image_alt', true);
         if ($altText) {
            update_post_meta($jpegAttachmentId, '_wp_attachment_image_alt', $altText);
         }
         return $jpegAttachmentId;
      } catch (Exception $e) {
         $this->logError('Image conversion failed...', [
            'method' => 'convertWebpToJpeg'
         ]);
         return false;
      }
   }
   /**
   * Convert WebP to JPEG using Imagick
   */
   protected function convertWebpToJpegImagick(string $source, string $destination): void
   {
      $image = new \Imagick($source);
      $image->setImageFormat('jpeg');
      // Set quality (using 85 for good balance of quality/size)
      $image->setImageCompressionQuality(85);
      // Remove alpha channel and set white background
      $image->setImageBackgroundColor('white');
      $image->setImageAlphaChannel(\Imagick::ALPHACHANNEL_REMOVE);
      $image->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
      $image->writeImage($destination);
      $image->clear();
   }
   /**
    * Convert WebP to JPEG using GD
    */
   protected function convertWebpToJpegGd(string $source, string $destination): void
   {
      $image = imagecreatefromwebp($source);
      if ($image === false) {
         throw new Exception('Failed to create image from WebP source');
      }
      // Get dimensions
      $width = imagesx($image);
      $height = imagesy($image);
      // Create new true color image
      $jpegImage = imagecreatetruecolor($width, $height);
      // Set white background (for transparency)
      $white = imagecolorallocate($jpegImage, 255, 255, 255);
      imagefill($jpegImage, 0, 0, $white);
      // Copy WebP image to JPEG
      imagecopy($jpegImage, $image, 0, 0, 0, 0, $width, $height);
      // Save as JPEG (quality 85)
      $result = imagejpeg($jpegImage, $destination, 85);
      // Clean up
      imagedestroy($image);
      imagedestroy($jpegImage);
      if (!$result) {
         throw new Exception('Failed to save JPEG image');
      }
   }
   /**
    * Reset token refresh attempt flag
    * Called automatically when switching users
    */
   protected function resetTokenRefreshFlag(): void
   {
      $this->token_refresh_attempted = false;
   }
   public function getAllowedContent():array
   {
@@ -3542,4 +2200,24 @@
   {
      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;
   }
}