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

class GW_Analytics_Email_Settings {

    public function __construct() {
        add_action( 'admin_init', [ $this, 'save_settings' ] );
        add_action( 'wp_ajax_gw_send_test_email', [ $this, 'ajax_send_test_email' ] );
    }

    /**
     * Detecta si hay algún plugin SMTP instalado
     */
    private function detect_smtp_plugin() {
        // Lista de plugins SMTP comunes
        $smtp_plugins = [
            'wp-mail-smtp/wp_mail_smtp.php' => 'WP Mail SMTP',
            'easy-wp-smtp/easy-wp-smtp.php' => 'Easy WP SMTP',
            'post-smtp/postman-smtp.php' => 'Post SMTP',
            'wp-smtp/wp-smtp.php' => 'WP SMTP',
            'smtp-mailer/main.php' => 'SMTP Mailer',
            'gmail-smtp/main.php' => 'Gmail SMTP',
            'wp-mail-bank/wp-mail-bank.php' => 'WP Mail Bank',
            'fluent-smtp/fluent-smtp.php' => 'FluentSMTP',
            'mailgun/mailgun.php' => 'Mailgun',
            'sendgrid-email-delivery-simplified/wpsendgrid.php' => 'SendGrid',
        ];

        // Verificar si alguno está activo
        if ( ! function_exists( 'is_plugin_active' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
        }

        foreach ( $smtp_plugins as $plugin_path => $plugin_name ) {
            if ( is_plugin_active( $plugin_path ) ) {
                return [
                    'installed' => true,
                    'name' => $plugin_name,
                ];
            }
        }

        // También verificar si hay funciones SMTP personalizadas
        if ( has_filter( 'wp_mail_smtp' ) || has_filter( 'phpmailer_init' ) ) {
            return [
                'installed' => true,
                'name' => 'SMTP Personalizado',
            ];
        }

        return [
            'installed' => false,
            'name' => null,
        ];
    }

    /**
     * Guarda la configuración de correo
     */
    public function save_settings() {
        if ( ! isset( $_POST['gw_save_email_settings'] ) ) return;
        if ( ! check_admin_referer( 'gw_email_settings_nonce' ) ) return;

        // Permitimos guardar a quien tenga el rol configurado
        $role = get_option( 'efa_access_role', 'manage_options' );
        if ( ! current_user_can( $role ) ) return;

        $section = isset($_POST['gw_email_settings_section']) ? sanitize_text_field($_POST['gw_email_settings_section']) : 'settings';

        if ($section === 'settings') {
            update_option( 'efa_email_signature', isset($_POST['efa_email_signature']) ? wp_kses_post($_POST['efa_email_signature']) : '' );
        }

        wp_redirect( add_query_arg( ['page' => 'gw-elementor', 'tab' => 'email-settings', 'section' => $section, 'updated' => 'true'], admin_url( 'admin.php' ) ) );
        exit;
    }

    /**
     * Envía un correo de prueba vía AJAX
     */
    public function ajax_send_test_email() {
        check_ajax_referer( 'gw_email_settings_nonce', 'nonce' );

        $role = get_option( 'efa_access_role', 'manage_options' );
        if ( ! current_user_can( $role ) ) {
            wp_send_json_error( [ 'message' => 'No tienes permisos para realizar esta acción.' ] );
        }

        $test_email = isset( $_POST['test_email'] ) ? sanitize_email( $_POST['test_email'] ) : '';

        if ( empty( $test_email ) || ! is_email( $test_email ) ) {
            wp_send_json_error( [ 'message' => 'Por favor, introduce un correo electrónico válido.' ] );
        }

        $signature = get_option( 'efa_email_signature', '' );
        
        $subject = 'Correo de Prueba - GW Analytics';
        $message = 'Este es un correo de prueba enviado desde GW Analytics.' . "\n\n";
        $message .= 'Si recibes este correo, significa que tu configuración SMTP está funcionando correctamente.' . "\n\n";
        
        if ( ! empty( $signature ) ) {
            $message .= "\n\n---\n" . wp_kses_post( $signature );
        }

        $headers = [ 'Content-Type: text/html; charset=UTF-8' ];
        
        $sent = wp_mail( $test_email, $subject, nl2br( esc_html( $message ) ), $headers );

        if ( $sent ) {
            wp_send_json_success( [ 'message' => '¡Correo de prueba enviado correctamente! Revisa tu bandeja de entrada.' ] );
        } else {
            wp_send_json_error( [ 'message' => 'Error al enviar el correo. Verifica tu configuración SMTP.' ] );
        }
    }

    /**
     * Renderiza la vista de configuración de correo
     */
    public function render_email_settings_view() {
        $signature = get_option( 'efa_email_signature', '' );
        $smtp_status = $this->detect_smtp_plugin();
        $section = isset($_GET['section']) ? sanitize_text_field($_GET['section']) : 'settings';

        if ( isset( $_GET['updated'] ) ) {
            echo '<div class="notice notice-success is-dismissible inline" style="margin-top:20px;"><p><strong>¡Ajustes guardados!</strong> La configuración se ha actualizado correctamente.</p></div>';
        }
        ?>
        <div class="gw-settings-container">
            <!-- Header -->
            <div class="gw-settings-header">
                <div class="gw-header-content">
                    <div class="gw-header-text">
                        <h1 class="gw-main-title">
                            <span class="gw-icon-wrapper">
                                <span class="dashicons dashicons-email-alt"></span>
                            </span>
                            Configuración de Correo
                        </h1>
                        <p class="gw-header-description">Configura el envío de correos electrónicos desde el plugin.</p>
                    </div>
                </div>
            </div>

            <!-- Tabs -->
            <div class="gw-settings-tabs-wrapper">
                <div class="nav-tab-wrapper efa-settings-tabs">
                    <a href="<?php echo admin_url('admin.php?page=gw-elementor&tab=email-settings&section=settings'); ?>" class="nav-tab <?php echo $section === 'settings' ? 'nav-tab-active' : ''; ?>">
                        <span class="dashicons dashicons-admin-settings"></span>
                        AJUSTES DE CORREO
                    </a>
                    <a href="<?php echo admin_url('admin.php?page=gw-elementor&tab=email-settings&section=test'); ?>" class="nav-tab <?php echo $section === 'test' ? 'nav-tab-active' : ''; ?>">
                        <span class="dashicons dashicons-email"></span>
                        ENVÍO DE PRUEBA
                    </a>
                </div>
            </div>

            <?php if ($section === 'settings'): ?>
            <form method="post" action="">
                <?php wp_nonce_field( 'gw_email_settings_nonce' ); ?>
                <input type="hidden" name="gw_email_settings_section" value="settings">

                <div class="gw-card">
                    <h3 class="gw-card-title"><span class="dashicons dashicons-admin-settings"></span> Configuración SMTP</h3>
                    <p class="gw-card-desc">Verifica el estado de tu configuración SMTP para el envío de correos.</p>

                    <?php if ( $smtp_status['installed'] ): ?>
                        <div class="notice notice-success inline" style="margin: 15px 0; padding: 15px; border-left: 4px solid #46b450;">
                            <p style="margin: 0; display: flex; align-items: center; gap: 10px;">
                                <span class="dashicons dashicons-yes-alt" style="color: #46b450; font-size: 20px;"></span>
                                <strong>Ok, tienes SMTP instalado</strong>
                                <?php if ( $smtp_status['name'] ): ?>
                                    <span style="color: #666; font-weight: normal;">(<?php echo esc_html( $smtp_status['name'] ); ?>)</span>
                                <?php endif; ?>
                            </p>
                        </div>
                    <?php else: ?>
                        <div class="notice notice-error inline" style="margin: 15px 0; padding: 15px; border-left: 4px solid #dc3232;">
                            <p style="margin: 0; display: flex; align-items: center; gap: 10px;">
                                <span class="dashicons dashicons-warning" style="color: #dc3232; font-size: 20px;"></span>
                                <strong>No tienes ningún plugin SMTP instalado, recomendamos utilizar uno.</strong>
                            </p>
                            <p style="margin: 10px 0 0 0; color: #666;">
                                Para enviar correos de forma confiable, te recomendamos instalar un plugin SMTP como 
                                <a href="https://wordpress.org/plugins/wp-mail-smtp/" target="_blank" style="color: #2271b1;">WP Mail SMTP</a> o 
                                <a href="https://wordpress.org/plugins/post-smtp/" target="_blank" style="color: #2271b1;">Post SMTP</a>.
                            </p>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="gw-card">
                    <h3 class="gw-card-title"><span class="dashicons dashicons-edit"></span> Firma de Correos</h3>
                    <p class="gw-card-desc">Personaliza la firma que se añadirá automáticamente a todos los correos enviados desde el plugin.</p>

                    <div class="gw-input-group">
                        <label class="gw-label">Firma Personalizada</label>
                        <?php
                        wp_editor( 
                            $signature, 
                            'efa_email_signature', 
                            [
                                'textarea_name' => 'efa_email_signature',
                                'textarea_rows' => 10,
                                'media_buttons' => false,
                                'teeny' => true,
                                'tinymce' => [
                                    'toolbar1' => 'bold,italic,underline,link,unlink,bullist,numlist',
                                    'toolbar2' => '',
                                ],
                            ] 
                        );
                        ?>
                        <span class="gw-helper">Esta firma se añadirá automáticamente al final de todos los correos enviados desde el plugin. Puedes usar HTML básico.</span>
                    </div>
                </div>

                <div class="gw-save-bar">
                    <button type="submit" name="gw_save_email_settings" class="gw-btn-primary">
                        <span class="dashicons dashicons-yes-alt"></span>
                        Guardar Configuración
                    </button>
                </div>
            </form>
            <?php endif; ?>

            <?php if ($section === 'test'): ?>
            <div class="gw-card">
                <h3 class="gw-card-title"><span class="dashicons dashicons-email"></span> Envío de Correo de Prueba</h3>
                <p class="gw-card-desc">Envía un correo de prueba para verificar que tu configuración SMTP está funcionando correctamente.</p>

                <div class="gw-input-group">
                    <label class="gw-label">Correo Destinatario</label>
                    <input type="email" id="gw-test-email-input" class="gw-input" placeholder="ejemplo@correo.com" required>
                    <span class="gw-helper">Introduce el correo electrónico al que quieres enviar el mensaje de prueba.</span>
                </div>

                <div class="gw-save-bar">
                    <button type="button" id="gw-send-test-email-btn" class="gw-btn-primary">
                        <span class="dashicons dashicons-email-alt"></span>
                        Enviar Prueba
                    </button>
                </div>

                <div id="gw-test-email-message" style="margin-top: 20px; display: none;"></div>
            </div>
            <?php endif; ?>
        </div>

        <style>
            /* Reutilizar estilos de ajustes */
            .gw-settings-container {
                max-width: 1600px;
                margin: 0 auto;
                padding: 15px 20px 30px 20px;
            }

            .gw-settings-header {
                margin-bottom: 30px;
                padding-bottom: 20px;
                border-bottom: 2px solid #e5e7eb;
            }

            .gw-header-content {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                gap: 20px;
            }

            .gw-header-text {
                flex: 1;
            }

            .gw-main-title {
                display: flex;
                align-items: center;
                gap: 15px;
                margin: 0 0 8px 0;
                font-size: 28px;
                font-weight: 700;
                color: #1f2937;
            }

            .gw-icon-wrapper {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: 48px;
                height: 48px;
                border-radius: 12px;
                background: #e01d75;
                color: #fff;
                font-size: 24px;
            }

            .gw-header-description {
                font-size: 15px;
                color: #6b7280;
                margin: 0;
            }

            .gw-settings-tabs-wrapper {
                margin-bottom: 30px;
            }

            .efa-settings-tabs {
                display: flex;
                gap: 8px;
                border-bottom: none;
                padding: 0;
                background: transparent;
            }

            .efa-settings-tabs .nav-tab {
                display: inline-flex;
                align-items: center;
                gap: 8px;
                padding: 12px 24px;
                background: #ffffff;
                border: 1px solid #e5e7eb;
                border-radius: 8px 8px 0 0;
                color: #374151;
                font-weight: 600;
                font-size: 13px;
                text-transform: uppercase;
                letter-spacing: 0.5px;
                text-decoration: none;
                transition: all 0.3s ease;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
                margin-bottom: -1px;
            }

            .efa-settings-tabs .nav-tab:hover {
                background: #f9fafb;
                border-color: #d1d5db;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            }

            .efa-settings-tabs .nav-tab-active {
                background: linear-gradient(135deg, #e01d75 0%, #c91a6a 100%);
                border-color: #e01d75;
                color: #ffffff;
                box-shadow: 0 4px 12px rgba(224, 29, 117, 0.3);
            }

            .efa-settings-tabs .nav-tab-active:hover {
                background: linear-gradient(135deg, #c91a6a 0%, #e01d75 100%);
                box-shadow: 0 6px 16px rgba(224, 29, 117, 0.4);
            }

            .efa-settings-tabs .nav-tab .dashicons {
                font-size: 18px;
                width: 18px;
                height: 18px;
            }

            .gw-card {
                background: #ffffff;
                border: 1px solid #e5e7eb;
                border-radius: 12px;
                padding: 24px;
                margin-bottom: 24px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
                transition: all 0.3s ease;
            }

            .gw-card:hover {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
                border-color: #d1d5db;
            }

            .gw-card-title {
                display: flex;
                align-items: center;
                gap: 12px;
                font-size: 18px;
                font-weight: 700;
                color: #1f2937;
                margin: 0 0 12px 0;
                padding-bottom: 16px;
                border-bottom: 2px solid #f3f4f6;
            }

            .gw-card-title .dashicons {
                color: #e01d75;
                font-size: 20px;
                width: 20px;
                height: 20px;
            }

            .gw-card-desc {
                font-size: 14px;
                color: #6b7280;
                margin: 0 0 20px 0;
                line-height: 1.6;
            }

            .gw-input-group {
                margin-bottom: 24px;
            }

            .gw-label {
                display: block;
                font-size: 14px;
                font-weight: 600;
                color: #374151;
                margin-bottom: 8px;
            }

            .gw-input {
                width: 100%;
                padding: 12px 16px;
                border: 1px solid #d1d5db;
                border-radius: 8px;
                font-size: 14px;
                color: #1f2937;
                transition: all 0.3s ease;
                background: #ffffff;
            }

            .gw-input:focus {
                outline: none;
                border-color: #e01d75;
                box-shadow: 0 0 0 3px rgba(224, 29, 117, 0.2);
            }

            .gw-helper {
                display: block;
                font-size: 13px;
                color: #6b7280;
                margin-top: 8px;
                line-height: 1.5;
            }

            .gw-save-bar {
                padding: 20px 24px;
                background: #f9fafb;
                border-top: 1px solid #e5e7eb;
                border-radius: 0 0 12px 12px;
                margin: 24px -24px -24px -24px;
                display: flex;
                justify-content: flex-start;
            }

            .gw-btn-primary {
                display: inline-flex;
                align-items: center;
                gap: 10px;
                background: #e01d75;
                color: white;
                border: none;
                padding: 14px 32px;
                border-radius: 8px;
                font-size: 15px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(224, 29, 117, 0.3);
                min-width: auto;
                width: auto;
            }

            .gw-btn-primary:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 25px rgba(224, 29, 117, 0.4);
                background: #c91a6a;
            }

            .gw-btn-primary:active {
                transform: translateY(0);
            }

            .gw-btn-primary .dashicons {
                font-size: 18px;
                width: 18px;
                height: 18px;
            }

            /* Dark Mode */
            body.efa-dark-mode .gw-settings-container {
                background: transparent;
            }

            body.efa-dark-mode .gw-settings-header {
                border-bottom-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-main-title {
                color: #e4e7eb !important;
            }

            body.efa-dark-mode .gw-header-description {
                color: #9ca3af !important;
            }

            body.efa-dark-mode .gw-card {
                background: #1f2940 !important;
                border-color: #3a3a4e !important;
                color: #e0e0e0 !important;
            }

            body.efa-dark-mode .gw-card:hover {
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
                border-color: #4a4a6a !important;
            }

            body.efa-dark-mode .gw-card-title {
                color: #ffffff !important;
                border-bottom-color: #3a3a4e !important;
            }

            body.efa-dark-mode .gw-card-title .dashicons {
                color: #e01d75 !important;
            }

            body.efa-dark-mode .gw-card-desc {
                color: #9ca3af !important;
            }

            body.efa-dark-mode .gw-label {
                color: #e0e0e0 !important;
            }

            body.efa-dark-mode .gw-input {
                background: #2a2a3e !important;
                border-color: #3a3a4e !important;
                color: #e0e0e0 !important;
            }

            body.efa-dark-mode .gw-input:focus {
                border-color: #e01d75 !important;
                box-shadow: 0 0 0 3px rgba(224, 29, 117, 0.2) !important;
            }

            body.efa-dark-mode .gw-helper {
                color: #9ca3af !important;
            }

            body.efa-dark-mode .gw-save-bar {
                border-top-color: #3a3a4e !important;
                background: #1f2940 !important;
            }

            body.efa-dark-mode .efa-settings-tabs .nav-tab {
                background: #1f2940 !important;
                border-color: #3a3a4e !important;
                color: #e0e0e0 !important;
            }

            body.efa-dark-mode .efa-settings-tabs .nav-tab:hover {
                background: #2a2a3e !important;
                border-color: #4a4a6a !important;
            }

            body.efa-dark-mode .efa-settings-tabs .nav-tab-active {
                background: linear-gradient(135deg, #e01d75 0%, #c91a6a 100%) !important;
                border-color: #e01d75 !important;
            }
        </style>

        <script>
        jQuery(document).ready(function($) {
            var emailNonce = '<?php echo wp_create_nonce( 'gw_email_settings_nonce' ); ?>';
            
            $('#gw-send-test-email-btn').on('click', function() {
                var $btn = $(this);
                var $message = $('#gw-test-email-message');
                var email = $('#gw-test-email-input').val();

                if (!email || !email.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
                    $message.removeClass('notice-success').addClass('notice notice-error inline').html('<p><strong>Error:</strong> Por favor, introduce un correo electrónico válido.</p>').show();
                    return;
                }

                $btn.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Enviando...');
                $message.hide();

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'gw_send_test_email',
                        nonce: emailNonce,
                        test_email: email
                    },
                    success: function(response) {
                        if (response.success) {
                            $message.removeClass('notice-error').addClass('notice notice-success inline').html('<p><strong>¡Éxito!</strong> ' + response.data.message + '</p>').show();
                            $('#gw-test-email-input').val('');
                        } else {
                            $message.removeClass('notice-success').addClass('notice notice-error inline').html('<p><strong>Error:</strong> ' + (response.data.message || 'Error al enviar el correo.') + '</p>').show();
                        }
                    },
                    error: function() {
                        $message.removeClass('notice-success').addClass('notice notice-error inline').html('<p><strong>Error:</strong> Error de conexión. Por favor, intenta de nuevo.</p>').show();
                    },
                    complete: function() {
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-email-alt"></span> Enviar Prueba');
                    }
                });
            });

            // Permitir enviar con Enter
            $('#gw-test-email-input').on('keypress', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    $('#gw-send-test-email-btn').click();
                }
            });
        });
        </script>

        <style>
            .dashicons-update.spin {
                animation: spin 1s linear infinite;
            }
            @keyframes spin {
                from { transform: rotate(0deg); }
                to { transform: rotate(360deg); }
            }
        </style>
        <?php
    }
}

