<?php
if (!defined('ABSPATH')) {
    exit;
}

class GW_Analytics_Emails
{

    // Solo necesitamos constantes de vista, no de lógica
    const ORIGIN_FIELD_KEY = 'origen';

    private static $instance = null;

    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        // ELIMINADOS: Hooks de AJAX (Ahora los gestiona centralizadamente el Dashboard)
        // Esto evita conflictos y errores de funciones duplicadas
    }

    /**
     * RENDERIZADO DE LA PESTAÑA CORREOS (Tabla Unificada)
     */
    public function render_emails_view()
    {
        global $wpdb;
        $t = $wpdb->prefix . 'e_submissions';
        $tv = $wpdb->prefix . 'e_submissions_values';

        if ($wpdb->get_var("SHOW TABLES LIKE '$t'") != $t) {
            echo '<div class="notice notice-error"><p>Error: Base de datos no encontrada.</p></div>';
            return;
        }

        // 1. Cargar Formularios
        $forms = $wpdb->get_col("SELECT DISTINCT form_name FROM {$t} WHERE status != 'trash'");

        // 2. Cargar Orígenes Únicos
        $raw_origins = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT value FROM {$tv} WHERE `key` = %s AND value != '' LIMIT 100", 'origen'));
        $origins = [];
        if (!empty($raw_origins) && is_array($raw_origins)) {
            foreach ($raw_origins as $ro) {
                $norm = GW_Analytics_Dashboard::normalize_origin_name($ro);
                $origins[$norm] = $norm;
            }
            ksort($origins);
        }

        // Banner de trial eliminado - La información se muestra en la página de Licencias
        ?>
        <div class="efa-wrapper">
            <div class="efa-page-title-row">
                <h2 style="margin:0;">Gestión de Correos</h2>

                <!-- BUSCADOR EN TIEMPO REAL -->
                <div style="flex-grow: 1; max-width: 400px; margin-left: 20px; position: relative;">
                    <span class="dashicons dashicons-search"
                        style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: #888;"></span>
                    <input type="text" id="efa-search-input" placeholder="Buscar por nombre, email, ID..."
                        style="width: 100%; padding-left: 32px; height: 36px; border: 1px solid #ccc; border-radius: 4px;">
                </div>

                <!-- Highlighted Unread Counter -->
                <div id="efa-highlight-badge" class="efa-highlight-badge" style="display:none; margin-left: 15px;">
                    <span class="dashicons dashicons-star-filled"></span>
                    <span id="efa-highlight-count">0</span> destacados sin leer
                </div>



                <div class="efa-header-actions" style="display:flex; gap:10px; margin-left:auto;">
                    <button id="efa-btn-excel" class="efa-btn-excel">
                        <span class="dashicons dashicons-download"
                            style="font-size:14px; width:14px; height:14px; line-height:1.2;"></span> Descargar CSV
                    </button>
                </div>
            </div>

            <hr class="wp-header-end">

            <div class="efa-main-layout">
                <!-- SIDEBAR -->
                <div class="efa-sidebar">
                    <div class="efa-nav-item active" data-filter="all">
                        <span class="dashicons dashicons-email-alt"></span>
                        <span class="efa-nav-label">Todos</span>
                        <span class="efa-nav-badge" id="efa-count-all">0</span>
                    </div>
                    <div class="efa-nav-item" data-filter="unread">
                        <span class="dashicons dashicons-marker"></span>
                        <span class="efa-nav-label">Sin leer</span>
                        <span class="efa-nav-badge" id="efa-count-unread">0</span>
                    </div>
                    <div class="efa-nav-item" data-filter="starred">
                        <span class="dashicons dashicons-star-filled"></span>
                        <span class="efa-nav-label">Destacados</span>
                        <span class="efa-nav-badge" id="efa-count-starred">0</span>
                    </div>
                    <div class="efa-nav-item" data-filter="replied">
                        <span class="dashicons dashicons-email-alt"></span>
                        <span class="efa-nav-label">Enviados</span>
                        <span class="efa-nav-badge" id="efa-count-replied">0</span>
                    </div>
                    <div class="efa-nav-item" data-filter="spam">
                        <span class="dashicons dashicons-warning"></span>
                        <span class="efa-nav-label">Spam</span>
                        <span class="efa-nav-badge" id="efa-count-spam">0</span>
                    </div>
                    <div class="efa-nav-item" data-filter="trash">
                        <span class="dashicons dashicons-trash"></span>
                        <span class="efa-nav-label">Papelera</span>
                        <span class="efa-nav-badge" id="efa-count-trash">0</span>
                    </div>

                    <!-- Estados Section -->
                    <div class="efa-nav-divider"></div>
                    <div class="efa-nav-header">Estados</div>
                    <div id="efa-crm-states-container">
                        <!-- CRM states will be populated by JavaScript -->
                    </div>

                    <!-- Formularios Section -->
                    <div class="efa-nav-divider"></div>
                    <div class="efa-nav-header">Formularios</div>
                    <div id="efa-forms-list-container">
                        <!-- Forms will be populated by JavaScript -->
                    </div>
                </div>

                <!-- MAIN CONTENT -->
                <div class="efa-table-wrapper">

                    <div class="efa-table-toolbar unified">

                        <div class="efa-toolbar-group left">

                            <div class="efa-multiselect-wrapper" id="efa-form-wrapper">
                                <button type="button" class="efa-select-sm efa-multiselect-btn" id="efa-form-btn">
                                    <span>Formularios: Todos</span>
                                    <span class="dashicons dashicons-arrow-down-alt2"
                                        style="font-size:12px; margin-left:5px;"></span>
                                </button>
                                <div class="efa-multiselect-dropdown" id="efa-form-dropdown">
                                    <label class="efa-ms-option all">
                                        <input type="checkbox" id="efa-form-all" checked> <strong>Seleccionar Todos</strong>
                                    </label>
                                    <div class="efa-ms-separator"></div>
                                    <?php if (empty($forms)): ?>
                                        <div style="padding:10px; color:#999; font-size:11px;">No hay formularios.</div>
                                    <?php else:
                                        foreach ($forms as $f): ?>
                                            <label class="efa-ms-option">
                                                <input type="checkbox" class="efa-form-check" value="<?php echo esc_attr($f); ?>"
                                                    checked>
                                                <?php echo esc_html($f); ?>
                                            </label>
                                        <?php endforeach; endif; ?>
                                </div>
                            </div>

                            <div class="efa-multiselect-wrapper" id="efa-origin-wrapper">
                                <button type="button" class="efa-select-sm efa-multiselect-btn" id="efa-origin-btn">
                                    <span>Orígenes: Todos</span>
                                    <span class="dashicons dashicons-arrow-down-alt2"
                                        style="font-size:12px; margin-left:5px;"></span>
                                </button>
                                <div class="efa-multiselect-dropdown" id="efa-origin-dropdown">
                                    <label class="efa-ms-option all">
                                        <input type="checkbox" id="efa-origin-all" checked> <strong>Seleccionar Todos</strong>
                                    </label>
                                    <div class="efa-ms-separator"></div>
                                    <?php if (empty($origins)): ?>
                                        <div style="padding:10px; color:#999; font-size:11px;">No hay orígenes registrados.</div>
                                    <?php else:
                                        foreach ($origins as $o): ?>
                                            <label class="efa-ms-option">
                                                <input type="checkbox" class="efa-origin-check" value="<?php echo esc_attr($o); ?>"
                                                    checked>
                                                <?php echo esc_html($o); ?>
                                            </label>
                                        <?php endforeach; endif; ?>
                                </div>
                            </div>

                            <!-- Hidden input for status filter (controlled by sidebar) -->
                            <input type="hidden" id="efa-current-status-filter" value="active">
                            <input type="hidden" id="efa-current-form-filter" value="">

                            <select id="efa-date-range" class="efa-select-sm">
                                <option value="last_7_days">Últimos 7 días</option>
                                <option value="last_month">Último mes</option>
                                <option value="all" selected>Todo el tiempo</option>
                                <option value="custom">Personalizado</option>
                            </select>
                            <div id="efa-custom-dates" class="efa-filters efa-hidden" style="display:none;"><input type="date"
                                    id="efa-start-date"><span>a</span><input type="date" id="efa-end-date"></div>
                            <button id="efa-apply-filters" class="efa-btn efa-btn-sm">🔍 Buscar</button>
                        </div>

                        <div class="efa-toolbar-group right">
                            <button id="efa-btn-delete-all" class="efa-btn-danger efa-hidden"
                                style="margin-left:0; margin-right:10px;">
                                <span class="dashicons dashicons-trash"
                                    style="font-size:14px; width:14px; height:14px; line-height:1.2;"></span> Borrar Spam
                            </button>
                        </div>



                        <div class="efa-columns-wrapper">
                            <button id="efa-btn-cols" class="efa-btn-icon" title="Configurar Columnas"><span
                                    class="dashicons dashicons-admin-settings"></span></button>
                            <div id="efa-cols-dropdown" class="efa-cols-dropdown"></div>
                        </div>

                        <div class="efa-toggle-wrapper" style="margin-left: 10px;">
                            <span class="efa-toggle-label">Comercial:</span>
                            <label class="efa-switch"><input type="checkbox" id="efa-toggle-commercial"><span
                                    class="slider"></span></label>
                        </div>

                        <div id="efa-origin-toggles" style="display:none;"></div>
                    </div>

                    <div class="efa-table-scroll">
                        <div class="efa-loading-overlay" id="efa-loading-overlay">
                            <div class="efa-spinner"></div>
                        </div>

                        <!-- Records Counter -->
                        <div class="efa-records-counter" id="efa-records-counter">
                            Total: <span id="efa-total-records">0</span> correos. Mostrando <span
                                id="efa-showing-records">0</span> de <span id="efa-filtered-records">0</span>
                        </div>

                        <table class="efa-table">
                            <thead>
                                <tr>

                                    <th>Fecha</th>
                                    <th>Formulario</th>
                                    <th>Origen</th>
                                    <th>Nombre</th>
                                    <th>Email</th>
                                    <th>Teléfono</th>
                                    <th>
                                        <span class="efa-tooltip-header" data-tooltip="Primera página que visitó el usuario">
                                            Landing
                                        </span>
                                    </th>
                                    <th>
                                        <span class="efa-tooltip-header" data-tooltip="Página desde la que llegó al formulario">
                                            Previa
                                        </span>
                                    </th>
                                    <th>
                                        <span class="efa-tooltip-header" data-tooltip="Página donde envió el formulario">
                                            Lead
                                        </span>
                                    </th>
                                    <th>Estado</th>
                                    <th style="text-align:center;">
                                        <span class="efa-tooltip-header" data-tooltip="Aceptado comunicaciones comerciales">
                                            Comercial
                                        </span>
                                    </th>
                                    <th>ID</th>
                                    <th class="efa-cell-status" style="text-align:center;">Spam</th>
                                    <th style="text-align:center;">Acción</th>
                                </tr>
                            </thead>
                            <tbody id="efa-table-body"></tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="efa-modal-overlay"></div>
            <div id="efa-slide-panel" class="efa-slide-panel">
                <div class="efa-panel-header">
                    <div class="efa-panel-nav">
                        <button id="efa-panel-manage-btn" class="efa-ph-btn manage" title="Notas y Gestión"
                            style="position:relative; margin-right: 10px;">
                            <span class="dashicons dashicons-edit"></span> Gestionar
                            <span id="efa-notes-badge-panel" class="efa-notes-badge" style="display:none;">0</span>
                        </button>
                        <button class="efa-nav-btn" id="efa-prev-btn" title="Anterior"><span
                                class="dashicons dashicons-arrow-left-alt2"></span></button>
                        <span class="efa-nav-counter" id="efa-nav-counter"></span>
                        <button class="efa-nav-btn" id="efa-next-btn" title="Siguiente"><span
                                class="dashicons dashicons-arrow-right-alt2"></span></button>
                        <span id="efa-panel-origin" class="efa-panel-origin" style="margin-left: 15px; display: none;"></span>
                    </div>
                    <button class="efa-close-btn" id="efa-close-panel">&times;</button>
                </div>
                <div id="efa-panel-content" class="efa-panel-content"></div>
                <div class="efa-panel-actions">
                    <button id="efa-btn-reply" class="efa-action-btn btn-reply">
                        <span class="dashicons dashicons-email-alt"></span> Responder
                    </button>
                    <a href="#" id="efa-btn-wa" class="efa-action-btn btn-wa" target="_blank">
                        <span class="dashicons dashicons-whatsapp"></span> WhatsApp
                    </a>
                </div>
            </div>

            <!-- CRM PANEL (SECONDARY) -->
            <div id="efa-crm-panel" class="efa-crm-panel">
                <div class="efa-panel-header">
                    <div class="efa-sec-title" style="margin:0; font-size:14px;"><span class="dashicons dashicons-edit"></span>
                        Notas Internas</div>
                    <button class="efa-close-btn" id="efa-close-crm-panel">&times;</button>
                </div>
                <div id="efa-crm-content" class="efa-panel-content">
                    <!-- CRM Content injected via JS -->
                </div>
            </div>

            <!-- REPLY PANEL (SECONDARY) -->
            <div id="efa-reply-panel" class="efa-reply-panel">
                <div class="efa-panel-header">
                    <div class="efa-sec-title" style="margin:0; font-size:14px;"><span class="dashicons dashicons-email-alt"></span>
                        Responder Correo</div>
                    <button class="efa-close-btn" id="efa-close-reply-panel">&times;</button>
                </div>
                <div id="efa-reply-content" class="efa-panel-content">
                    <!-- Reply Content injected via JS -->
                </div>
                <div id="efa-reply-actions" class="efa-panel-actions" style="display:none;">
                    <!-- Reply Actions injected via JS -->
                </div>
            </div>
            <?php
    }

    /**
     * HELPER: Genera el HTML del aviso de Trial
     * (Añadido para evitar el error de método indefinido)
     */
    private function get_trial_notice_html()
    {
        // Ahora delegamos en la clase de licencia que obtiene info desde la API
        if (class_exists('GW_Elementor_Plugin')) {
            $license = GW_Elementor_Plugin::get_instance()->license_instance;
            
            // Capturar el output del banner
            ob_start();
            $license->render_trial_notice();
            return ob_get_clean();
        }
        return '';
    }
}
