<?php

namespace PloverCRM\Modules\NativeCRM;

/**
 * Custom Fields Renderer
 * 
 * Renders custom fields in contact edit screen
 */
class CustomFieldsRenderer
{
    /**
     * @var CustomFieldsManager
     */
    private $manager;

    /**
     * Constructor
     * 
     * @param CustomFieldsManager $manager
     */
    public function __construct(CustomFieldsManager $manager)
    {
        $this->manager = $manager;
    }

    /**
     * Render custom fields
     * 
     * @param int $contact_id
     * @return void
     */
    public function render(int $contact_id): void
    {
        $fields = $this->manager->getAllFields();

        if (empty($fields)) {
            echo '<p>No custom fields defined. <a href="' . home_url('/plover-crm/settings/custom-fields/') . '">Add custom fields</a></p>';
            return;
        }

        // Sort by order
        usort($fields, function ($a, $b) {
            return ($a['order'] ?? 0) - ($b['order'] ?? 0);
        });

        // Group fields by group name
        $grouped_fields = [];
        foreach ($fields as $field) {
            $group = $field['group'] ?? 'Other';
            if (!isset($grouped_fields[$group])) {
                $grouped_fields[$group] = [];
            }
            $grouped_fields[$group][] = $field;
        }

        echo '<style>
            .plvcrm-custom-field { margin-bottom: 15px; }
            .plvcrm-custom-field label { display: block; font-weight: 600; margin-bottom: 5px; }
            .plvcrm-custom-field input[type="text"],
            .plvcrm-custom-field input[type="email"],
            .plvcrm-custom-field input[type="url"],
            .plvcrm-custom-field input[type="number"],
            .plvcrm-custom-field input[type="date"],
            .plvcrm-custom-field input[type="datetime-local"],
            .plvcrm-custom-field textarea,
            .plvcrm-custom-field select { width: 100%; }
            .plvcrm-custom-field textarea { min-height: 80px; }
            .plvcrm-field-group { margin-top: 20px; margin-bottom: 20px; }
            .plvcrm-field-group-title { font-size: 14px; font-weight: 600; margin-bottom: 10px; padding-bottom: 5px; border-bottom: 1px solid #ddd; }
        </style>';

        foreach ($grouped_fields as $group_name => $group_fields) {
            if (count($grouped_fields) > 1) {
                echo '<div class="plvcrm-field-group">';
                echo '<div class="plvcrm-field-group-title">' . esc_html($group_name) . '</div>';
            }

            foreach ($group_fields as $field) {
                $this->renderField($contact_id, $field);
            }

            if (count($grouped_fields) > 1) {
                echo '</div>';
            }
        }
    }

    /**
     * Render a single field
     * 
     * @param int $contact_id
     * @param array $field
     * @return void
     */
    private function renderField(int $contact_id, array $field): void
    {
        $value = $this->manager->getContactFieldValue($contact_id, $field['slug']);
        $field_name = 'plover_crm_cf_' . $field['slug'];
        $unique_field = get_option('plover_crm_unique_field', 'email');
        $is_unique = ($unique_field === $field_name);
        $is_readonly = !empty($field['readonly']);

        echo '<div class="plvcrm-custom-field">';
        echo '<label for="' . esc_attr($field_name) . '">';
        echo esc_html($field['label']);
        if ($is_unique) echo ' *';
        if ($is_readonly) echo ' <span style="color: #666; font-weight: normal;">(Read Only)</span>';
        echo '</label>';

        $required = $is_unique ? 'required' : '';
        $readonly_attr = $is_readonly ? 'readonly disabled' : '';
        $readonly_style = $is_readonly ? 'style="background-color: #f5f5f5; cursor: not-allowed;"' : '';

        switch ($field['type']) {
            case 'text':
                echo '<input type="text" id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '" ' . $required . ' ' . $readonly_attr . ' ' . $readonly_style . ' />';
                break;

            case 'textarea':
                echo '<textarea id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" ' . $required . ' ' . $readonly_attr . ' ' . $readonly_style . '>' . esc_textarea($value) . '</textarea>';
                break;

            case 'email':
                echo '<input type="email" id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '" ' . $required . ' ' . $readonly_attr . ' ' . $readonly_style . ' />';
                break;

            case 'url':
                echo '<input type="url" id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '" ' . $required . ' ' . $readonly_attr . ' ' . $readonly_style . ' />';
                break;

            case 'number':
                echo '<input type="number" id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '" ' . $required . ' ' . $readonly_attr . ' ' . $readonly_style . ' />';
                break;

            case 'date':
                echo '<input type="date" id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '" ' . $required . ' ' . $readonly_attr . ' ' . $readonly_style . ' />';
                break;

            case 'date_time':
                echo '<input type="datetime-local" id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '" ' . $required . ' ' . $readonly_attr . ' ' . $readonly_style . ' />';
                break;

            case 'select':
                echo '<select id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" ' . $required . ' ' . $readonly_attr . ' ' . $readonly_style . '>';
                echo '<option value="">-- Select --</option>';
                if (!empty($field['options'])) {
                    foreach ($field['options'] as $option) {
                        $selected = ($value === $option) ? 'selected' : '';
                        echo '<option value="' . esc_attr($option) . '" ' . $selected . '>' . esc_html($option) . '</option>';
                    }
                }
                echo '</select>';
                break;

            case 'radio':
                if (!empty($field['options'])) {
                    foreach ($field['options'] as $option) {
                        $checked = ($value === $option) ? 'checked' : '';
                        echo '<label style="display: inline-block; margin-right: 15px;">';
                        echo '<input type="radio" name="' . esc_attr($field_name) . '" value="' . esc_attr($option) . '" ' . $checked . ' ' . $readonly_attr . ' /> ';
                        echo esc_html($option);
                        echo '</label>';
                    }
                }
                break;

            case 'checkbox':
                if (!empty($field['options'])) {
                    // Multiple checkboxes
                    $selected_values = is_array($value) ? $value : (empty($value) ? [] : explode(',', $value));
                    foreach ($field['options'] as $option) {
                        $checked = in_array($option, $selected_values) ? 'checked' : '';
                        echo '<label style="display: inline-block; margin-right: 15px;">';
                        echo '<input type="checkbox" name="' . esc_attr($field_name) . '[]" value="' . esc_attr($option) . '" ' . $checked . ' ' . $readonly_attr . ' /> ';
                        echo esc_html($option);
                        echo '</label>';
                    }
                } else {
                    // Single checkbox (on/off)
                    $checked = $value ? 'checked' : '';
                    echo '<input type="checkbox" id="' . esc_attr($field_name) . '" name="' . esc_attr($field_name) . '" value="1" ' . $checked . ' ' . $readonly_attr . ' />';
                }
                break;
        }

        if (!empty($field['help_text'])) {
            echo '<p class="description">' . esc_html($field['help_text']) . '</p>';
        }

        echo '</div>';
    }
}
