<?php

namespace PloverCRM\Common;

/**
 * Common Utility Functions
 * 
 * Shared utility functions used across the plugin
 */
class Utils
{
    /**
     * Check if bulk import is in progress (for any CRM)
     * 
     * @return bool
     */
    public static function isBulkImporting(): bool
    {
        // FluentCRM bulk import
        if (defined('FLUENTCRM_DOING_BULK_IMPORT') && FLUENTCRM_DOING_BULK_IMPORT) {
            return true;
        }

        // PloverCRM CSV import
        if (defined('WPR_CRM_IMPORTING') && WPR_CRM_IMPORTING) {
            return true;
        }

        return false;
    }

    /**
     * Generate random email
     */
    public static function generateRandomEmail(): string
    {
        $timestamp = (int)(microtime(true) * 1000);
        $random = bin2hex(random_bytes(2));
        return $timestamp . $random . '@wpr.com';
    }

    /**
     * Get CRM list IDs by titles
     */
    public static function getCrmListIdsByNames(array $list_names): array
    {
        if (empty($list_names)) {
            return [];
        }

        $crm = \PloverCRM\Core\Plugin::getInstance()->getContainer()->get('crm');

        if (!$crm->isAvailable()) {
            return [];
        }

        $all_lists = $crm->getAllLists();
        $matching_ids = [];

        foreach ($all_lists as $list) {
            if (in_array($list['title'], $list_names)) {
                $matching_ids[] = (int)$list['id'];
            }
        }

        return $matching_ids;
    }

    /**
     * Format custom fields with labels
     */
    public static function formatCustomFields($subscriber): array
    {
        $crm = \PloverCRM\Core\Plugin::getInstance()->getContainer()->get('crm');

        $custom_fields = $crm->getContactCustomFields($subscriber);
        $definitions = $crm->getAllCustomFields();
        $defs_by_slug = array_column($definitions, null, 'slug');

        // Build formatted array—only slugs that exist in your definitions
        $formatted_fields = [];
        foreach ($custom_fields as $slug => $value) {
            if (!isset($defs_by_slug[$slug])) {
                // skip unknown slugs entirely
                continue;
            }

            $formatted_fields[] = [
                'label' => $defs_by_slug[$slug]['label'],
                'key' => $slug,
                'value' => $value,
            ];
        }

        return $formatted_fields;
    }

    /**
     * Generate avatar URL
     * 
     * @param array|object $subscriber Contact data (array or object)
     */
    public static function generateAvatar($subscriber): string
    {
        // Handle both array and object
        $first = is_array($subscriber) ? ($subscriber['first_name'] ?? '') : ($subscriber->first_name ?? '');
        $last = is_array($subscriber) ? ($subscriber['last_name'] ?? '') : ($subscriber->last_name ?? '');
        $hash = is_array($subscriber) ? ($subscriber['hash'] ?? md5($subscriber['email'] ?? '')) : ($subscriber->hash ?? '');

        $initials = ($first || $last)
            ? strtoupper(mb_substr($first, 0, 1) . mb_substr($last, 0, 1))
            : 'NA';

        return sprintf(
            'https://www.gravatar.com/avatar/%s?d=%s',
            $hash,
            urlencode("https://ui-avatars.com/api/{$initials}/128/random/fff")
        );
    }

    /**
     * Get and format last note
     * 
     * @param array|object $subscriber Contact data (array or object)
     */
    public static function getFormattedLastNote($subscriber)
    {
        // Only works with objects (from endpoints)
        if (is_array($subscriber)) {
            return null;
        }

        $last_note = $subscriber->notes()
            ->orderBy('id', 'DESC')
            ->select(['title', 'description', 'created_at', 'created_by'])
            ->first();

        if ($last_note && $last_note->created_by) {
            $user = get_user_by('ID', $last_note->created_by);
            $last_note->created_by = [
                'id' => $last_note->created_by,
                'username' => $user ? $user->user_login : 'Unknown'
            ];
        }

        return $last_note;
    }

    /**
     * Enrich subscriber data
     * 
     * @param object $subscriber Contact object (from endpoints only)
     */
    public static function enrichSubscriber($subscriber)
    {
        static $countries = null; // Cache country list for all calls in this request

        // Generate avatar
        $subscriber->plover_crm_avatar = self::generateAvatar($subscriber);

        // Add custom fields
        $subscriber->custom_fields = self::formatCustomFields($subscriber);

        // Add last note
        $subscriber->last_note = self::getFormattedLastNote($subscriber);

        // Convert 2-letter country code to country name
        if (!empty($subscriber->country)) {
            $countryCode = strtoupper(trim($subscriber->country));

            if (strlen($countryCode) === 2) {
                // Load country list once per request
                if ($countries === null) {
                    $countryNames = new \FluentCrm\App\Hooks\Handlers\CountryNames();
                    $allCountries = $countryNames->get();

                    // Create an indexed map for O(1) lookups
                    $countries = [];
                    foreach ($allCountries as $country) {
                        if (isset($country['code']) && isset($country['title'])) {
                            $countries[strtoupper($country['code'])] = $country['title'];
                        }
                    }
                }

                // Lookup country name efficiently
                if (isset($countries[$countryCode])) {
                    $subscriber->country = $countries[$countryCode];
                }
            }
        }

        return $subscriber;
    }

    /**
     * Format API response with subscribers and pagination metadata
     */
    public static function formatResponse($subscribers, $page, $per_page, $total, $total_pages): array
    {
        return [
            'subscribers' => $subscribers,
            'meta' => [
                'current_page' => $page,
                'per_page' => $per_page,
                'total_items' => $total,
                'total_pages' => $total_pages
            ]
        ];
    }

    /**
     * Update or create custom fields
     */
    public static function updateOrCreateCustomFields(array $fields_to_create): void
    {
        $crm = \PloverCRM\Core\Plugin::getInstance()->getContainer()->get('crm');

        if (!$crm->isAvailable()) {
            return;
        }

        $crm->createOrUpdateCustomFields($fields_to_create);
    }

    /**
     * Get stage colors
     */
    public static function getStageColors(): array
    {
        return get_option('plover_crm_stage_colors', []);
    }

    /**
     * Enhance stage field with colors
     */
    public static function enhanceStageFieldWithColors($field)
    {
        if ($field['slug'] === 'stage-plover-crm' && isset($field['options'])) {
            $stage_colors = self::getStageColors();
            $enhanced_options = [];

            foreach ($field['options'] as $stage) {
                $enhanced_options[] = [
                    'name' => $stage,
                    'color' => isset($stage_colors[$stage]) ? $stage_colors[$stage] : '#666666'
                ];
            }

            $field['options_with_colors'] = $enhanced_options;
        }

        return $field;
    }
}
