<?php

declare(strict_types=1);

namespace PloverCRM\Modules\Integrations\Providers;

use PloverCRM\Modules\Integrations\Services\MetaApiService;
use PloverCRM\Modules\Integrations\Services\MetaConnectionService;

/**
 * Meta Lead Ads Provider
 * 
 * Provides integration with Facebook/Instagram Lead Ads.
 */
class MetaLeadAdsProvider implements DataSourceProviderInterface
{
    private MetaApiService $api;

    public function __construct()
    {
        $this->api = new MetaApiService();
    }

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

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

    public function getIcon(): string
    {
        return 'meta.svg';
    }

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

    /**
     * Always available - users need to see it to set up connections
     */
    public function isAvailable(): bool
    {
        return true;
    }

    /**
     * Get available lead forms from all connected pages
     */
    public function getSources(): array
    {
        // Check if any connection exists
        if (empty(MetaConnectionService::getAll(true))) {
            return [];
        }

        $forms = $this->api->getAllForms();

        // Format for UI - include page name
        return array_map(function ($form) {
            return [
                'id' => $form['id'],
                'title' => $form['title'] . ' (' . ($form['page_name'] ?? 'Unknown') . ')',
                'page_id' => $form['page_id'] ?? '',
                'page_name' => $form['page_name'] ?? '',
            ];
        }, $forms);
    }

    /**
     * Get fields for a specific form
     */
    public function getSourceFields(string $sourceId): array
    {
        return $this->api->getFormFields($sourceId);
    }

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

    /**
     * Register event listener
     * 
     * Note: Events are handled via webhook endpoint, not real-time
     */
    public function registerEventListener(callable $callback): void
    {
        // Webhooks are received via MetaWebhookEndpoint
        // This method is not used for Meta Lead Ads
    }
}
