<?php
namespace Blazemedia\Affiliation\AdminUserInterface\Settings\Components;

class FieldRenderer {
    
    private string $optionName;
    
    public function __construct(string $optionName) {
        $this->optionName = $optionName;
    }
    
    public function render(string $fieldId, array $config, $value): void {
        echo '<div class="field-container">';
        
        switch ($config['type']) {
            case 'text':
                $this->renderTextInput($fieldId, $value);
                break;
            case 'password':
                $this->renderPasswordInput($fieldId, $value, !empty($config['required']));
                break;
            case 'textarea':
                $this->renderTextarea($fieldId, $value);
                break;
            case 'select':
                $this->renderSelect($fieldId, $config['options'], $value);
                break;
            case 'multiselect':
                $this->renderMultiSelect($fieldId, $config['options'], $value);
                break;
            case 'toggle':
                $this->renderToggle($fieldId, $value);
                break;
        }
        
        if (isset($config['description'])) {
            echo '<p class="field-description">' . esc_html($config['description']) . '</p>';
        }
        
        echo '</div>';
    }
    
    private function renderTextInput(string $field, $value): void {
        printf(
            '<input class="regular-text field-input" type="text" name="%s[%s]" id="%s" value="%s">',
            $this->optionName,
            $field,
            $field,
            esc_attr($value)
        );
    }
    
    private function renderPasswordInput(string $field, $value, bool $required): void {
        $placeholder = $value !== '' ? '********' : '';
        $shouldRequire = $required && ($value === '');
        printf(
            '<input class="regular-text field-input" type="password" name="%s[%s]" id="%s" value="%s" %s placeholder="%s" autocomplete="new-password">',
            $this->optionName,
            $field,
            $field,
            '',
            $shouldRequire ? 'required' : '',
            esc_attr($placeholder)
        );
        if ($value !== '') {
            echo '<p class="description">Un valore è già impostato. Lascia vuoto per non modificarlo.</p>';
        }
    }
    
    private function renderTextarea(string $field, $value): void {
        printf(
            '<textarea class="large-text field-textarea" rows="5" name="%s[%s]" id="%s">%s</textarea>',
            $this->optionName,
            $field,
            $field,
            esc_textarea($value)
        );
    }
    
    private function renderSelect(string $field, array $options, $value): void {
        printf('<select name="%s[%s]" id="%s" class="field-select">', $this->optionName, $field, $field);
        
        foreach ($options as $optionValue => $label) {
            $selected = selected($value, $optionValue, false);
            printf('<option value="%s" %s>%s</option>', $optionValue, $selected, $label);
        }
        
        echo '</select>';
    }
    
    private function renderMultiSelect(string $field, array $options, $value): void {
        // Converti il valore da stringa separata da virgole ad array
        $selectedValues = !empty($value) ? explode(',', $value) : [];
        $selectedValues = array_map('trim', $selectedValues);
        $uniqueId = 'multiselect_' . $field;
        
        ?>
        <div class="multiselect-container" id="<?php echo $uniqueId; ?>">
            <!-- Hidden input per memorizzare i valori selezionati -->
            <input type="hidden" 
                   name="<?php echo $this->optionName; ?>[<?php echo $field; ?>]" 
                   id="<?php echo $field; ?>_hidden" 
                   value="<?php echo esc_attr($value); ?>">
            
            <!-- Area badge per mostrare i post types selezionati -->
            <div class="selected-badges" id="<?php echo $field; ?>_badges">
                <?php foreach ($selectedValues as $selectedValue): ?>
                    <?php if (!empty($selectedValue) && isset($options[$selectedValue])): ?>
                        <span class="post-type-badge" data-value="<?php echo esc_attr($selectedValue); ?>">
                            <?php echo esc_html($options[$selectedValue]); ?>
                            <button type="button" class="remove-badge" onclick="removeBadge('<?php echo $field; ?>', '<?php echo esc_js($selectedValue); ?>')">×</button>
                        </span>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
            
            <!-- Select per aggiungere nuovi post types -->
            <select id="<?php echo $field; ?>_select" 
                    class="multiselect-dropdown"
                    onchange="addBadge('<?php echo $field; ?>', this)">
                <option value="">-- Seleziona Post Type --</option>
                <?php foreach ($options as $optionValue => $label): ?>
                    <?php if (!in_array($optionValue, $selectedValues)): ?>
                        <option value="<?php echo esc_attr($optionValue); ?>"><?php echo esc_html($label); ?></option>
                    <?php endif; ?>
                <?php endforeach; ?>
            </select>
        </div>
        
        <script>
        function addBadge(fieldId, selectElement) {
            if (!selectElement.value) return;
            
            const value = selectElement.value;
            const text = selectElement.options[selectElement.selectedIndex].text;
            const badgesContainer = document.getElementById(fieldId + '_badges');
            const hiddenInput = document.getElementById(fieldId + '_hidden');
            
            // Crea il badge
            const badge = document.createElement('span');
            badge.className = 'post-type-badge';
            badge.setAttribute('data-value', value);
            badge.innerHTML = text + '<button type="button" class="remove-badge" onclick="removeBadge(\'' + fieldId + '\', \'' + value + '\')">×</button>';
            
            badgesContainer.appendChild(badge);
            
            // Rimuovi l'opzione dal select
            selectElement.remove(selectElement.selectedIndex);
            selectElement.value = '';
            
            // Aggiorna il campo hidden
            updateHiddenField(fieldId);
        }
        
        function removeBadge(fieldId, value) {
            const badge = document.querySelector('#' + fieldId + '_badges .post-type-badge[data-value="' + value + '"]');
            const select = document.getElementById(fieldId + '_select');
            
            if (badge) {
                const text = badge.textContent.replace('×', '');
                
                // Rimuovi il badge
                badge.remove();
                
                // Aggiungi l'opzione al select
                const option = document.createElement('option');
                option.value = value;
                option.textContent = text;
                select.appendChild(option);
                
                // Riordina le opzioni alfabeticamente
                const options = Array.from(select.options).slice(1); // Escludi la prima opzione
                options.sort((a, b) => a.text.localeCompare(b.text));
                
                // Rimuovi tutte le opzioni tranne la prima
                while (select.children.length > 1) {
                    select.removeChild(select.lastChild);
                }
                
                // Aggiungi le opzioni ordinate
                options.forEach(option => select.appendChild(option));
                
                // Aggiorna il campo hidden
                updateHiddenField(fieldId);
            }
        }
        
        function updateHiddenField(fieldId) {
            const badges = document.querySelectorAll('#' + fieldId + '_badges .post-type-badge');
            const values = Array.from(badges).map(badge => badge.getAttribute('data-value'));
            const hiddenInput = document.getElementById(fieldId + '_hidden');
            hiddenInput.value = values.join(',');
        }
        </script>
        <?php
    }
    
    private function renderToggle(string $field, $value): void {
        $checked = checked($value, '1', false);
        $uniqueId = 'toggle_' . $field;
        
        ?>
        <div class="toggle-switch">
            <input type="hidden" name="<?php echo $this->optionName; ?>[<?php echo $field; ?>]" value="0">
            <input type="checkbox" 
                   id="<?php echo $uniqueId; ?>" 
                   name="<?php echo $this->optionName; ?>[<?php echo $field; ?>]" 
                   value="1" 
                   <?php echo $checked; ?>
                   class="toggle-input">
            <label for="<?php echo $uniqueId; ?>" class="toggle-label">
                <span class="toggle-slider"></span>
                <span class="toggle-text">
                    <span class="toggle-on">ON</span>
                    <span class="toggle-off">OFF</span>
                </span>
            </label>
        </div>
        <?php
    }
}