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

use NewsletterBridge\Config\NewsletterConfig;
use NewsletterBridge\Services\External\Sender;
use NewsletterBridge\Services\Feed\FeedGenerator;
use NewsletterBridge\Utils\ServiceContainer;
use NewsletterBridge\Config\SiteConfig;
use NewsletterBridge\Admin\Tabs\Newsletter\NewsletterProcessor;
use NewsletterBridge\Admin\Tabs\Newsletter\NewsletterCommands;

/**
 * Tab Newsletter per l'admin - File principale
 * Responsabilità: Orchestrazione e coordinamento
 */
class NewsletterTab {
    
    public static function init() {
        NewsletterAutocomplete::init();
    }
    
    public static function render() {
        // Mostra avviso se l'UI è limitata
        self::render_ui_limited_notice();
        
        $config = NewsletterConfig::getConfig();
        
        // Converti gli oggetti in array per il rendering
        $feeds_array = [];
        foreach ($config->feeds as $feed) {
            $feed_array = [
                'name' => $feed->name,
                'file' => $feed->file
            ];
            
            // Includi query_params se presenti
            if (isset($feed->query_params)) {
                $feed_array['query_params'] = (array) $feed->query_params;
            }
            
            $feeds_array[] = $feed_array;
        }
        $newsletter_feeds = json_encode($feeds_array);
        
        $dates_array = [];
        foreach ($config->datesToExclude as $date) {
            $dates_array[] = [
                'date' => $date->date,
                'description' => $date->description
            ];
        }
        $newsletter_dates = json_encode($dates_array);
        $feed_base_url = esc_url(trailingslashit(home_url('/nl-feed/')));
        
        ?>
        <style>
        @media (max-width: 768px) {
            .newsletter-flex-container {
                flex-direction: column !important;
            }
        }
        .newsletter-flex-container {
            display: flex;
            gap: 20px;
            margin: 20px 0;
        }
        .newsletter-flex-item {
            flex: 1;
        }
        </style>
        
        <div class="wrap">
            <h1>Newsletter Bridge - Configurazione Newsletter</h1>
                
                
                <h2>Comandi Newsletter</h2>
                <p>Esegui operazioni sulla newsletter.</p>
                
                <form method="post" action="" style="margin: 20px 0;">
                    <?php wp_nonce_field('newsletter_command', 'newsletter_nonce'); ?>
                    <button type="submit" name="newsletter_action" value="generate_xml" class="button button-primary">
                        📄 Genera XML
                    </button>
                    <button type="submit" name="newsletter_action" value="send_newsletter" class="button button-secondary">
                        📧 Invia Newsletter Completa
                    </button>
                </form>
                
                <h2>Stato Newsletter</h2>
                <div style="background: #f9f9f9; padding: 15px; border-left: 4px solid #0073aa; margin: 20px 0;">
                    <?php
                    // Recupera la data dell'ultimo invio (gestisce automaticamente multisite)
                    $last_send_date = \NewsletterBridge\Config\SiteConfig::getLastNewsletterDate();
                    $domain = get_bloginfo('name');
                    if ($last_send_date) {
                        $formatted_date = date('d/m/Y H:i:s', strtotime($last_send_date));
                        echo '<p><strong>📅 Ultimo invio:</strong> ' . esc_html($formatted_date) . '</p>';
                    } else {
                        echo '<p><strong>📅 Ultimo invio:</strong> <em>Mai inviata</em></p>';
                    }
                    ?>
                </div>
                
                <form method="post" action="">
                    <?php wp_nonce_field('newsletter_admin_nonce', 'newsletter_admin_nonce'); ?>
                    
                    <h2>Configurazione Newsletter</h2>
                    <table class="form-table">
                        <tr>
                            <th scope="row">Titolo Newsletter</th>
                            <td>
                                <input type="text" name="newsletter_title" value="<?php echo esc_attr($config->newsletter_title ?? ''); ?>" class="regular-text" placeholder="<?php echo esc_attr(get_bloginfo('name')); ?> - Tutte le news del {{date}}" />
                                <p class="description">Titolo della newsletter. Usa {{date}} per inserire la data corrente in formato italiano.</p>
                            </td>
                        </tr>
                    </table>
                
                <div class="newsletter-flex-container">
                    <div class="newsletter-flex-item">
                        <h2>Configurazione Feed</h2>
                        <p>Configura i feed newsletter e le relative query per la selezione dei contenuti.</p>
                        
                        <div id="feeds-section">
                            <?php NewsletterInterface::render_feeds_interface($newsletter_feeds, $config->feeds); ?>
                        </div>
                    </div>
                    
                    <div class="newsletter-flex-item">
                        <h2>Date da Escludere</h2>
                        <p>Specifica le date in cui non inviare newsletter.</p>
                        
                        <div id="dates-section">
                            <?php NewsletterInterface::render_dates_interface($newsletter_dates); ?>
                        </div>
                    </div>
                </div>
                
                <?php submit_button('Salva Impostazioni'); ?>
            </form>
        </div>
        
        <script>
        // JavaScript per la gestione dinamica dei feed e date
        let feedIndex = <?php echo count($feeds_array); ?>;
        let dateIndex = <?php echo count($dates_array); ?>;
        
        function addFeed() {
            const container = document.getElementById('feeds-container');
            const feedHtml = `
                <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_${feedIndex}" placeholder="Nome feed" style="width: 150px;" />
                        <input type="text" name="feed_file_${feedIndex}" placeholder="Nome 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>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', feedHtml);
            feedIndex++;
        }
        
        function addDate() {
            const container = document.getElementById('dates-container');
            const dateHtml = `
                <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_${dateIndex}" placeholder="XXXX-01-06 oppure 2025-12-24" style="width: 220px; margin-right: 10px;" />
                        <input type="text" name="date_description_${dateIndex}" placeholder="Descrizione" style="width: 300px; margin-right: 10px;" />
                        <button type="button" onclick="removeItem(this)" class="remove-btn">Rimuovi</button>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', dateHtml);
            dateIndex++;
        }
        
        </script>
        <?php
    }
    
    public static function save($data) {
        // Gestione flush permalink
        if (isset($_GET['action']) && $_GET['action'] === 'flush_permalinks') {
            flush_rewrite_rules();
            wp_redirect(admin_url('admin.php?page=newsletter-bridge-admin&tab=newsletter&message=permalinks_flushed'));
            exit;
        }
        
        // Gestione comandi newsletter
        if (isset($data['newsletter_action']) && isset($data['newsletter_nonce'])) {
            if (!wp_verify_nonce($data['newsletter_nonce'], 'newsletter_command')) {
                wp_die('Nonce verification failed');
            }
            
            return NewsletterCommands::executeCommand($data['newsletter_action']);
        }
        
        // Processamento dati normali (salvataggio configurazione)
        if (isset($data['newsletter_admin_nonce'])) {
            return NewsletterProcessor::processData($data);
        }
        
        return false;
    }

    private static function resolveLogFilePath(): ?string {
        $candidates = [];
        if (defined('WP_CONTENT_DIR')) {
            $candidates[] = trailingslashit(WP_CONTENT_DIR) . 'debug.log';
        }
        $candidates[] = trailingslashit(ABSPATH) . 'debug.log';
        $domain_slug = sanitize_file_name(get_bloginfo('name'));
        $candidates[] = "/var/log/newsletter_{$domain_slug}.log";

        foreach ($candidates as $candidate) {
            if ($candidate && file_exists($candidate) && is_readable($candidate)) {
                return $candidate;
            }
        }

        return null;
    }

    private static function getLastLogEntry(string $file): ?string {
        try {
            $log = new \SplFileObject($file, 'r');
            $log->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::SKIP_EMPTY);

            $log->seek(PHP_INT_MAX);
            $lastLineIndex = $log->key();
            $linesRead = 0;

            for ($line = $lastLineIndex; $line >= 0 && $linesRead < 10; $line--, $linesRead++) {
                $log->seek($line);
                $current = trim($log->current());
                if ($current === '') {
                    continue;
                }

                if (stripos($current, 'error') !== false || stripos($current, 'fatal') !== false || stripos($current, 'warning') !== false) {
                    return $current;
                }
            }

            return null;
        } catch (\Throwable $e) {
            return null;
        }
    }
    
    /**
     * Verifica se l'UI completa è abilitata (stessa logica di Admin::is_ui_enabled)
     */
    private static function is_ui_enabled() {
        // Prova prima getenv() (variabili di sistema)
        $env_value = getenv('SHOW_UI_NEWSLETTER');
        
        // Se non trovata, prova $_ENV (variabili caricate da file .env)
        if ($env_value === false && isset($_ENV['SHOW_UI_NEWSLETTER'])) {
            $env_value = $_ENV['SHOW_UI_NEWSLETTER'];
        }
        
        // Se ancora non trovata, prova $_SERVER (fallback)
        if ($env_value === false && isset($_SERVER['SHOW_UI_NEWSLETTER'])) {
            $env_value = $_SERVER['SHOW_UI_NEWSLETTER'];
        }
        
        // Se non definita, mostra solo Newsletter (default)
        if ($env_value === false || $env_value === '') {
            return false;
        }
        
        // Se è 'true', mostra tutti i tab
        if (strtolower($env_value) === 'true') {
            return true;
        }
        
        // Se è 'false' o qualsiasi altro valore, mostra solo Newsletter
        return false;
    }
    
    /**
     * Mostra un avviso quando l'UI è limitata
     */
    private static function render_ui_limited_notice() {
        if (!self::is_ui_enabled()) {
            ?>
            <div class="notice notice-info" style="margin: 20px 0; padding: 15px; border-left: 4px solid #0073aa;">
                <p><strong>ℹ️ Interfaccia limitata</strong></p>
                <p>Attualmente è visibile solo il tab Newsletter. Per abilitare tutti i tab di configurazione (MailUp, Database Storage, Import, CDN Immagini), è necessario impostare la variabile d'ambiente <code>SHOW_UI_NEWSLETTER=true</code>.</p>
            </div>
            <?php
        }
    }
}
