<?php

namespace PloverCRM\Common;

/**
 * Third-Party Plugin Compatibility
 * 
 * Handles compatibility with third-party plugins
 */
class Compatibility
{
    /**
     * Initialize compatibility handlers
     */
    public static function init(): void
    {
        // Mabel Wheel of Fortune compatibility
        add_filter('wof_zapier_optin_values', [self::class, 'modifyWheelOfFortuneZapierData']);
        add_filter('fluent_crm/incoming_webhook_data', [self::class, 'processLuckyWheelWebhook']);
    }

    /**
     * Modify Wheel of Fortune Zapier data
     * Adds source, key, and IP while storing request tracking context
     * internally for downstream enrichment.
     */
    public static function modifyWheelOfFortuneZapierData(array $zapier_data): array
    {
        $zapier_data['source'] = 'Webhook';
        $zapier_data['key'] = 'plover_crm_lucky_wheel';
        $zapier_data['ip'] = IpHandler::getRealUserIp();

        WebhookContextStore::remember([
            'user_ip' => $zapier_data['ip'],
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
            'current_url' => Hooks::getCurrentUrl(),
            'referrer_url' => $_SERVER['HTTP_REFERER'] ?? '',
            'cookies' => $_COOKIE ?? [],
        ]);

        return $zapier_data;
    }

    /**
     * Process Lucky Wheel incoming webhook data for FluentCRM
     * Maps custom fields to standard contact fields
     */
    public static function processLuckyWheelWebhook(array $postData): array
    {
        // ... (existing Wheel of Fortune code) ...
        // Only process if this is a Lucky Wheel webhook
        if (!isset($postData['key']) || $postData['key'] !== 'plover_crm_lucky_wheel') {
            return $postData;
        }

        // Map fields (text_1 => full_name, number_1 => phone)
        if (isset($postData['fields']) && is_array($postData['fields'])) {
            foreach ($postData['fields'] as $field) {
                if (empty($field['id']) || !isset($field['value'])) {
                    continue;
                }

                switch ($field['id']) {
                    case 'text_1':
                        // Split full name into first and last name
                        $nameParts = explode(' ', trim($field['value']), 2);
                        $postData['first_name'] = $nameParts[0] ?? '';
                        $postData['last_name'] = $nameParts[1] ?? '';
                        break;

                    case 'number_1':
                        $postData['phone'] = $field['value'];
                        break;
                }
            }
        }

        return $postData;
    }
}
