<?php

namespace PloverCRM\Core\CRM;

use PloverCRM\Core\Plugin;
use PloverCRM\Core\Services\Logger;

/**
 * CRM Helper
 * 
 * Helper functions for working with CRM fields and UI components
 */
class CRMHelper
{
    /**
     * Get CRM fields organized for dropdown options
     * 
     * @return array Associative array with 'contact_standard' and 'contact_custom' groups
     */
    public static function getFieldsDropdownOptions(): array
    {
        $options = [];

        $crm = Plugin::getInstance()->getContainer()->get('crm');
        
        if (!$crm->isAvailable()) {
            return $options;
        }

        try {
            // Get standard contact fields
            $standard_fields = $crm->getStandardFields();
            foreach ($standard_fields as $key => $label) {
                $options['contact_standard'][$key] = $label;
            }

            // Get custom contact fields
            $custom_contact_fields = $crm->getAllCustomFields();
            foreach ($custom_contact_fields as $field) {
                if (isset($field['slug']) && isset($field['label'])) {
                    $options['contact_custom'][$field['slug']] = $field['label'];
                }
            }
        } catch (\Exception $e) {
            $logger = new Logger();
            $logger->logError('Failed to get fields', [
                'error' => $e->getMessage()
            ]);
        }

        return $options;
    }

    /**
     * Render a CRM fields dropdown HTML element
     * 
     * @param string $name The name attribute for the select element
     * @param string $selected The currently selected value
     * @param array $attributes Optional additional HTML attributes
     * @return string HTML select element
     */
    public static function renderFieldsDropdown(string $name, string $selected = '', array $attributes = []): string
    {
        $fields = self::getFieldsDropdownOptions();

        // Build attributes string
        $attr_string = '';
        $default_attrs = [
            'class' => 'crm-field-dropdown',
            'style' => 'width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 4px;'
        ];
        
        $merged_attrs = array_merge($default_attrs, $attributes);
        foreach ($merged_attrs as $attr => $value) {
            $attr_string .= ' ' . esc_attr($attr) . '="' . esc_attr($value) . '"';
        }

        $html = '<select name="' . esc_attr($name) . '"' . $attr_string . '>';
        $html .= '<option value="">Select CRM Field</option>';

        foreach ($fields as $group_name => $group_fields) {
            $group_label = str_replace('_', ' ', ucfirst($group_name));
            $html .= '<optgroup label="' . esc_attr($group_label) . '">';
            foreach ($group_fields as $key => $label) {
                $selected_attr = ($selected == $key) ? ' selected' : '';
                $html .= '<option value="' . esc_attr($key) . '"' . $selected_attr . '>' . esc_html($label) . '</option>';
            }
            $html .= '</optgroup>';
        }

        $html .= '</select>';
        return $html;
    }

    /**
     * Get all CRM fields as a flat array
     * 
     * @return array Flat array of field_key => field_label
     */
    public static function getAllFields(): array
    {
        $grouped = self::getFieldsDropdownOptions();
        $flat = [];

        foreach ($grouped as $group_fields) {
            $flat = array_merge($flat, $group_fields);
        }

        return $flat;
    }

    /**
     * Check if a field exists in CRM
     * 
     * @param string $field_key The field key to check
     * @return bool
     */
    public static function fieldExists(string $field_key): bool
    {
        $all_fields = self::getAllFields();
        return isset($all_fields[$field_key]);
    }

    /**
     * Get field label by key
     * 
     * @param string $field_key The field key
     * @return string|null Field label or null if not found
     */
    public static function getFieldLabel(string $field_key): ?string
    {
        $all_fields = self::getAllFields();
        return $all_fields[$field_key] ?? null;
    }
}
