<?php

namespace PloverCRM\Modules\Integrations;

use PloverCRM\Core\AbstractModule;
use PloverCRM\Core\AdminMenu;

/**
 * Integrations Module
 * 
 * Centralized data source integrations.
 * Handles integrations with Forms, E-commerce, Memberships, LMS, etc.
 * CRM-agnostic: works with any CRM provider (PloverCRM, FluentCRM, etc.)
 */
class IntegrationsModule extends AbstractModule
{
  protected $id = 'integrations';
  protected $dependencies = [];  // No hard dependencies - uses active CRM via CRMManager

  public function getMetadata(): array
  {
    return [
      'name' => 'Data Sources',
      'description' => 'Centralized data source integrations',
      'version' => '1.0.0',
      'author' => 'PloverCRM',
      'icon' => '🔗',
      'required' => true,
    ];
  }

  public function register(): void
  {
    add_action('rest_api_init', [$this, 'registerEndpoints']);
    add_action('init', [$this, 'initListeners'], 20);

    // Register submenu via centralized AdminMenu
    AdminMenu::addSubmenu(
      'plover-crm-integrations',
      'Data Sources',
      'Data Sources',
      [$this, 'renderAdminPage'],
      20,
      'manage_options',
      false
    );

    // Register Conversions submenu
    AdminMenu::addSubmenu(
      'plover-crm-conversions',
      'Conversions',
      'Conversions',
      [$this, 'renderAutomationsPage'],
      30,
      'manage_options',
      false
    );
  }

  public function boot(): void
  {
    $this->ensureTablesExist();
  }

  public function isEnabled(): bool
  {
    return true;
  }

  public function registerEndpoints(): void
  {
    $this->registerModuleEndpoints([
      // App-facing data sources contract
      new Endpoints\DataSourcesBootstrapEndpoint($this->container),
      new Endpoints\DataSourcesEndpoint($this->container),
      new Endpoints\DataSourceSourcesEndpoint($this->container),
      new Endpoints\DataSourceFieldsEndpoint($this->container),
      new Endpoints\DataSourceWebhooksEndpoint($this->container),

      // Data source integrations
      new Endpoints\ListIntegrationsEndpoint($this->container),
      new Endpoints\GetIntegrationEndpoint($this->container),
      new Endpoints\CreateIntegrationEndpoint($this->container),
      new Endpoints\UpdateIntegrationEndpoint($this->container),
      new Endpoints\DeleteIntegrationEndpoint($this->container),
      new Endpoints\GetCategoriesEndpoint($this->container),
      new Endpoints\GetSourcesEndpoint($this->container),
      new Endpoints\GetSourceFieldsEndpoint($this->container),

      // Meta webhook (public)
      new Endpoints\MetaWebhookEndpoint($this->container),

      // Google Ads webhook (public)
      new Endpoints\GoogleAdsWebhookEndpoint($this->container),

      // Meta connections management (consolidated)
      new Endpoints\MetaConnectionsEndpoint($this->container),

      // Google Ads OAuth (Managed Mode only)
      new Endpoints\GoogleOAuthCallbackEndpoint($this->container),
      new Endpoints\GetGoogleAccountsEndpoint($this->container),
      new Endpoints\ConnectionsBootstrapEndpoint($this->container),
      new Endpoints\SaveGoogleConnectionEndpoint($this->container),
      new Endpoints\DeleteGoogleConnectionEndpoint($this->container),
      new Endpoints\DisconnectGoogleAuthEndpoint($this->container),
      new Endpoints\GetGoogleConversionActionsEndpoint($this->container),
      new Endpoints\GetGoogleMappingsEndpoint($this->container),
      new Endpoints\SaveGoogleMappingEndpoint($this->container),
      new Endpoints\DeleteGoogleMappingEndpoint($this->container),
      new Endpoints\GetCRMItemsEndpoint($this->container),

      // Meta CAPI (Conversion API)
      new Endpoints\GetMetaCapiConnectionsEndpoint($this->container),
      new Endpoints\SaveMetaCapiConnectionEndpoint($this->container),
      new Endpoints\DeleteMetaCapiConnectionEndpoint($this->container),
      new Endpoints\GetMetaCapiMappingsEndpoint($this->container),
      new Endpoints\SaveMetaCapiMappingEndpoint($this->container),
      new Endpoints\DeleteMetaCapiMappingEndpoint($this->container),

      // Incoming Webhooks
      new Endpoints\IncomingWebhookEndpoint($this->container),
      new Endpoints\ListWebhooksEndpoint($this->container),
      new Endpoints\CreateWebhookEndpoint($this->container),
      new Endpoints\UpdateWebhookEndpoint($this->container),
      new Endpoints\DeleteWebhookEndpoint($this->container),
    ]);
  }

  public function initListeners(): void
  {
    $service = new Services\DataSourceService($this->container);
    $service->registerListeners();
  }

  public function renderAdminPage(): void
  {
    $category = sanitize_text_field($_GET['category'] ?? '');

    if ($category === 'connections') {
      wp_safe_redirect(home_url('/plover-crm/connections/'));
      exit;
    }

    $targetUrl = home_url('/plover-crm/data-sources/');

    if ($category !== '') {
      $targetUrl = add_query_arg(['category' => $category], $targetUrl);
    }

    wp_safe_redirect($targetUrl);
    exit;
  }

  public function renderAutomationsPage(): void
  {
    $platform = sanitize_text_field($_GET['platform'] ?? '');
    $query = [];

    if ($platform === 'google_ads') {
      $query['platform'] = 'google-ads';
    } elseif ($platform === 'meta_capi') {
      $query['platform'] = 'meta-capi';
    }

    $targetUrl = home_url('/plover-crm/connections/');

    if (!empty($query)) {
      $targetUrl = add_query_arg($query, $targetUrl);
    }

    wp_safe_redirect($targetUrl);
    exit;
  }

  private function ensureTablesExist(): void
  {
    global $wpdb;

    // Data sources table
    $dataSourcesTable = $wpdb->prefix . 'plover_crm_data_sources';
    if ($wpdb->get_var("SHOW TABLES LIKE '$dataSourcesTable'") !== $dataSourcesTable) {
      $this->createDataSourcesTable();
    }

    // Meta connections table (Lead Ads - incoming)
    Services\MetaConnectionService::install();

    // Meta CAPI connections table (Conversions - outgoing)
    Services\MetaCapiConnectionService::ensureTableExists();

    // Google Ads connections table
    Services\GoogleAdsConnectionService::ensureTableExists();

    // Incoming webhooks table
    Services\WebhookService::ensureTableExists();
  }

  private function createDataSourcesTable(): void
  {
    global $wpdb;
    $table_name = $wpdb->prefix . 'plover_crm_data_sources';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            name varchar(255) NOT NULL,
            category varchar(50) NOT NULL,
            provider varchar(50) NOT NULL,
            source_id varchar(100) NOT NULL,
            event_type varchar(50) DEFAULT 'default',
            field_mappings longtext NOT NULL,
            lists longtext DEFAULT NULL,
            tags longtext DEFAULT NULL,
            options longtext DEFAULT NULL,
            conditions longtext DEFAULT NULL,
            status varchar(20) NOT NULL DEFAULT 'active',
            created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY category (category),
            KEY provider_source (provider, source_id),
            KEY status (status)
        ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
  }
}
