<?php
namespace NewsletterBridge\Admin\Tabs;

use NewsletterBridge\Lib\DB;

/**
 * Tab Import per l'admin
 */
class ImportTab {
    
    public static function render() {
        ?>
        <h2>Importa da Tagmailer</h2>
        <p>Importa gli utenti da un file CSV esportato da Tagmailer.</p>
        
        <form method="post" enctype="multipart/form-data">
            <?php wp_nonce_field('import_csv_nonce', 'import_csv_nonce'); ?>
            
            <table class="form-table">
                <tr>
                    <th scope="row">File CSV</th>
                    <td>
                        <input type="file" name="csv_file" accept=".csv" required />
                        <p class="description">Seleziona il file CSV esportato da Tagmailer</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Modalità</th>
                    <td>
                        <label>
                            <input type="radio" name="import_mode" value="preview" checked />
                            Anteprima (solo visualizza i dati)
                        </label><br>
                        <label>
                            <input type="radio" name="import_mode" value="import" />
                            Importa effettivamente i dati
                        </label>
                        <p class="description">Scegli se fare solo un'anteprima o importare realmente i dati</p>
                    </td>
                </tr>
            </table>
            
            <?php submit_button('Importa da Tagmailer', 'primary', 'import_csv'); ?>
        </form>
        
        <?php
        // Gestione dell'import
        if (isset($_POST['import_csv']) && isset($_POST['import_csv_nonce'])) {
            if (wp_verify_nonce($_POST['import_csv_nonce'], 'import_csv_nonce')) {
                self::handle_import();
            }
        }
        ?>
        
        <style>
        .import-results {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #f9f9f9;
        }
        .import-success {
            border-color: #00a32a;
            background: #f0f8f0;
        }
        .import-error {
            border-color: #d63638;
            background: #fdf0f0;
        }
        .csv-preview {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            margin: 10px 0;
        }
        .csv-preview table {
            width: 100%;
            border-collapse: collapse;
        }
        .csv-preview th,
        .csv-preview td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
            font-size: 12px;
        }
        .csv-preview th {
            background: #f0f0f0;
            font-weight: bold;
        }
        </style>
        <?php
    }
    
    public static function handle_import() {
        if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            echo '<div class="import-results import-error">';
            echo '<h3>❌ Errore</h3>';
            echo '<p>Nessun file selezionato o errore nel caricamento del file.</p>';
            echo '</div>';
            return;
        }
        
        $file = $_FILES['csv_file'];
        $import_mode = $_POST['import_mode'] ?? 'preview';
        
        // Recupera il dominio dalla configurazione del database
        $db_config = \NewsletterBridge\Config\DatabaseConfig::getConfig();
        $domain = $db_config->domain;
        
        // Verifica che sia un file CSV
        $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if ($file_extension !== 'csv') {
            echo '<div class="import-results import-error">';
            echo '<h3>❌ Errore</h3>';
            echo '<p>Il file deve essere un CSV.</p>';
            echo '</div>';
            return;
        }
        
        // Leggi il file CSV
        $csv_data = self::read_csv_file($file['tmp_name']);
        if (empty($csv_data)) {
            echo '<div class="import-results import-error">';
            echo '<h3>❌ Errore</h3>';
            echo '<p>Impossibile leggere il file CSV o file vuoto.</p>';
            echo '</div>';
            return;
        }
        
        // Valida l'header del CSV
        $expected_headers = [
            'IdIscritto', 'Email', 'Lista', 'Marketing', 'CessioneATerzi', 'IpIscrizione', 
            'DataIscrizione', 'Nome', 'Cognome', 'Anno', 'DataDiNascita', 'Genere', 
            'Provincia', 'Professione', 'TitoloDiStudio', 'Cellulare', 'PIVAoCF', 'Cap', 
            'Azienda', 'ClienteCategoria', 'ClienteTipo', 'AutoMarca', 'AutoModello'
        ];
        
        $csv_headers = array_keys($csv_data[0]);
        $missing_headers = array_diff($expected_headers, $csv_headers);
        
        if (!empty($missing_headers)) {
            echo '<div class="import-results import-error">';
            echo '<h3>❌ Errore</h3>';
            echo '<p>Header CSV mancanti: ' . implode(', ', $missing_headers) . '</p>';
            echo '<p>Header trovati: ' . implode(', ', $csv_headers) . '</p>';
            echo '</div>';
            return;
        }
        
        if ($import_mode === 'preview') {
            self::show_preview($csv_data, $domain);
        } else {
            self::perform_import($csv_data, $domain);
        }
    }
    
    private static function read_csv_file($file_path) {
        $data = [];
        $handle = fopen($file_path, 'r');
        
        if ($handle === false) {
            return [];
        }
        
        // Leggi la prima riga come header
        $headers = fgetcsv($handle, 1000, ';');
        if ($headers === false) {
            fclose($handle);
            return [];
        }
        
        // Leggi le righe di dati
        while (($row = fgetcsv($handle, 1000, ';')) !== false) {
            if (count($row) === count($headers)) {
                $data[] = array_combine($headers, $row);
            }
        }
        
        fclose($handle);
        return $data;
    }
    
    private static function show_preview($csv_data, $domain) {
        $total_rows = count($csv_data);
        $sample_rows = array_slice($csv_data, 0, 10); // Mostra solo le prime 10 righe
        
        echo '<div class="import-results import-success">';
        echo '<h3>📊 Anteprima Import</h3>';
        echo '<p><strong>Dominio:</strong> ' . esc_html($domain) . '</p>';
        echo '<p><strong>Righe totali:</strong> ' . $total_rows . '</p>';
        echo '<p><strong>Righe mostrate:</strong> ' . count($sample_rows) . ' (prime 10)</p>';
        
        echo '<div class="csv-preview">';
        echo '<table>';
        echo '<thead><tr>';
        foreach (array_keys($sample_rows[0]) as $header) {
            echo '<th>' . esc_html($header) . '</th>';
        }
        echo '</tr></thead>';
        echo '<tbody>';
        
        foreach ($sample_rows as $row) {
            echo '<tr>';
            foreach ($row as $value) {
                echo '<td>' . esc_html($value) . '</td>';
            }
            echo '</tr>';
        }
        
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
        
        // Mostra un esempio di import con i dati processati
        if (!empty($sample_rows)) {
            echo '<style>
                .import-example {
                    background: #f9f9f9;
                    border: 1px solid #ddd;
                    border-radius: 5px;
                    padding: 15px;
                    margin: 15px 0;
                }
                .example-data {
                    background: white;
                    padding: 10px;
                    border-radius: 3px;
                    border-left: 4px solid #0073aa;
                }
                .example-data p {
                    margin: 5px 0;
                }
                .example-data code {
                    background: #e1e1e1;
                    padding: 2px 4px;
                    border-radius: 3px;
                    font-family: monospace;
                }
            </style>';
            
            echo '<div class="import-example">';
            echo '<h4>🔍 Esempio di Import (prima riga)</h4>';
            
            $example_row = $sample_rows[0];
            $email = trim($example_row['Email']);
            $inviaDem = self::normalizeMarketingFlag($example_row['Marketing']);
            $ip = substr(trim($example_row['IpIscrizione']) ?: '127.0.0.1', 0, 45); // Limita a 45 caratteri
            $dataIscrizione = trim($example_row['DataIscrizione']) ?: date('Y-m-d H:i:s');
            
            echo '<div class="example-data">';
            echo '<p><strong>Email:</strong> ' . esc_html($email) . '</p>';
            echo '<p><strong>Marketing:</strong> ' . esc_html($example_row['Marketing']) . ' → <code>inviaDem = ' . $inviaDem . '</code></p>';
            echo '<p><strong>IP:</strong> ' . esc_html($ip) . '</p>';
            echo '<p><strong>Data Iscrizione:</strong> ' . esc_html($dataIscrizione) . '</p>';
            echo '<p><strong>Dominio:</strong> ' . esc_html($domain) . '</p>';
            
            // Simula la conversione della data
            $convertedDate = self::convertDateToMySQL($dataIscrizione);
            echo '<p><strong>Data convertita:</strong> ' . esc_html($convertedDate) . '</p>';
            
            // Mostra i gruppi che verranno utilizzati
            if ($inviaDem == 1) {
                echo '<p><strong>Gruppi MailUp:</strong> Principale + DEM (entrambi)</p>';
            } else {
                echo '<p><strong>Gruppi MailUp:</strong> Solo Principale</p>';
            }
            
            echo '<p><strong>Campi DB:</strong> deleted=0, domain=' . esc_html($domain) . ', email=' . esc_html($email) . ', trattamento_privacy_day=' . esc_html($convertedDate) . ', invio_dem=' . $inviaDem . ', from_ip=' . esc_html($ip) . '</p>';
            echo '</div>';
            echo '</div>';
        }
        
        echo '<p><em>Se i dati sembrano corretti, cambia la modalità in "Importa effettivamente i dati" e ricarica.</em></p>';
        echo '</div>';
    }
    
    private static function perform_import($csv_data, $domain) {
        // Recupera sempre il dominio dalla configurazione del database
        $db_config = \NewsletterBridge\Config\DatabaseConfig::getConfig();
        $current_domain = $db_config->domain;
        
        $total_rows = count($csv_data);
        $imported = 0;
        $errors = 0;
        $skipped = 0;
        $start_time = time();
        
        $db_service = new DB();
        
        echo '<div class="import-results">';
        echo '<h3>🔄 Importazione in corso...</h3>';
        echo '<p>Dominio: ' . esc_html($current_domain) . '</p>';
        echo '<p>Righe totali: ' . $total_rows . '</p>';
        echo '<p><strong>⚠️ Import in corso - Non chiudere questa pagina!</strong></p>';
        
        echo '<div style="max-height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; margin: 10px 0;">';
        
        // Processa tutti i record in una volta, con flush per mostrare il progresso
        foreach ($csv_data as $index => $row) {
            $email = trim($row['Email']);
            
            if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                echo '<p style="color: #d63638;">❌ Riga ' . ($index + 1) . ': Email non valida - ' . esc_html($email) . '</p>';
                $errors++;
                continue;
            }
            
            // Prepara i dati per l'import (solo campi base)
            $import_data = [
                'email' => $email,
                'inviaDem' => self::normalizeMarketingFlag($row['Marketing']),
                'ip' => substr(trim($row['IpIscrizione']) ?: '127.0.0.1', 0, 45), // Limita a 45 caratteri per il campo from_ip
                'domain' => $current_domain,
                'dataIscrizione' => trim($row['DataIscrizione']) ?: date('Y-m-d H:i:s')
            ];
            
            try {
                $result = $db_service->importUser($import_data);
                
                if ($result[0] === 'SUCCESS') {
                    echo '<p style="color: #00a32a;">✅ Riga ' . ($index + 1) . ': ' . esc_html($email) . ' - ' . $result[1] . '</p>';
                    $imported++;
                } else {
                    echo '<p style="color: #d63638;">❌ Riga ' . ($index + 1) . ': ' . esc_html($email) . ' - ' . $result[1] . '</p>';
                    $errors++;
                }
            } catch (Exception $e) {
                echo '<p style="color: #d63638;">❌ Riga ' . ($index + 1) . ': ' . esc_html($email) . ' - Errore: ' . $e->getMessage() . '</p>';
                $errors++;
            }
            
            // Flush per mostrare il progresso in tempo reale
            if (($index + 1) % 10 == 0) {
                echo '<p style="color: #666; font-style: italic;">📊 Processate ' . ($index + 1) . ' / ' . $total_rows . ' righe...</p>';
                flush();
            }
        }
        
        echo '</div>';
        
        // Mostra risultati finali
        $duration = time() - $start_time;
        $minutes = floor($duration / 60);
        $seconds = $duration % 60;
        
        echo '<h3>🎉 Import Completato!</h3>';
        echo '<p><strong>Durata:</strong> ' . $minutes . 'm ' . $seconds . 's</p>';
        echo '<p><strong>Righe totali:</strong> ' . $total_rows . '</p>';
        
        echo '<h4>📈 Risultati Finali:</h4>';
        echo '<ul>';
        echo '<li><strong>Importati:</strong> ' . $imported . '</li>';
        echo '<li><strong>Errori:</strong> ' . $errors . '</li>';
        echo '<li><strong>Saltati:</strong> ' . $skipped . '</li>';
        echo '</ul>';
        
        if ($imported > 0) {
            echo '<p style="color: #00a32a; font-size: 18px;"><strong>✅ Import completato con successo!</strong></p>';
        }
        
        echo '</div>';
    }
    
    private static function show_final_results($progress) {
        $duration = time() - $progress['start_time'];
        $minutes = floor($duration / 60);
        $seconds = $duration % 60;
        
        // Recupera il dominio dalla configurazione del database
        $db_config = \NewsletterBridge\Config\DatabaseConfig::getConfig();
        $current_domain = $db_config->domain;
        
        echo '<div class="import-results import-success">';
        echo '<h3>🎉 Import Completato!</h3>';
        echo '<p><strong>Dominio:</strong> ' . esc_html($current_domain) . '</p>';
        echo '<p><strong>Durata:</strong> ' . $minutes . 'm ' . $seconds . 's</p>';
        echo '<p><strong>Righe totali:</strong> ' . $progress['total_rows'] . '</p>';
        
        echo '<h4>📈 Risultati Finali:</h4>';
        echo '<ul>';
        echo '<li><strong>Importati:</strong> ' . $progress['imported'] . '</li>';
        echo '<li><strong>Errori:</strong> ' . $progress['errors'] . '</li>';
        echo '<li><strong>Saltati:</strong> ' . $progress['skipped'] . '</li>';
        echo '</ul>';
        
        if ($progress['imported'] > 0) {
            echo '<p style="color: #00a32a; font-size: 18px;"><strong>✅ Import completato con successo!</strong></p>';
        }
        
        echo '</div>';
    }
    
    /**
     * Converte la data dal CSV nel formato MySQL (copia del metodo da DB.php)
     */
    private static function convertDateToMySQL($dateString) {
        if (empty($dateString)) {
            return date('Y-m-d H:i:s');
        }
        
        // Prova diversi formati di data comuni nei CSV
        $formats = [
            'Y-m-d H:i:s',     // 2023-12-25 14:30:00
            'Y-m-d',           // 2023-12-25
            'd/m/Y H:i:s',     // 25/12/2023 14:30:00
            'd/m/Y',           // 25/12/2023
            'd-m-Y H:i:s',     // 25-12-2023 14:30:00
            'd-m-Y',           // 25-12-2023
            'Y/m/d H:i:s',     // 2023/12/25 14:30:00
            'Y/m/d',           // 2023/12/25
        ];
        
        foreach ($formats as $format) {
            $date = \DateTime::createFromFormat($format, $dateString);
            if ($date !== false) {
                return $date->format('Y-m-d H:i:s');
            }
        }
        
        // Se nessun formato funziona, prova con strtotime
        $timestamp = strtotime($dateString);
        if ($timestamp !== false) {
            return date('Y-m-d H:i:s', $timestamp);
        }
        
        // Fallback alla data corrente
        return date('Y-m-d H:i:s');
    }

    /**
     * Normalizza il valore della colonna Marketing in un flag booleano
     */
    private static function normalizeMarketingFlag($value) {
        if (is_bool($value)) {
            return $value ? 1 : 0;
        }

        $normalized = strtolower(trim((string) $value));
        $trueValues = ['si', 'sì', 'true', '1', 'yes'];

        return in_array($normalized, $trueValues, true) ? 1 : 0;
    }
}
