<?php
/**
 * View: Settings & SMTP Page (Premium UI)
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Fetch settings and tightly scope global variables
$pexemail_settings = get_option( 'pexemail_settings', [] );
if ( ! is_array( $pexemail_settings ) ) {
    $pexemail_settings = [];
}

// Default values safely assigned to prefixed variables (Strictly empty for fresh installs)
$pexemail_enabled             = isset( $pexemail_settings['enabled'] ) ? $pexemail_settings['enabled'] : 'yes';
$pexemail_sender_name         = isset( $pexemail_settings['sender_name'] ) ? $pexemail_settings['sender_name'] : '';
$pexemail_sender_email        = isset( $pexemail_settings['sender_email'] ) ? $pexemail_settings['sender_email'] : '';
$pexemail_logo_url            = isset( $pexemail_settings['logo_url'] ) ? $pexemail_settings['logo_url'] : '';
$pexemail_footer_contact_text = isset( $pexemail_settings['footer_contact_text'] ) ? $pexemail_settings['footer_contact_text'] : '';
$pexemail_facebook_url        = isset( $pexemail_settings['facebook_url'] ) ? $pexemail_settings['facebook_url'] : '';
$pexemail_x_url               = isset( $pexemail_settings['x_url'] ) ? $pexemail_settings['x_url'] : '';
$pexemail_linkedin_url        = isset( $pexemail_settings['linkedin_url'] ) ? $pexemail_settings['linkedin_url'] : '';
$pexemail_instagram_url       = isset( $pexemail_settings['instagram_url'] ) ? $pexemail_settings['instagram_url'] : '';
$pexemail_youtube_url         = isset( $pexemail_settings['youtube_url'] ) ? $pexemail_settings['youtube_url'] : '';
$pexemail_telegram_url        = isset( $pexemail_settings['telegram_url'] ) ? $pexemail_settings['telegram_url'] : '';
$pexemail_whatsapp_url        = isset( $pexemail_settings['whatsapp_url'] ) ? $pexemail_settings['whatsapp_url'] : '';
$pexemail_teams_url           = isset( $pexemail_settings['teams_url'] ) ? $pexemail_settings['teams_url'] : '';

// SMTP Settings (Defaults kept blank for fresh installs)
$pexemail_smtp_enabled        = isset( $pexemail_settings['smtp_enabled'] ) ? $pexemail_settings['smtp_enabled'] : 'no';
$pexemail_smtp_provider       = isset( $pexemail_settings['smtp_provider'] ) ? $pexemail_settings['smtp_provider'] : 'google';
$pexemail_smtp_host           = isset( $pexemail_settings['smtp_host'] ) ? $pexemail_settings['smtp_host'] : '';
$pexemail_smtp_port           = isset( $pexemail_settings['smtp_port'] ) ? $pexemail_settings['smtp_port'] : '';
$pexemail_smtp_secure         = isset( $pexemail_settings['smtp_secure'] ) ? $pexemail_settings['smtp_secure'] : 'tls';
$pexemail_smtp_username       = isset( $pexemail_settings['smtp_username'] ) ? $pexemail_settings['smtp_username'] : '';
$pexemail_smtp_password       = isset( $pexemail_settings['smtp_password'] ) ? $pexemail_settings['smtp_password'] : '';
?>

<style>
    /* Global Reset & Typography */
    .pex-premium-wrap { 
        max-width: 1400px; 
        margin: 25px 0 0 0; 
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; 
        color: #334155; 
    }
    
    /* Hero Section (Brand Green) */
    .pex-hero { 
        background: linear-gradient(135deg, #0f5132 0%, #064e3b 100%); 
        color: #fff; 
        padding: 45px 50px; 
        border-radius: 16px; 
        margin-bottom: 35px; 
        box-shadow: 0 20px 40px -10px rgba(6, 78, 59, 0.4), inset 0 1px 0 rgba(255,255,255,0.15); 
        position: relative;
        overflow: hidden;
    }
    .pex-hero::after {
        content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0;
        background: url('data:image/svg+xml;utf8,<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40" fill="rgba(255,255,255,0.04)"/></svg>') repeat;
        opacity: 0.8; pointer-events: none;
    }
    .pex-hero-text { position: relative; z-index: 2; }
    .pex-hero h1 { color: #fff; margin: 0 0 10px 0; font-size: 32px; font-weight: 800; letter-spacing: -0.5px; text-shadow: 0 2px 4px rgba(0,0,0,0.2); }
    .pex-hero p { margin: 0; font-size: 16px; color: #d1fae5; line-height: 1.6; max-width: 650px; font-weight: 400; }

    /* Layout Cards */
    .pex-card { 
        background: #ffffff; 
        border-radius: 16px; 
        border: 1px solid #eef2f6; 
        box-shadow: 0 4px 6px -1px rgba(15, 23, 42, 0.03), 0 2px 4px -1px rgba(15, 23, 42, 0.03); 
        overflow: hidden; 
        margin-bottom: 35px; 
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .pex-card:hover { box-shadow: 0 15px 30px -5px rgba(15, 23, 42, 0.08); border-color: #e2e8f0; }
    .pex-card-header { padding: 24px 30px; border-bottom: 1px solid #f1f5f9; background: #ffffff; }
    .pex-card-header h2 { margin: 0; font-size: 18px; font-weight: 800; color: #0f172a; letter-spacing: -0.3px; }
    .pex-card-body { padding: 35px 30px; }

    /* Form Styles */
    .pex-form-row-flex { display: flex; gap: 30px; margin-bottom: 25px; flex-wrap: wrap; align-items: center; }
    .pex-form-group { display: flex; flex-direction: column; margin-bottom: 25px; position: relative; }
    .pex-form-label { font-size: 13.5px; font-weight: 800; color: #0f172a; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.5px; }
    .pex-input { 
        width: 100%; max-width: 700px; padding: 14px 18px; border: 1px solid #cbd5e1; border-radius: 6px; 
        font-size: 15px; outline: none; transition: all 0.3s ease; background: #ffffff; color: #0f172a; 
        box-sizing: border-box; 
    }
    .pex-input:focus { border-color: #10b981; box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.15); transform: translateY(-1px); }
    .pex-desc { font-size: 13.5px; color: #64748b; margin-top: 8px; line-height: 1.5; font-weight: 400; max-width: 700px; transition: color 0.3s; }
    
    /* Live Update Animation */
    @keyframes flashSuccess {
        0% { border-color: #cbd5e1; }
        20% { background-color: #ecfdf5; border-color: #10b981; box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.2); transform: scale(1.01); }
        100% { background-color: #ffffff; border-color: #cbd5e1; transform: scale(1); }
    }
    .live-update { animation: flashSuccess 1s ease-out; }

    @keyframes fadeInSlide {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .fade-in-slide { animation: fadeInSlide 0.4s cubic-bezier(0.4, 0, 0.2, 1) forwards; }

    /* Social Grid */
    .pex-social-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; max-width: 1000px; }
    @media (max-width: 800px) { .pex-social-grid { grid-template-columns: 1fr; } }
    .pex-social-grid .pex-input { max-width: 100%; }

    /* Interactive Mailer Cards */
    .pex-mailer-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 10px; }
    @media (max-width: 1024px) { .pex-mailer-grid { grid-template-columns: repeat(2, 1fr); } }
    @media (max-width: 600px) { .pex-mailer-grid { grid-template-columns: 1fr; } }

    .pex-mailer-option { position: relative; cursor: pointer; }
    .pex-mailer-option input[type="radio"] { position: absolute; opacity: 0; width: 0; height: 0; }
    .pex-mailer-box {
        background: #ffffff; border: 2px solid #e2e8f0; border-radius: 14px; padding: 25px 20px;
        text-align: center; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); position: relative; height: 100%; box-sizing: border-box;
        display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.02);
    }
    .pex-mailer-box:hover { border-color: #94a3b8; background: #f8fafc; transform: translateY(-4px); box-shadow: 0 10px 15px rgba(0,0,0,0.05); }
    .pex-mailer-option input[type="radio"]:checked + .pex-mailer-box {
        border-color: #10b981; background: #f0fdf4; box-shadow: 0 15px 30px -5px rgba(16, 185, 129, 0.2); transform: translateY(-4px);
    }
    .pex-mailer-option input[type="radio"]:checked + .pex-mailer-box::before {
        content: '✓'; position: absolute; top: 12px; right: 14px; color: #fff; background: #10b981; width: 22px; height: 22px; border-radius: 50%; font-weight: 900; font-size: 12px; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 4px rgba(16,185,129,0.3);
    }
    .pex-mailer-box strong { color: #0f172a; font-size: 16px; font-weight: 800; }
    .pex-mailer-box span { color: #64748b; font-size: 13.5px; }
    .pex-mailer-icon { width: 54px; height: 54px; border-radius: 14px; background: #f1f5f9; display: flex; align-items: center; justify-content: center; font-size: 26px; color: #475569; transition: all 0.3s; }
    .pex-mailer-option input[type="radio"]:checked + .pex-mailer-box .pex-mailer-icon { background: #d1fae5; color: #059669; transform: scale(1.1); }

    /* Badges */
    .pex-badge-rec { background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 800; text-transform: uppercase; margin-top: 5px; box-shadow: 0 2px 4px rgba(16,185,129,0.2); }
    .pex-badge-wp { background: linear-gradient(135deg, #f59e0b, #d97706); color: white; padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 800; text-transform: uppercase; margin-top: 5px; box-shadow: 0 2px 4px rgba(245,158,11,0.2); }

    /* Buttons */
    .pex-btn-primary { 
        background: linear-gradient(135deg, #0f172a, #1e293b); color: white; padding: 16px 36px; border-radius: 12px; font-weight: 700; font-size: 16px; 
        text-decoration: none; display: inline-flex; align-items: center; justify-content: center; transition: all 0.3s; border: none; cursor: pointer; box-shadow: 0 10px 20px rgba(15, 23, 42, 0.15); gap: 10px; letter-spacing: 0.5px;
    }
    .pex-btn-primary:hover { transform: translateY(-3px); box-shadow: 0 15px 25px rgba(15, 23, 42, 0.25); background: linear-gradient(135deg, #1e293b, #334155); }
    .pex-btn-primary:active { transform: translateY(0); }

    /* Password Input Toggle */
    .pex-pw-wrapper { position: relative; display: flex; align-items: center; width: 100%; max-width: 700px; }
    .pex-pw-toggle { 
        position: absolute; right: 10px; background: #e2e8f0; border: none; color: #475569; 
        font-size: 12px; font-weight: 700; padding: 8px 14px; border-radius: 6px; cursor: pointer; transition: all 0.2s; 
    }
    .pex-pw-toggle:hover { background: #cbd5e1; color: #0f172a; }

    /* Notice */
    .pex-custom-notice { background: #f0fdf4; border: 1px solid #bbf7d0; border-left: 5px solid #10b981; padding: 18px 24px; border-radius: 12px; color: #065f46; font-weight: 600; margin-bottom: 30px; box-shadow: 0 4px 15px rgba(16, 185, 129, 0.1); font-size: 15px; display: flex; align-items: center; gap: 12px; animation: fadeInSlide 0.5s ease; }

    /* Custom Switch */
    .pex-switch { position: relative; display: inline-block; width: 54px; height: 28px; flex-shrink: 0; }
    .pex-switch input { opacity: 0; width: 0; height: 0; }
    .pex-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #cbd5e1; transition: .4s cubic-bezier(0.4, 0, 0.2, 1); border-radius: 28px; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); }
    .pex-slider:before { position: absolute; content: ""; height: 20px; width: 20px; left: 4px; bottom: 4px; background-color: white; transition: .4s cubic-bezier(0.4, 0, 0.2, 1); border-radius: 50%; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }
    input:checked + .pex-slider { background-color: #10b981; }
    input:checked + .pex-slider:before { transform: translateX(26px); }
</style>

<div class="wrap pex-premium-wrap">

    <?php 
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( isset( $_GET['settings_updated'] ) ) : ?>
        <div class="pex-custom-notice">
            <span style="font-size: 22px;">✅</span> 
            <?php esc_html_e( 'Settings saved successfully. Your connection is secure.', 'pexally-email-campaigns' ); ?>
        </div>
    <?php endif; ?>

    <div class="pex-hero">
        <div class="pex-hero-text">
            <h1><?php esc_html_e( 'Email Configuration & SMTP', 'pexally-email-campaigns' ); ?></h1>
            <p><?php esc_html_e( 'Setup your Sender Identity, Branding, and Global SMTP connection to guarantee high inbox delivery via our secure central engine.', 'pexally-email-campaigns' ); ?></p>
        </div>
    </div>

    <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" autocomplete="off">
        <?php wp_nonce_field( 'pexemail_save_settings_action', 'pexemail_settings_nonce' ); ?>
        <input type="hidden" name="action" value="pexemail_save_settings">

        <!-- 1. Sender & Branding Details -->
        <div class="pex-card">
            <div class="pex-card-header">
                <h2><?php esc_html_e( 'Sender & Branding Details', 'pexally-email-campaigns' ); ?></h2>
            </div>
            <div class="pex-card-body">
                
                <div class="pex-form-row-flex" style="background: #f8fafc; padding: 25px; border-radius: 14px; border: 1px solid #e2e8f0; max-width: 700px; box-sizing: border-box; box-shadow: inset 0 2px 4px rgba(0,0,0,0.01);">
                    <div style="flex-grow: 1;">
                        <label class="pex-form-label" style="margin-bottom: 6px; font-size: 15px;"><?php esc_html_e( 'Enable Email Sending Engine', 'pexally-email-campaigns' ); ?></label>
                        <div class="pex-desc" style="margin-top: 0;"><?php esc_html_e( 'Turn this off to globally pause all automated and manual email sending.', 'pexally-email-campaigns' ); ?></div>
                    </div>
                    <label class="pex-switch">
                        <input type="checkbox" name="enabled" value="yes" <?php checked( $pexemail_enabled, 'yes' ); ?>>
                        <span class="pex-slider"></span>
                    </label>
                </div>

                <div class="pex-form-group">
                    <label class="pex-form-label"><?php esc_html_e( 'Sender Name', 'pexally-email-campaigns' ); ?></label>
                    <input type="text" name="sender_name" class="pex-input" value="<?php echo esc_attr( $pexemail_sender_name ); ?>" placeholder="e.g. Your Company Name" autocomplete="off" data-lpignore="true">
                    <div class="pex-desc"><?php esc_html_e( 'The display name your recipients will see in their inbox.', 'pexally-email-campaigns' ); ?></div>
                </div>

                <div class="pex-form-group">
                    <label class="pex-form-label"><?php esc_html_e( 'Sender Email', 'pexally-email-campaigns' ); ?></label>
                    <input type="email" name="sender_email" class="pex-input" value="<?php echo esc_attr( $pexemail_sender_email ); ?>" placeholder="e.g. you@yourdomain.com" autocomplete="new-password" data-lpignore="true" spellcheck="false" readonly onfocus="this.removeAttribute('readonly');">
                    <div class="pex-desc"><?php esc_html_e( 'Handles the "From:" address. Must match your authenticated SMTP provider domain.', 'pexally-email-campaigns' ); ?></div>
                </div>

                <div class="pex-form-group">
                    <label class="pex-form-label"><?php esc_html_e( 'Email Header Image (Logo)', 'pexally-email-campaigns' ); ?></label>
                    <input type="url" name="logo_url" class="pex-input" value="<?php echo esc_url( $pexemail_logo_url ); ?>" placeholder="https://yourdomain.com/logo.png">
                    <div class="pex-desc"><?php esc_html_e( 'Paste a direct URL to your logo. It will be injected beautifully into all templates.', 'pexally-email-campaigns' ); ?></div>
                </div>

                <div class="pex-form-group" style="margin-bottom: 35px;">
                    <label class="pex-form-label"><?php esc_html_e( 'Footer Contact Text (Anti-Spam Compliance)', 'pexally-email-campaigns' ); ?></label>
                    <div style="border: 1px solid #cbd5e1; border-radius: 6px; overflow: hidden; max-width: 700px;">
                        <?php wp_editor( stripslashes( htmlspecialchars_decode( $pexemail_footer_contact_text ) ), 'footer_contact_text', [ 'textarea_rows' => 6, 'media_buttons' => false ] ); ?>
                    </div>
                    <div class="pex-desc"><?php esc_html_e( 'Add your company address or physical contact info to comply with CAN-SPAM laws.', 'pexally-email-campaigns' ); ?></div>
                </div>

                <hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 35px 0; max-width: 700px;">

                <h3 style="margin: 0 0 20px 0; font-size: 16px; font-weight: 800; color: #0f172a;"><?php esc_html_e( 'Social Media Links (Footer Icons)', 'pexally-email-campaigns' ); ?></h3>
                
                <div class="pex-social-grid">
                    <div class="pex-form-group" style="margin-bottom: 0;">
                        <label class="pex-form-label">Facebook URL</label>
                        <input type="url" name="facebook_url" class="pex-input" value="<?php echo esc_url( $pexemail_facebook_url ); ?>" placeholder="https://facebook.com/...">
                    </div>
                    <div class="pex-form-group" style="margin-bottom: 0;">
                        <label class="pex-form-label">X / Twitter URL</label>
                        <input type="url" name="x_url" class="pex-input" value="<?php echo esc_url( $pexemail_x_url ); ?>" placeholder="https://x.com/...">
                    </div>
                    <div class="pex-form-group" style="margin-bottom: 0;">
                        <label class="pex-form-label">LinkedIn URL</label>
                        <input type="url" name="linkedin_url" class="pex-input" value="<?php echo esc_url( $pexemail_linkedin_url ); ?>" placeholder="https://linkedin.com/company/...">
                    </div>
                    <div class="pex-form-group" style="margin-bottom: 0;">
                        <label class="pex-form-label">Instagram URL</label>
                        <input type="url" name="instagram_url" class="pex-input" value="<?php echo esc_url( $pexemail_instagram_url ); ?>" placeholder="https://instagram.com/...">
                    </div>
                    <div class="pex-form-group" style="margin-bottom: 0;">
                        <label class="pex-form-label">YouTube URL</label>
                        <input type="url" name="youtube_url" class="pex-input" value="<?php echo esc_url( $pexemail_youtube_url ); ?>" placeholder="https://youtube.com/...">
                    </div>
                    <div class="pex-form-group" style="margin-bottom: 0;">
                        <label class="pex-form-label">Telegram URL</label>
                        <input type="url" name="telegram_url" class="pex-input" value="<?php echo esc_url( $pexemail_telegram_url ); ?>" placeholder="https://t.me/...">
                    </div>
                    <div class="pex-form-group" style="margin-bottom: 0;">
                        <label class="pex-form-label">WhatsApp URL</label>
                        <input type="url" name="whatsapp_url" class="pex-input" value="<?php echo esc_url( $pexemail_whatsapp_url ); ?>" placeholder="https://wa.me/...">
                    </div>
                    <div class="pex-form-group" style="margin-bottom: 0;">
                        <label class="pex-form-label">Microsoft Teams URL</label>
                        <input type="url" name="teams_url" class="pex-input" value="<?php echo esc_url( $pexemail_teams_url ); ?>" placeholder="https://teams.microsoft.com/...">
                    </div>
                </div>

            </div>
        </div>

        <!-- 2. Mailer Engine & SMTP -->
        <div class="pex-card">
            <div class="pex-card-header">
                <h2><?php esc_html_e( 'Mailer Engine Connection', 'pexally-email-campaigns' ); ?></h2>
            </div>
            <div class="pex-card-body" style="background-color: #f8fafc;">
                
                <input type="hidden" name="smtp_enabled" id="smtp_enabled_val" value="<?php echo esc_attr( $pexemail_smtp_enabled ); ?>">
                
                <div class="pex-mailer-grid">
                    <label class="pex-mailer-option">
                        <input type="radio" name="smtp_provider" value="wp_mail" <?php checked( $pexemail_smtp_provider, 'wp_mail' ); ?>>
                        <div class="pex-mailer-box">
                            <div class="pex-mailer-icon">⚙️</div>
                            <div style="line-height: 1.4;">
                                <strong>Default PHP Mail</strong><br>
                                <span>Uses website server</span>
                            </div>
                            <span class="pex-badge-wp">NOT RECOMMENDED</span>
                        </div>
                    </label>
                    <label class="pex-mailer-option">
                        <input type="radio" name="smtp_provider" value="google" <?php checked( $pexemail_smtp_provider, 'google' ); ?>>
                        <div class="pex-mailer-box">
                            <div class="pex-mailer-icon">
                                <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
                            </div>
                            <div style="line-height: 1.4;">
                                <strong>Google Workspace</strong><br>
                                <span>Gmail / G-Suite</span>
                            </div>
                            <span class="pex-badge-rec">RECOMMENDED</span>
                        </div>
                    </label>
                    <label class="pex-mailer-option">
                        <input type="radio" name="smtp_provider" value="sendgrid" <?php checked( $pexemail_smtp_provider, 'sendgrid' ); ?>>
                        <div class="pex-mailer-box">
                            <div class="pex-mailer-icon">☁️</div>
                            <div style="line-height: 1.4;">
                                <strong>SendGrid</strong><br>
                                <span>Twilio SendGrid SMTP</span>
                            </div>
                        </div>
                    </label>
                    <label class="pex-mailer-option">
                        <input type="radio" name="smtp_provider" value="ses" <?php checked( $pexemail_smtp_provider, 'ses' ); ?>>
                        <div class="pex-mailer-box">
                            <div class="pex-mailer-icon">📦</div>
                            <div style="line-height: 1.4;">
                                <strong>Amazon SES</strong><br>
                                <span>AWS Simple Email</span>
                            </div>
                        </div>
                    </label>
                    <label class="pex-mailer-option">
                        <input type="radio" name="smtp_provider" value="mailgun" <?php checked( $pexemail_smtp_provider, 'mailgun' ); ?>>
                        <div class="pex-mailer-box">
                            <div class="pex-mailer-icon">🎯</div>
                            <div style="line-height: 1.4;">
                                <strong>Mailgun</strong><br>
                                <span>Mailgun SMTP</span>
                            </div>
                        </div>
                    </label>
                    <label class="pex-mailer-option">
                        <input type="radio" name="smtp_provider" value="other" <?php checked( $pexemail_smtp_provider, 'other' ); ?>>
                        <div class="pex-mailer-box">
                            <div class="pex-mailer-icon">🔌</div>
                            <div style="line-height: 1.4;">
                                <strong>Other SMTP</strong><br>
                                <span>Brevo, Hostinger, etc.</span>
                            </div>
                        </div>
                    </label>
                </div>

                <!-- Hidden/Shown based on selection -->
                <div id="pex-smtp-settings-wrapper" class="pex-smtp-fields" style="<?php echo ($pexemail_smtp_provider === 'wp_mail') ? 'display:none;' : ''; ?>">
                    <hr style="border: 0; border-top: 1px solid #e2e8f0; margin: 35px 0 25px 0;">
                    
                    <h3 style="margin: 0 0 25px 0; font-size: 16px; font-weight: 800; color: #0f172a;" id="smtp-section-title">SMTP Connection Settings</h3>
                    
                    <div class="pex-form-group">
                        <label class="pex-form-label"><?php esc_html_e( 'SMTP HOST', 'pexally-email-campaigns' ); ?></label>
                        <input type="text" id="smtp_host" name="smtp_host" class="pex-input" value="<?php echo esc_attr( $pexemail_smtp_host ); ?>" placeholder="e.g. smtp.gmail.com">
                    </div>

                    <div class="pex-form-group">
                        <label class="pex-form-label"><?php esc_html_e( 'SMTP PORT', 'pexally-email-campaigns' ); ?></label>
                        <input type="number" id="smtp_port" name="smtp_port" class="pex-input" value="<?php echo esc_attr( $pexemail_smtp_port ); ?>">
                    </div>

                    <div class="pex-form-group">
                        <label class="pex-form-label"><?php esc_html_e( 'ENCRYPTION', 'pexally-email-campaigns' ); ?></label>
                        <select id="smtp_secure" name="smtp_secure" class="pex-input">
                            <option value="tls" <?php selected( $pexemail_smtp_secure, 'tls' ); ?>>TLS (Recommended)</option>
                            <option value="ssl" <?php selected( $pexemail_smtp_secure, 'ssl' ); ?>>SSL</option>
                        </select>
                    </div>

                    <div class="pex-form-group">
                        <label class="pex-form-label" id="lbl_smtp_username"><?php esc_html_e( 'SMTP USERNAME', 'pexally-email-campaigns' ); ?></label>
                        <input type="text" id="smtp_username" name="smtp_username" class="pex-input" value="<?php echo esc_attr( $pexemail_smtp_username ); ?>" autocomplete="new-password" data-lpignore="true" spellcheck="false" readonly onfocus="this.removeAttribute('readonly');">
                        <div class="pex-desc" id="hint_smtp_username"><?php esc_html_e( 'The authenticated username for your SMTP server.', 'pexally-email-campaigns' ); ?></div>
                    </div>
                    
                    <div class="pex-form-group" style="margin-bottom: 10px;">
                        <label class="pex-form-label" id="lbl_smtp_password"><?php esc_html_e( 'SMTP PASSWORD', 'pexally-email-campaigns' ); ?></label>
                        <div class="pex-pw-wrapper">
                            <input type="password" id="smtp_password" name="smtp_password" class="pex-input" value="<?php echo esc_attr( $pexemail_smtp_password ); ?>" style="padding-right: 75px;" autocomplete="new-password" data-lpignore="true" spellcheck="false" readonly onfocus="this.removeAttribute('readonly');">
                            <button type="button" class="pex-pw-toggle" onclick="let el = document.getElementById('smtp_password'); if(el.type === 'password') { el.type = 'text'; this.innerHTML = 'Hide'; } else { el.type = 'password'; this.innerHTML = 'Show'; }">Show</button>
                        </div>
                        <div class="pex-desc" id="hint_smtp_password" style="color: #b91c1c; font-weight: 500;">
                            <?php esc_html_e( 'Enter your secure App Password or API Key.', 'pexally-email-campaigns' ); ?>
                        </div>
                    </div>

                </div>

            </div>
        </div>

        <div style="margin-bottom: 50px;">
            <button type="submit" class="pex-btn-primary">
                <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"></path></svg>
                <?php esc_html_e( 'Save All Settings', 'pexally-email-campaigns' ); ?>
            </button>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const radioButtons = document.querySelectorAll('input[name="smtp_provider"]');
    const settingsWrapper = document.getElementById('pex-smtp-settings-wrapper');
    const enabledInput = document.getElementById('smtp_enabled_val');
    
    // Inputs & Titles
    const sectionTitle = document.getElementById('smtp-section-title');
    const hostInput = document.getElementById('smtp_host');
    const portInput = document.getElementById('smtp_port');
    const secureInput = document.getElementById('smtp_secure');
    const userInput = document.getElementById('smtp_username');
    const passInput = document.getElementById('smtp_password');
    
    // Hints & Labels
    const userHint = document.getElementById('hint_smtp_username');
    const passHint = document.getElementById('hint_smtp_password');
    const userLbl = document.getElementById('lbl_smtp_username');
    const passLbl = document.getElementById('lbl_smtp_password');

    // Store initial provider to detect intentional switches vs initial load
    let currentProvider = document.querySelector('input[name="smtp_provider"]:checked');
    currentProvider = currentProvider ? currentProvider.value : 'google';

    function handleProviderUI(val, isManualSwitch) {
        if (val === 'wp_mail') {
            settingsWrapper.style.display = 'none';
            enabledInput.value = 'no';
            return;
        }

        // Show wrapper with smooth animation if manual switch
        if(isManualSwitch && settingsWrapper.style.display === 'none') {
            settingsWrapper.style.display = 'block';
            settingsWrapper.classList.add('fade-in-slide');
            setTimeout(() => settingsWrapper.classList.remove('fade-in-slide'), 400);
        } else {
            settingsWrapper.style.display = 'block';
        }
        
        enabledInput.value = 'yes';

        // 1. If user actually clicked a DIFFERENT engine, flush old credentials and trigger Live Update CSS
        if (isManualSwitch && val !== currentProvider) {
            userInput.value = '';
            passInput.value = '';
            
            // Remove readonly lock immediately so they can type
            userInput.removeAttribute('readonly');
            passInput.removeAttribute('readonly');

            // Apply flash animation to show auto-fill is happening
            [hostInput, portInput, secureInput].forEach(el => {
                el.classList.remove('live-update');
                void el.offsetWidth; // trigger reflow
                el.classList.add('live-update');
            });
            
            currentProvider = val;
        }

        // 2. We apply defaults if it's a manual switch OR if the field is currently empty (Fresh Install Fix)
        const applyDefaults = isManualSwitch || !hostInput.value;

        if (val === 'google') {
            sectionTitle.innerText = 'Google Workspace Settings';
            if(applyDefaults) { hostInput.value = 'smtp.gmail.com'; portInput.value = '587'; }
            if(isManualSwitch) secureInput.value = 'tls';
            
            userLbl.innerText = 'GOOGLE WORKSPACE EMAIL';
            passLbl.innerText = 'GOOGLE APP PASSWORD';
            userHint.innerText = 'Enter your exact @gmail.com or Workspace email address.';
            passHint.innerText = 'Google Workspace users: Do NOT use your regular login password. You must generate a 16-character "App Password" in Google Security settings.';
        } 
        else if (val === 'sendgrid') {
            sectionTitle.innerText = 'SendGrid Settings';
            if(applyDefaults) { hostInput.value = 'smtp.sendgrid.net'; portInput.value = '587'; }
            if(isManualSwitch) secureInput.value = 'tls';
            
            userLbl.innerText = 'API KEY USERNAME';
            passLbl.innerText = 'SENDGRID API KEY';
            if(applyDefaults && !userInput.value) { 
                userInput.value = 'apikey'; 
                if(isManualSwitch) userInput.classList.add('live-update'); 
            }
            userHint.innerText = '';
            passHint.innerText = 'Enter your SendGrid API key starting with SG.';
        }
        else if (val === 'ses') {
            sectionTitle.innerText = 'Amazon SES Settings';
            if(applyDefaults) { hostInput.value = 'email-smtp.us-east-1.amazonaws.com'; portInput.value = '587'; }
            if(isManualSwitch) secureInput.value = 'tls';
            
            userLbl.innerText = 'SES SMTP USERNAME';
            passLbl.innerText = 'SES SMTP PASSWORD';
            userHint.innerText = 'Your generated AWS SES SMTP username.';
            passHint.innerText = 'Your generated AWS SES SMTP password.';
        }
        else if (val === 'mailgun') {
            sectionTitle.innerText = 'Mailgun Settings';
            if(applyDefaults) { hostInput.value = 'smtp.mailgun.org'; portInput.value = '587'; }
            if(isManualSwitch) secureInput.value = 'tls';
            
            userLbl.innerText = 'MAILGUN POSTMASTER';
            passLbl.innerText = 'MAILGUN PASSWORD';
            userHint.innerText = 'e.g. postmaster@yourdomain.com';
            passHint.innerText = 'Your Mailgun SMTP password.';
        }
        else {
            sectionTitle.innerText = 'Other SMTP Settings';
            if(isManualSwitch) { hostInput.value = ''; portInput.value = '587'; secureInput.value = 'tls'; }
            
            userLbl.innerText = 'SMTP USERNAME';
            passLbl.innerText = 'SMTP PASSWORD';
            userHint.innerText = 'The authenticated username for your SMTP server.';
            passHint.innerText = 'Enter your secure App Password or API Key.';
        }
    }

    // Attach event listeners
    radioButtons.forEach(radio => {
        radio.addEventListener('change', function() {
            handleProviderUI(this.value, true);
        });
    });

    // Run once on page load to initialize titles/labels and fill empty hosts
    handleProviderUI(currentProvider, false);
});
</script>