Jake Vanderwerf
2026-07-12 c204185ae86a98994f80010abf35a190c9406739
inc/integrations/Integrations.php
@@ -3,21 +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_Query;
use WP_REST_Request;
use WP_REST_Response;
use WP_Term;
use WP_User;
if (!defined('ABSPATH')) {
   exit;
@@ -34,85 +30,30 @@
 */
abstract class Integrations
{
   use _Base;
   //Flag to allow for custom settings (defaults, etc) for an integration in the dashboard
   public static bool $hasExtraOptions = false;
   public bool $hasExtraOptions = false;
   public bool $hasBatchCreate = false;
   public bool $hasBatchUpdate = false;
   public bool $hasBatchDelete = false;
   public bool $canCreateOnUpdate = false;
   /**
    * Queue types
    * These types match with IntegrationExecutor
    */
   protected static string $syncTo;
   protected static string $deleteFrom;
   protected static string $syncFrom;
   protected static string $syncCustomer;
   protected static string $import;
   /**
    * 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 = [];
@@ -127,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
@@ -163,74 +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;
   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 ($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)'
         ];
      if (method_exists($this, 'setQueueTypes')) {
         $this->setQueueTypes();
      }
      self::$syncTo = $this->service_name.'_sync_to';
      self::$deleteFrom = $this->service_name.'_delete_from';
      self::$syncFrom = $this->service_name.'_sync_from';
      //TODO: What is the difference between sync_from and import?
      self::$import = $this->service_name.'import_from';
      $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;
         }
   protected function addFilters():bool
   {
      return is_null($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
   {
@@ -238,7 +138,6 @@
   }
   public function getContentTypes(string $type):array
   {
      return (array_key_exists($type, $this->contentTypes)) ? $this->contentTypes[$type] : $this->contentTypes;
   }
@@ -256,7 +155,7 @@
   public function handleOAuthConnect(): array
   {
      if (!$this->isOAuthService) {
      if (!$this->hasOAuth) {
         return ['success' => false, 'message' => 'Not an OAuth service'];
      }
@@ -355,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
@@ -393,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
@@ -475,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
@@ -513,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
   {
@@ -552,7 +370,7 @@
         // Connection successful, save credentials
         $stored = CredentialsManager::getInstance()->storeCredentials(
         $stored = Auth::getInstance()->storeCredentials(
            $this->service_name,
            $credentials,
            $this->userID
@@ -576,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
         );
@@ -595,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
      ];
@@ -759,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
@@ -1101,114 +652,17 @@
    *********************************************************************/
   /**
    * 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
   {
      //Handled by IntegrationExecutor now
//    add_filter(BASE . 'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
      if (is_null($this->userID)) {
         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 && is_null($this->userID)){
      if (method_exists($this, 'registerOAuthCallbacks')) {
         $this->registerOAuthCallbacks();
      }
      if (method_exists($this, 'registerWebhookEndpoint')) {
         $this->registerWebhookEndpoint();
      }
      // Let child classes register additional hooks if needed
@@ -1280,62 +734,7 @@
         {
            //Empty. Integration extensions can register additional operation types from here.
         }
   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');
      }
      // 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');
      }
      // Exchange code for tokens
      $result = $integration->handleOAuthCode($code, $state);
      // 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';
         wp_redirect(add_query_arg([
            'error' => $error_message
         ], $return_url));
      }
      exit;
   }
   /**
    * Handle connection setup and credential storage
    *
@@ -1393,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();
   }
@@ -1443,42 +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();
      }
      $this->initialize();
   }
@@ -1526,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,
@@ -1539,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
@@ -1597,7 +885,7 @@
   public function getOAuthUrl(?string $return_url = null): string
   {
      if (!$this->isOAuthService) {
      if (!$this->hasOAuth) {
         return '';
      }
@@ -1663,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
@@ -1870,7 +1046,7 @@
    */
   protected function shouldRefreshToken(): bool
   {
      if (!$this->isOAuthService || $this->refresh_interval === 0) {
      if (!$this->hasOAuth || $this->refresh_interval === 0) {
         return false;
      }
@@ -1908,7 +1084,7 @@
    */
   public function getTokenStatus(): string
   {
      if (!$this->isOAuthService) {
      if (!$this->hasOAuth) {
         return 'not_oauth';
      }
@@ -1938,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;
      }
@@ -1992,7 +1168,7 @@
    */
   public function revokeOAuthAccess(): bool
   {
      if (!$this->isOAuthService || empty($this->oauth['revoke'])) {
      if (!$this->hasOAuth || empty($this->oauth['revoke'])) {
         return false;
      }
@@ -2002,7 +1178,7 @@
         ]);
      }
      return CredentialsManager::getInstance()->deleteCredentials($this->service_name, $this->userID);
      return Auth::getInstance()->deleteCredentials($this->service_name, $this->userID);
   }
@@ -2312,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
@@ -2409,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)) {
@@ -2477,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
@@ -2636,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
@@ -2785,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
@@ -2877,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 '';
      }
@@ -3065,7 +1837,7 @@
                  echo Form::render($name, '', $config);
               }
            }
            if ($this->handleWebhooks) {
            if ($this->hasWebhooks) {
               echo $this->renderWebhookUrl();
            }
            ?>
@@ -3203,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
@@ -3416,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
   {
@@ -3585,15 +2206,7 @@
      return $this->icon;
   }
   public function getServiceItemID(int $itemID, string $type = 'post'):string
   {
      return match($type) {
         'post'   => Meta::forPost($itemID)->get("_{$this->service_name}_item_id"),
         'term','taxonomy' => Meta::forTerm($itemID)->get("_{$this->service_name}_item_id"),
         'user'   => Meta::forUser($itemID)->get("_{$this->service_name}_item_id"),
         default => ''
      };
   }
   public function canBatchUpdate():bool
   {
@@ -3607,402 +2220,4 @@
   {
      return $this->hasBatchDelete;
   }
   protected function updateItemStatus(int|array $items, string $status = 'pending', string $type = 'post'):void
   {
      if (!is_array($items)) {
         $items = [$items];
      }
      foreach ($items as $ID) {
         match ($type) {
            'post'   => Meta::forPost($ID)->set('_'.$this->service_name.'_sync_status', $status),
            'term'   => Meta::forTerm($ID)->set('_'.$this->service_name.'_sync_status', $status),
            'user'   => Meta::forUser($ID)->set('_'.$this->service_name.'_sync_status', $status),
            default => false
         };
      }
   }
   public function updateBatchToService(array $data):array
   {
      $type = $data['type']??'post';
      $newlyCreated = [];
      if (!$this->canCreateOnUpdate) {
         $created = array_filter($data['items'], function($ID) use ($type) {
            return !empty($this->getServiceItemID($ID, $type));
         });
         //Test to see if we have any that haven't been created yet.
         //For some services, items may have to be created before they can be updated
         if (count($created) !== count($data['items'])) {
            $notCreated = array_filter($data['items'], function($ID) use ($type) {
               return empty($this->getServiceItemID($ID, $type));
            });
            $newData = $data;
            $newData['items'] = $notCreated;
            $newlyCreated = $this->createBatchToService($newData);
         }
         // If we don't have any that are created, just send the noUpdatedItems response, with any newly created items added
         if (empty($created)) {
            return $this->noUpdatedItems($newlyCreated);
         }
         $data['items'] = $created;
      }
      $items = $this->formatItems($data['items'], $type);
      if (empty($items)) {
         return $this->noUpdatedItems($newlyCreated);
      }
      if ($this->hasBatchUpdate) {
         $response = $this->sendBatchUpdate($items);
         if (!is_wp_error($response)) {
            $result = $this->processBatchUpdateResponse($data, $response);
         } else {
            $this->logError('Batch update failed',[
               'method' => 'updateBatchToService',
               'item_ids'  => $data['items'],
               'error'     => $response
            ]);
            $this->updateItemStatus($data['items'], 'error');
            $result = [
               'outcome'   => 'failed_permanent',
               'result' => 'Could not update items'
            ];
         }
      } else {
         $success = $errors = [];
         //Does not have batch update, manually update each one
         foreach ($items as $item) {
            $itemResult = $this->updateOne($item);
            if (!is_wp_error($itemResult)) {
               $success[] = $itemResult;
            } else {
               $errors[] = $itemResult;
            }
         }
         $result = [
            'outcome'   => empty($errors) ? 'success' : (empty($success) ? 'failed' : 'partial'),
            'result' => [
               'success'   => $success,
               'errors' => $errors
            ]
         ];
      }
      return array_merge($result, $newlyCreated);
   }
   /**
    * To be implemented by integration extension. Updates a single item
    * @param array $item
    * @return array|WP_Error
    */
      protected function updateOne(array $item):array|WP_Error
      {
         return new WP_Error('invalid', 'Integration '.$this->service_name.' must implement its own updateOne method');
      }
   /**
    * Overridden by child classes
    * @param array $items
    * @return array|WP_Error
    */
      protected function sendBatchUpdate(array $items):array|WP_Error
      {
         return new WP_Error('invalid', 'Integration '.$this->service_name.' must implement its own sendBatchUpdate');
      }
   /**
    * Overridden by child classes
    * @param array $items
    * @return array|WP_Error
    */
      protected function sendBatchCreate(array $items):array|WP_Error
      {
         return new WP_Error('invalid', 'Integration '.$this->service_name.' must implement its own sendBatchCreate');
      }
   /**
    * To be implemented by extensions
    * @param array $data
    * @param array $response
    * @return array
    */
      protected function processBatchUpdateResponse(array $data, array $response):array
      {
         return [
            'outcome'   => 'failed',
            'result' => [
               'message'   => $this->service_name.' should implement processBatchUpdateResponse.'
            ]
         ];
      }
   /**
    * To be implemented by extensions
    * @param array $data
    * @param array $response
    * @return array
    */
      protected function processBatchCreateResponse(array $data, array $response):array
      {
         return [
            'outcome'   => 'failed',
            'result' => [
               'message'   => $this->service_name.' should implement processBatchCreateResponse.'
            ]
         ];
      }
   /**
    * Defaults to an array of formatted items. Can be overridden in child classes
    * @param array $itemIDs
    * @param string $type
    * @return array
    */
      protected function formatItems(array $itemIDs, string $type):array
      {
         $items = [];
         foreach ($itemIDs as $ID) {
            try {
               $items[] = $this->formatForService($ID, $type);
            } catch (Exception $e){
               $this->logError('Could not format Item for service',[
                  'itemID' => $ID,
                  'type'   => $type,
                  'message'   => $e->getMessage(),
               ]);
            }
         }
         return $items;
      }
   /**
    * Must be defined according to how each service needs it to be
    * @param int $itemID
    * @param string $type
    * @return array
    * @throws Exception
    */
      protected function formatForService(int $itemID, string $type = 'post'):array
      {
         throw new Exception('formatForService must be implemented by child class');
      }
      protected function noUpdatedItems(array $created):array
      {
         $result =  [
            'outcome'   => 'success',
            'result' => [
               'message'   => 'No items to update',
               'updated'   => [],
               'errors' => [],
            ]
         ];
         if (!empty($created)) {
            error_log('Result before: '.print_r($result, true));
            $result = array_merge($result, $created);
            error_log('Result after merge: '.print_r($result, true));
         }
         return $result;
      }
      protected function noCreatedItems(array $updated):array
      {
         $result = [
            'outcome'   => 'success',
            'result' => [
               'message'   => 'No items to create',
               'created'   => [],
               'errors' => [],
            ]
         ];
         if (!empty($updated)) {
            $result = array_merge($result, $updated);
         }
         return $result;
      }
      public function createBatchToService($data):array
      {
         $type = $data['type']??'post';
         //Check if any of the submitted ids are already created
         $created = array_filter($data['items'],
            function($ID) use ($type) {
               return !empty($this->getServiceItemID($ID, $type));
            });
         $updated = [];
         if (!empty($created)) {
            $updateData = $data;
            $updateData['items'] = $created;
            $updated = $this->updateBatchToService($data);
            //remove any updated items from the original items to process
            $data['items'] = array_filter($data['items'], function ($ID) use ($created) {
               return !in_array($ID, $created);
            });
         }
         $items = $this->formatItems($data['items'], $type);
         if (empty($items)) {
            return $this->noCreatedItems($updated);
         }
         $response = [
            'outcome'   => 'failed',
            'result' => [
               'message'   => 'No result'
            ]
         ];
         if ($this->hasBatchCreate) {
            $response = $this->sendBatchCreate($items);
            if (!is_wp_error($response)) {
               $result = $this->processBatchCreateResponse($data, $response);
            } else {
               $this->logError('Batch create failed',[
                  'method' => 'createBatchToService',
                  'item_ids'  => $data['items'],
                  'error'     => $response
               ]);
               $this->updateItemStatus($data['items'], 'error');
               $result = [
                  'outcome'   => 'failed_permanent',
                  'result' => 'Could not update items'
               ];
            }
         } else {
            $success = $errors = [];
            foreach ($items as $item) {
               $itemResult = $this->createOne($item);
               if (!is_wp_error($itemResult)) {
                  $success[] = $itemResult;
               } else {
                  $errors[] = $itemResult;
               }
            }
            $result = [
               'outcome'   => empty($errors) ? 'success' : (empty($success) ? 'failed' : 'partial'),
               'result' => [
                  'success'   => $success,
                  'errors' => $errors
               ]
            ];
         }
         return array_merge($result, $updated);
      }
      /**
       * To be implemented by integration extension. Updates a single item
       * @param array $item
       * @return array|WP_Error
       */
      protected function createOne(array $item):array|WP_Error
      {
         return new WP_Error('invalid', 'Integration '.$this->service_name.' must implement its own createOne');
      }
   public function findWPItem(string $integrationID, ?string $type = null):array|false
   {
      if (empty($integrationID)) {
         error_log('Integrations::findWPItem No Integration ID received.');
         return false;
      }
      $types = ['post', 'term', 'user'];
      if (!is_null($type) && !in_array($type, $types)) {
         error_log('Integrations::findWPItem invalid type sent: '.$type.'; defaulting to checking all');
         $type = null;
      }
      if (!is_null($type)) {
         return $this->queryWPType($integrationID, $type);
      } else {
         foreach ($types as $type) {
            $check = $this->queryWPType($integrationID, $type);
            if ($check) {
               return $check;
            }
         }
      }
      return false;
   }
   /**
    * @param string $integrationID
    * @param string|null $type
    * @return array|false if success, an array of $ID and $type
    */
      public function queryWPType(string $integrationID, ?string $type = null):array|false
      {
         if (!in_array($type, ['post', 'term', 'user'])) {
            return $this->findWPItem($integrationID);
         }
         return match($type) {
            'post'   => $this->findWPPost($integrationID),
            'term'   => $this->findWPTerm($integrationID),
            'user'   => $this->findWPUser($integrationID),
            default => false
         };
      }
      public function findWPPost(string $integrationID):array|false
      {
         if (empty($integrationID)) {
            return false;
         }
         $get = new WP_Query([
            'meta_query'   => [
               'key' => BASE."_{$this->service_name}_item_id",
               'value'  => $integrationID,
            ],
            'fields' => 'ids',
            'posts_per_page' => 1,
         ]);
         return $get->have_posts() && !empty($get->posts) ? [$get->posts[0], 'post'] : false;
      }
      public function findWPTerm(string $integrationID):array|false
      {
         if (empty($integrationID)) {
            return false;
         }
         $get = get_terms([
            'meta_query'   => [
               'key' => BASE."_{$this->service_name}_item_id",
               'value'  => $integrationID,
            ],
            'fields' => 'ids',
            'hide_empty'=> true,
            'number' => 1
         ]);
         return is_wp_error($get) || empty($get) ? false : [$get[0], 'term'];
      }
      public function findWPUser(string $integrationID):array|false
      {
         if (empty($integrationID)) {
            return false;
         }
         $get = get_users([
            'meta_query'   => [
               'key' => BASE."_{$this->service_name}_item_id",
               'value'  => $integrationID,
            ],
            'fields' => 'ids',
            'number' => 1,
         ]);
         return is_wp_error($get) || empty($get) ? false : [$get[0], 'user'];
      }
   /*********************************************************************************
    * Syncing WP items from Service
   *********************************************************************************/
   protected function createItemFromService(array $itemData):bool
   {
   }
}