<?php

namespace PloverCRM\Modules\Integrations\Providers;

/**
 * Google Ads Lead Forms Provider
 * 
 * Provides integration with Google Ads Lead Form Extensions via webhooks.
 * No OAuth required - uses simple webhook URL + key authentication.
 */
class GoogleAdsProvider implements DataSourceProviderInterface
{
  private $eventCallback;

  public function getKey(): string
  {
    return 'google_ads';
  }

  public function getName(): string
  {
    return 'Google Ads';
  }

  public function getIcon(): string
  {
    return 'google-ads.svg';
  }

  public function getCategory(): string
  {
    return 'ads';
  }

  public function isAvailable(): bool
  {
    // Always available - no plugin dependency
    return true;
  }

  public function getSupportedEvents(): array
  {
    return [
      ['key' => 'lead_received', 'label' => 'Lead Received'],
    ];
  }

  /**
   * Get sources (forms) - returns forms from cached test data
   * 
   * Note: Google Ads doesn't provide API to fetch forms without OAuth.
   * Forms appear here after sending test webhook data.
   */
  public function getSources(): array
  {
    // Get list of form IDs that have cached test data
    $cachedForms = get_option('plover_crm_google_ads_cached_forms', []);

    if (empty($cachedForms)) {
      return [];
    }

    $sources = [];
    foreach ($cachedForms as $formId => $formData) {
      $sources[] = [
        'id' => (string) $formId,
        'title' => 'Google Ads Form ' . $formId,
      ];
    }

    return $sources;
  }

  /**
   * Get fields for a specific form
   * 
   * Returns fields detected from test webhook data
   */
  public function getSourceFields(string $formId): array
  {
    // Try to get cached fields from test webhook
    $cached = get_transient('plover_crm_google_ads_fields_' . $formId);

    if ($cached && is_array($cached)) {
      return $cached;
    }

    // No test data found - return empty with metadata fields only
    return $this->getMetadataFields();
  }

  /**
   * Get metadata fields that are always available
   */
  private function getMetadataFields(): array
  {
    return [
      [
        'key' => '_google_lead_id',
        'label' => 'Lead ID',
        'type' => 'text',
        'group' => 'metadata',
      ],
      [
        'key' => '_google_form_id',
        'label' => 'Form ID',
        'type' => 'text',
        'group' => 'metadata',
      ],
      [
        'key' => '_google_campaign_id',
        'label' => 'Campaign ID',
        'type' => 'text',
        'group' => 'metadata',
      ],
      [
        'key' => '_google_adgroup_id',
        'label' => 'Ad Group ID',
        'type' => 'text',
        'group' => 'metadata',
      ],
      [
        'key' => '_google_creative_id',
        'label' => 'Creative ID',
        'type' => 'text',
        'group' => 'metadata',
      ],
      [
        'key' => '_google_asset_group_id',
        'label' => 'Asset Group ID (Performance Max)',
        'type' => 'text',
        'group' => 'metadata',
      ],
      [
        'key' => '_google_gcl_id',
        'label' => 'Google Click ID (GCLID)',
        'type' => 'text',
        'group' => 'metadata',
      ],
      [
        'key' => '_google_lead_stage',
        'label' => 'Lead Stage',
        'type' => 'text',
        'group' => 'metadata',
      ],
      [
        'key' => '_google_lead_submit_time',
        'label' => 'Lead Submit Time',
        'type' => 'text',
        'group' => 'metadata',
      ],
    ];
  }

  public function registerEventListener(callable $callback): void
  {
    $this->eventCallback = $callback;
  }

  /**
   * Handle incoming webhook lead data
   * 
   * Called by GoogleAdsWebhookEndpoint when a lead is received
   * 
   * @param string $formId The Google Ads form ID
   * @param array $leadData The flattened lead data
   */
  public function handleWebhookLead(string $formId, array $leadData): void
  {
    if (!$this->eventCallback) {
      return;
    }

    if (empty($formId) || empty($leadData)) {
      return;
    }

    call_user_func($this->eventCallback, $this->getKey(), $formId, $leadData);
  }

  /**
   * Get the event callback (for testing)
   */
  public function getEventCallback(): ?callable
  {
    return $this->eventCallback;
  }

  /**
   * Cache form fields from test webhook
   * 
   * @param string $formId Form ID
   * @param array $fields Array of field definitions
   */
  public static function cacheFormFields(string $formId, array $fields): void
  {
    // Merge with metadata fields
    $metadataFields = (new self())->getMetadataFields();
    $allFields = array_merge($fields, $metadataFields);

    // Cache fields for 7 days
    set_transient('plover_crm_google_ads_fields_' . $formId, $allFields, 7 * DAY_IN_SECONDS);

    // Store form ID in the list of cached forms (permanent storage)
    $cachedForms = get_option('plover_crm_google_ads_cached_forms', []);
    $cachedForms[$formId] = [
      'cached_at' => time(),
      'fields_count' => count($fields),
    ];
    update_option('plover_crm_google_ads_cached_forms', $cachedForms);
  }

  /**
   * Clear cached fields for a form
   * 
   * @param string $formId Form ID
   */
  public static function clearCachedFields(string $formId): void
  {
    delete_transient('plover_crm_google_ads_fields_' . $formId);
  }
}
