<?php
namespace NewsletterBridge\Admin\Tabs\Newsletter;

/**
 * Rendering interfaccia per NewsletterTab
 * Responsabilità: Rendering HTML delle interfacce feed e date
 */
class NewsletterInterface {
    
    public static function render_feeds_interface($json_data, $config_feeds = []) {
        $feeds = json_decode($json_data, true) ?: [];
        // Filtra eventuali feed vuoti (nome e file entrambi vuoti)
        $feeds = array_values(array_filter($feeds, function($f) {
            return !empty($f['name']) || !empty($f['file']);
        }));
        ?>
        <div id="feeds-container">
            <?php foreach ($feeds as $index => $feed): ?>
            <div class="feed-item" style="border: 1px solid #ddd; padding: 15px; margin: 10px 0; background: #f9f9f9;">
                <div style="display: flex; align-items: center; margin-bottom: 10px; gap: 8px;">
                    <input type="text" name="feed_name_<?php echo $index; ?>" placeholder="Nome feed" value="<?php echo esc_attr($feed['name'] ?? ''); ?>" style="width: 150px;" />
                    <input type="text" name="feed_file_<?php echo $index; ?>" placeholder="Nome file" value="<?php echo esc_attr($feed['file'] ?? ''); ?>" style="width: 200px;" />
                    <button type="button" class="button button-secondary view-feed-btn" onclick="viewFeed(this)">Visualizza</button>
                    <button type="button" onclick="removeItem(this)" class="remove-btn">Rimuovi</button>
                </div>
                
                <!-- Blocco Query per questo feed -->
                <div class="feed-query-section" style="border-top: 1px solid #ddd; padding-top: 10px;">
                    <h4 style="margin: 0 0 10px 0; cursor: pointer;" onclick="toggleFeedConfig(<?php echo $index; ?>)">
                        ⚙️ Configurazione Query
                        <span id="toggle-<?php echo $index; ?>" style="float: right;">▼</span>
                    </h4>
                    
                    <div id="config-<?php echo $index; ?>" class="feed-config" style="display: none;">
                        <table class="form-table">
                            <tr>
                                <th scope="row">Numero massimo articoli</th>
                                <td>
                                    <input type="number" name="feed_query_posts_<?php echo $index; ?>" value="<?php echo esc_attr($feed['query_params']['posts_per_page'] ?? 10); ?>" min="1" max="100" />
                                </td>
                            </tr>
                            
                            <tr>
                                <th scope="row">Tassonomie da includere</th>
                                <td>
                                    <div class="autocomplete-container" style="position: relative;">
                                        <input type="text" id="include-tags-<?php echo $index; ?>" placeholder="Cerca termine da includere..." style="width: 300px;" />
                                        <div id="include-suggestions-<?php echo $index; ?>" class="autocomplete-suggestions" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; z-index: 1000;"></div>
                                        <div id="include-selected-<?php echo $index; ?>" class="selected-items" style="margin-top: 5px;">
                                            <?php
                                            // Trova il feed corrispondente nella configurazione
                                            $config_feed = null;
                                            foreach ($config_feeds as $cf) {
                                                if ($cf->name === $feed['name']) {
                                                    $config_feed = $cf;
                                                    break;
                                                }
                                            }
                                            
                                            if ($config_feed && isset($config_feed->query_params)) {
                                                // Compatibilità con vecchi nomi (include_tags) e nuovi (include_taxonomies)
                                                $include_terms = $config_feed->query_params->include_taxonomies ?? $config_feed->query_params->include_tags ?? [];
                                                foreach ($include_terms as $term_slug): 
                                                    $term = get_term_by('slug', $term_slug);
                                                    if ($term) {
                                                        $taxonomy_obj = get_taxonomy($term->taxonomy);
                                                        $taxonomy_label = $taxonomy_obj ? $taxonomy_obj->label : $term->taxonomy;
                                                        $display_text = $taxonomy_label . ' -> ' . $term->name;
                                                    } else {
                                                        $display_text = $term_slug;
                                                    }
                                            ?>
                                                <span class="selected-item" style="display: inline-block; background: #0073aa; color: white; padding: 2px 8px; margin: 2px; border-radius: 3px; font-size: 12px;">
                                                    <?php echo esc_html($display_text); ?>
                                                    <input type="hidden" name="feed_query_include_taxonomies_<?php echo $index; ?>[]" value="<?php echo esc_attr($term_slug); ?>" />
                                                    <span onclick="removeSelectedItem(this)" style="cursor: pointer; margin-left: 5px;">×</span>
                                                </span>
                                            <?php endforeach; ?>
                                            <?php } ?>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            
                            <tr>
                                <th scope="row">Tassonomie da escludere</th>
                                <td>
                                    <div class="autocomplete-container" style="position: relative;">
                                        <input type="text" id="exclude-tags-<?php echo $index; ?>" placeholder="Cerca termine da escludere..." style="width: 300px;" />
                                        <div id="exclude-suggestions-<?php echo $index; ?>" class="autocomplete-suggestions" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; z-index: 1000;"></div>
                                        <div id="exclude-selected-<?php echo $index; ?>" class="selected-items" style="margin-top: 5px;">
                                            <?php
                                            if ($config_feed && isset($config_feed->query_params)) {
                                                // Compatibilità con vecchi nomi (exclude_tags) e nuovi (exclude_taxonomies)
                                                $exclude_terms = $config_feed->query_params->exclude_taxonomies ?? $config_feed->query_params->exclude_tags ?? [];
                                                foreach ($exclude_terms as $term_slug): 
                                                    $term = get_term_by('slug', $term_slug);
                                                    if ($term) {
                                                        $taxonomy_obj = get_taxonomy($term->taxonomy);
                                                        $taxonomy_label = $taxonomy_obj ? $taxonomy_obj->label : $term->taxonomy;
                                                        $display_text = $taxonomy_label . ' -> ' . $term->name;
                                                    } else {
                                                        $display_text = $term_slug;
                                                    }
                                            ?>
                                                <span class="selected-item" style="display: inline-block; background: #dc3232; color: white; padding: 2px 8px; margin: 2px; border-radius: 3px; font-size: 12px;">
                                                    <?php echo esc_html($display_text); ?>
                                                    <input type="hidden" name="feed_query_exclude_taxonomies_<?php echo $index; ?>[]" value="<?php echo esc_attr($term_slug); ?>" />
                                                    <span onclick="removeSelectedItem(this)" style="cursor: pointer; margin-left: 5px;">×</span>
                                                </span>
                                            <?php endforeach; ?>
                                            <?php } ?>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            
                            <tr>
                                <th scope="row">In evidenza newsletter</th>
                                <td>
                                    <?php
                                    $in_evidenza_filter = '';
                                    if ($config_feed && isset($config_feed->query_params->in_evidenza_filter)) {
                                        $in_evidenza_filter = (string) $config_feed->query_params->in_evidenza_filter;
                                    }
                                    ?>
                                    <select name="feed_query_in_evidenza_<?php echo $index; ?>">
                                        <option value="prioritize" <?php selected($in_evidenza_filter, 'prioritize'); selected($in_evidenza_filter, ''); ?>>In evidenza in cima (poi gli altri)</option>
                                        <option value="only" <?php selected($in_evidenza_filter, 'only'); ?>>Solo articoli in evidenza</option>
                                        <option value="exclude" <?php selected($in_evidenza_filter, 'exclude'); ?>>Escludi articoli in evidenza</option>
                                    </select>
                                    <p class="description">Con &quot;In evidenza in cima&quot;, se chiedi 10 articoli e ce ne sono 2 in evidenza, compaiono per primi i 2 e poi altri 8. &quot;Solo in evidenza&quot; restituisce unicamente quelli flaggati.</p>
                                </td>
                            </tr>

                            <tr>
                                <th scope="row">Post Types</th>
                                <td>
                                    <div class="autocomplete-container" style="position: relative;">
                                        <input type="text" id="post-types-<?php echo $index; ?>" placeholder="Cerca post types..." style="width: 300px;" />
                                        <div id="post-types-suggestions-<?php echo $index; ?>" class="autocomplete-suggestions" style="display: none; position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #ccc; max-height: 200px; overflow-y: auto; z-index: 1000;"></div>
                                        <div id="post-types-selected-<?php echo $index; ?>" class="selected-items" style="margin-top: 5px;">
                                            <?php
                                            if ($config_feed && isset($config_feed->query_params->post_types)) {
                                                foreach ($config_feed->query_params->post_types as $post_type): 
                                            ?>
                                                <span class="selected-item" style="display: inline-block; background: #00a32a; color: white; padding: 2px 8px; margin: 2px; border-radius: 3px; font-size: 12px;">
                                                    <?php echo esc_html($post_type); ?>
                                                    <input type="hidden" name="feed_query_post_types_<?php echo $index; ?>[]" value="<?php echo esc_attr($post_type); ?>" />
                                                    <span onclick="removeSelectedItem(this)" style="cursor: pointer; margin-left: 5px;">×</span>
                                                </span>
                                            <?php endforeach; ?>
                                            <?php } ?>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <input type="hidden" id="newsletter_feeds_compiled" name="newsletter_feeds_compiled" value="" />
        
        <button type="button" onclick="addFeed()" class="button">+ Aggiungi Feed</button>
        
        <script>
        if (typeof window.newsletterFeedBaseUrl === 'undefined') {
            <?php
            $baseFeedPath = trailingslashit(home_url('/nl-feed'));
            if (is_multisite()) {
                $currentSiteId = function_exists('get_current_blog_id') ? get_current_blog_id() : 1;
                $baseFeedPath .= 'site-' . $currentSiteId . '/';
            }
            ?>
            window.newsletterFeedBaseUrl = '<?php echo esc_url($baseFeedPath); ?>';
        }
        // JavaScript per autocompletamento e gestione interfaccia
        let autocompleteTimeout;
        
        // Funzioni per l'autocompletamento delle tassonomie
        function setupTaxonomyAutocomplete(inputId, suggestionsId, selectedId, inputName) {
            const input = document.getElementById(inputId);
            const suggestionsContainer = document.getElementById(suggestionsId);
            const selectedContainer = document.getElementById(selectedId);
            
            input.addEventListener('input', function(event) {
                const searchTerm = event.target.value.trim();
                
                if (searchTerm.length < 2) {
                    suggestionsContainer.style.display = 'none';
                    return;
                }
                
                // Clear timeout precedente
                clearTimeout(autocompleteTimeout);
                
                // Debounce la ricerca
                autocompleteTimeout = setTimeout(() => {
                    searchTaxonomyAutocomplete(searchTerm, suggestionsContainer, selectedId, inputName);
                }, 300);
            });
            
            input.addEventListener('keydown', function(event) {
                // Gestione tasti speciali
                if (event.key === 'ArrowDown') {
                    event.preventDefault();
                    const firstSuggestion = suggestionsContainer.querySelector('.suggestion-item');
                    if (firstSuggestion) {
                        firstSuggestion.classList.add('highlighted');
                        firstSuggestion.focus();
                    }
                } else if (event.key === 'Escape') {
                    suggestionsContainer.style.display = 'none';
                }
            });
        }
        
        function setupPostTypesAutocomplete(inputId, suggestionsId, selectedId, inputName) {
            const input = document.getElementById(inputId);
            const suggestionsContainer = document.getElementById(suggestionsId);
            const selectedContainer = document.getElementById(selectedId);
            
            input.addEventListener('input', function(event) {
                const searchTerm = event.target.value.trim();
                
                if (searchTerm.length < 2) {
                    suggestionsContainer.style.display = 'none';
                    return;
                }
                
                // Clear timeout precedente
                clearTimeout(autocompleteTimeout);
                
                // Debounce la ricerca
                autocompleteTimeout = setTimeout(() => {
                    searchAutocomplete(searchTerm, 'post_types', suggestionsContainer, selectedId, inputName);
                }, 300);
            });
            
            input.addEventListener('keydown', function(event) {
                // Gestione tasti speciali
                if (event.key === 'ArrowDown') {
                    event.preventDefault();
                    const firstSuggestion = suggestionsContainer.querySelector('.suggestion-item');
                    if (firstSuggestion) {
                        firstSuggestion.classList.add('highlighted');
                        firstSuggestion.focus();
                    }
                } else if (event.key === 'Escape') {
                    suggestionsContainer.style.display = 'none';
                }
            });
        }
        
        function searchTaxonomyAutocomplete(searchTerm, suggestionsContainer, selectedId, inputName) {
            fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'get_taxonomies_autocomplete',
                    search: searchTerm,
                    taxonomy: 'all',
                    nonce: '<?php echo wp_create_nonce('newsletter_autocomplete'); ?>'
                })
            })
            .then(response => response.json())
            .then(data => {
                displaySuggestions(data, suggestionsContainer, selectedId, inputName, 'taxonomy');
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
        
        function searchAutocomplete(searchTerm, type, suggestionsContainer, selectedId, inputName) {
            fetch(ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    action: 'get_' + type + '_autocomplete',
                    search: searchTerm,
                    nonce: '<?php echo wp_create_nonce('newsletter_autocomplete'); ?>'
                })
            })
            .then(response => response.json())
            .then(data => {
                displaySuggestions(data, suggestionsContainer, selectedId, inputName, type);
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
        
        function displaySuggestions(suggestions, container, selectedId, inputName, type) {
            container.innerHTML = '';
            
            if (suggestions.length === 0) {
                container.style.display = 'none';
                return;
            }
            
            suggestions.forEach(suggestion => {
                const div = document.createElement('div');
                div.className = 'suggestion-item';
                div.textContent = suggestion.text;
                div.style.padding = '8px';
                div.style.cursor = 'pointer';
                div.style.borderBottom = '1px solid #eee';
                
                div.addEventListener('click', () => {
                    addSelectedItem(suggestion, selectedId, inputName, type);
                    container.style.display = 'none';
                });
                
                div.addEventListener('mouseenter', () => {
                    // Rimuovi highlight precedente
                    suggestions.forEach(s => s.classList.remove('highlighted'));
                    div.classList.add('highlighted');
                });
                
                container.appendChild(div);
            });
            
            container.style.display = 'block';
        }
        
        function addSelectedItem(suggestion, selectedId, inputName, type) {
            const container = document.getElementById(selectedId);
            
            // Controlla se il termine è già presente
            const existingInputs = container.querySelectorAll(`input[name="${inputName}[]"]`);
            for (let input of existingInputs) {
                if (input.value === suggestion.id || input.value === suggestion.slug) {
                    return; // Già presente
                }
            }
            
            const span = document.createElement('span');
            span.className = 'selected-item';
            // Usa colore rosso per exclude, blu per include
            const bgColor = inputName.includes('exclude') ? '#dc3232' : '#0073aa';
            span.style.cssText = `display: inline-block; background: ${bgColor}; color: white; padding: 2px 8px; margin: 2px; border-radius: 3px; font-size: 12px;`;
            
            const value = type === 'taxonomy' ? (suggestion.slug || suggestion.id) : suggestion.id;
            // suggestion.text già contiene "nome_termine (nome_tassonomia)" dall'autocomplete
            span.innerHTML = `
                ${suggestion.text}
                <input type="hidden" name="${inputName}[]" value="${value}" />
                <span onclick="removeSelectedItem(this)" style="cursor: pointer; margin-left: 5px;">×</span>
            `;
            
            container.appendChild(span);
        }
        
        function addSelectedPostType(suggestion, selectedId, inputName) {
            const container = document.getElementById(selectedId);
            
            // Controlla se il post type è già presente
            const existingInputs = container.querySelectorAll(`input[name="${inputName}[]"]`);
            for (let input of existingInputs) {
                if (input.value === suggestion.name) {
                    return; // Già presente
                }
            }
            
            const span = document.createElement('span');
            span.className = 'selected-item';
            span.style.cssText = 'display: inline-block; background: #00a32a; color: white; padding: 2px 8px; margin: 2px; border-radius: 3px; font-size: 12px;';
            
            span.innerHTML = `
                ${suggestion.text}
                <input type="hidden" name="${inputName}[]" value="${suggestion.name}" />
                <span onclick="removeSelectedItem(this)" style="cursor: pointer; margin-left: 5px;">×</span>
            `;
            
            container.appendChild(span);
        }

        function removeSelectedItem(element) {
            element.closest('.selected-item').remove();
        }

        function removeItem(arg1, arg2) {
            const evt = arg2 ? arg1 : null;
            const button = arg2 ? arg2 : arg1;
            try { if (evt && evt.stopPropagation) evt.stopPropagation(); } catch (e) {}
            const item = (button && button.closest) ? button.closest('.feed-item, .date-item') : null;
            if (item && item.parentNode) {
                item.parentNode.removeChild(item);
            }
        }

        function viewFeed(button) {
            const feedItem = button.closest('.feed-item');
            if (!feedItem) return;
            const fileInput = feedItem.querySelector("input[name^='feed_file_']");
            if (!fileInput || !fileInput.value.trim()) {
                alert('Inserisci il nome file del feed prima di visualizzarlo.');
                return;
            }
            const baseUrl = window.newsletterFeedBaseUrl || '';
            window.open(baseUrl + fileInput.value.trim(), '_blank');
        }

        function toggleFeedConfig(index) {
            const config = document.getElementById('config-' + index);
            const toggle = document.getElementById('toggle-' + index);
            
            if (config.style.display === 'none') {
                config.style.display = 'block';
                toggle.textContent = '▲';
            } else {
                config.style.display = 'none';
                toggle.textContent = '▼';
            }
        }
        
        // Inizializza autocompletamento per tutti i feed esistenti
        document.addEventListener('DOMContentLoaded', function() {
            <?php foreach ($feeds as $index => $feed): ?>
            setupTaxonomyAutocomplete('include-tags-<?php echo $index; ?>', 'include-suggestions-<?php echo $index; ?>', 'include-selected-<?php echo $index; ?>', 'feed_query_include_taxonomies_<?php echo $index; ?>');
            setupTaxonomyAutocomplete('exclude-tags-<?php echo $index; ?>', 'exclude-suggestions-<?php echo $index; ?>', 'exclude-selected-<?php echo $index; ?>', 'feed_query_exclude_taxonomies_<?php echo $index; ?>');
            setupPostTypesAutocomplete('post-types-<?php echo $index; ?>', 'post-types-suggestions-<?php echo $index; ?>', 'post-types-selected-<?php echo $index; ?>', 'feed_query_post_types_<?php echo $index; ?>');
            <?php endforeach; ?>

            // Event delegation: usa il contenitore corretto #feeds-container
            const feedsContainerEl = document.getElementById('feeds-container');
            if (feedsContainerEl) {
                feedsContainerEl.addEventListener('click', function(e) {
                    const btn = e.target.closest('.remove-btn');
                    if (btn && feedsContainerEl.contains(btn)) {
                        e.stopPropagation();
                        const item = btn.closest('.feed-item');
                        if (item && item.parentNode) {
                            item.parentNode.removeChild(item);
                        }
                    }
                });
            }
            // Re-indicizza i nomi dei campi prima dell'invio del form
            const feedsContainer = document.getElementById('feeds-container');
            const datesContainer = document.getElementById('dates-container');
            const form = (feedsContainer ? feedsContainer.closest('form') : null) || (datesContainer ? datesContainer.closest('form') : null) || document.querySelector('form');
            if (form) {
                form.addEventListener('submit', function() {
                    // Re-index feeds
                    const feedItems = document.querySelectorAll('#feeds-container .feed-item');
                    let i = 0;
                    const compiledFeeds = [];
                    feedItems.forEach(item => {
                        // feed_name_X
                        const nameInput = item.querySelector("input[name^='feed_name_']");
                        if (nameInput) nameInput.name = `feed_name_${i}`;

                        // feed_file_X
                        const fileInput = item.querySelector("input[name^='feed_file_']");
                        if (fileInput) fileInput.name = `feed_file_${i}`;

                        // posts_per_page
                        const pppInput = item.querySelector("input[name^='feed_query_posts_']");
                        if (pppInput) pppInput.name = `feed_query_posts_${i}`;

                        const inEvidenzaSelect = item.querySelector("select[name^='feed_query_in_evidenza_']");
                        if (inEvidenzaSelect) inEvidenzaSelect.name = `feed_query_in_evidenza_${i}`;

                        // include/exclude taxonomies hidden inputs
                        item.querySelectorAll("input[name^='feed_query_include_taxonomies_']").forEach(inp => {
                            inp.name = `feed_query_include_taxonomies_${i}[]`;
                        });
                        item.querySelectorAll("input[name^='feed_query_exclude_taxonomies_']").forEach(inp => {
                            inp.name = `feed_query_exclude_taxonomies_${i}[]`;
                        });

                        // post types hidden inputs
                        item.querySelectorAll("input[name^='feed_query_post_types_']").forEach(inp => {
                            inp.name = `feed_query_post_types_${i}[]`;
                        });

                        // Build compiled feed object
                        const feedObj = {
                            name: nameInput ? nameInput.value : '',
                            file: fileInput ? fileInput.value : '',
                            query_params: {
                                posts_per_page: pppInput && pppInput.value ? parseInt(pppInput.value, 10) : 10,
                                include_taxonomies: Array.from(item.querySelectorAll("input[name^='feed_query_include_taxonomies_']")).map(el => el.value),
                                exclude_taxonomies: Array.from(item.querySelectorAll("input[name^='feed_query_exclude_taxonomies_']")).map(el => el.value),
                                post_types: Array.from(item.querySelectorAll("input[name^='feed_query_post_types_']")).map(el => el.value),
                                in_evidenza_filter: inEvidenzaSelect ? inEvidenzaSelect.value : ''
                            }
                        };
                        compiledFeeds.push(feedObj);

                        i++;
                    });

                    // Write compiled feeds JSON to hidden field
                    const compiledInput = document.getElementById('newsletter_feeds_compiled');
                    if (compiledInput) {
                        compiledInput.value = JSON.stringify(compiledFeeds);
                    }

                    // Re-index dates
                    const dateItems = document.querySelectorAll('#dates-container .date-item');
                    let d = 0;
                    dateItems.forEach(item => {
                        const dateInput = item.querySelector("input[name^='date_date_']");
                        if (dateInput) dateInput.name = `date_date_${d}`;

                        const descInput = item.querySelector("input[name^='date_description_']");
                        if (descInput) descInput.name = `date_description_${d}`;

                        d++;
                    });
                });
            }
        });
        
        // Nascondi suggerimenti quando si clicca fuori
        document.addEventListener('click', function(event) {
            if (!event.target.closest('.autocomplete-container')) {
                document.querySelectorAll('.autocomplete-suggestions').forEach(suggestions => {
                    suggestions.style.display = 'none';
                });
            }
        });
        </script>
        <?php
    }
    
    public static function render_dates_interface($json_data) {
        $dates = json_decode($json_data, true) ?: [];
        ?>
        <div id="dates-container">
            <?php foreach ($dates as $index => $date): ?>
            <div class="date-item" style="border: 1px solid #ddd; padding: 15px; margin: 10px 0; background: #f9f9f9;">
                <div style="display: flex; align-items: center; margin-bottom: 10px;">
                    <input type="text" name="date_date_<?php echo $index; ?>" value="<?php echo esc_attr($date['date'] ?? ''); ?>" placeholder="XXXX-01-06 oppure 2025-12-24" style="width: 220px; margin-right: 10px;" />
                    <input type="text" name="date_description_<?php echo $index; ?>" placeholder="Descrizione" value="<?php echo esc_attr($date['description'] ?? ''); ?>" style="width: 300px; margin-right: 10px;" />
                    <button type="button" onclick="removeItem(this)" class="remove-btn">Rimuovi</button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <button type="button" onclick="addDate()" class="button">+ Aggiungi Data</button>
        <?php
    }
}
