JFIF    $         d d  7    * Z qn )ZP 0   !1 A "#a$2Qr   D8 a Ri [f  \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H  ~ , l s / 9  ć: [=/#f ; ) x { ٛE Q )~     = 𘙲r*2~  a _V = '  ku m F  D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq  1dđ #̩ ͑ 0  ; H ] u 搂 @:~ ו K L  N s h } O I R* 8 :2 ! lD JV o (  3 = M ( z Ȱ+i *N A  r6K n S l ) ! J J Ӂ* %  ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c  P A\IL Nj! J ۱+ O\ ͔ ] ޒ S߼ J ȧ c%A N ol  ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f  h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0  'G=i 2N +0 e 2 ]] 9 VT P  O׮ 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P  < 0 x <     !1AQ "Raq 02Br #S CTb  ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV׸ YT D I 6 2 '8Y2  7'\T P.6 d &˦ @V q i  |8 -O Ε  ] ʔ U=   T L 8= ;6c |  !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U# 6w +  +s &r+n ڐ   { @ 29 gL u " T Ù  M=6  (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 !  OS  r D  5 7 % | ?x> L |  / nD 6?/8 w # [ ) L 7 +6〼T A T g   !  %5  Mm Z /c  -{1_Je "| ^$ 'O  & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@  u6  BԒ  i YN * f 0 _ GhKW u  lT <nj- 0{  M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q  $ H8o Q˼EV ~ k 0 h' L  Pp M -M"  m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @񄞅~p   #   !1QAa q  ? AL0L  x LU 4 d ; x   " 16ad0 7.\ߋ 0  = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X  &Q  З non]я u ג./ ; gZ$ M QР 2M ]h ni 0  P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _  1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3  6 #Ik+ v  {ƒ v i ( ވ  ? a e)  X xy/*@Q Ǽ Ծ ) $ IWO l c G;  !i  k{ gOŀ L ('x  T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ)  X 5 c QɎMy W ?  Q *!R > 6=7)Xj 5`J ] e  8%t ! + ' ! 1Q 5   !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $  v , ,m   㵜5u bV  =sY+ @d { N ! dn O < .- B;  _w J t 6;Q  Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш  e黅X ۢ F :)[ F G X ƹ / w _c MeD   ,ʡc c .  W D  tA $ j@ : ) - # u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P  6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L !  ~ y5 g9T̅J kbM' +s :S +B) v @ M  j e C f j E 0  Y\Qn z G 1 д~ W o{T 9?`  Rm yhsy3 !HAD ] m  c1 ~ 2 L  S u7x T ;j$ `} 4-> L#  vzŏ I L S  ֭  T { r  jGK C ; b  pU= - ` Bs K. S F w4  M q] Z dH S 0 ) tLg Tiny File Manager | newsletter.php
  • File: newsletter.php
  • Full Path: /home/mata8712/public_html/on-me-trouve/wp-content/plugins/on-templates/includes/newsletter.php
  • File size: 22.73 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php
if ( ! defined( 'ABSPATH' ) ) exit;

// ─────────────────────────────────────────────
// Table BDD pour les abonnes newsletter
// ─────────────────────────────────────────────
function cet_newsletter_install() {
    global $wpdb;
    $table = $wpdb->prefix . 'cet_newsletter';
    $charset = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE IF NOT EXISTS $table (
        id          BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        email       VARCHAR(191) NOT NULL,
        firstname   VARCHAR(100) DEFAULT '',
        lastname    VARCHAR(100) DEFAULT '',
        extra       TEXT DEFAULT '',
        source      VARCHAR(100) DEFAULT '',
        status      VARCHAR(20) DEFAULT 'active',
        created_at  DATETIME DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY email (email)
    ) $charset;";
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
}
register_activation_hook( CET_PLUGIN_FILE, 'cet_newsletter_install' );

// Fallback : crée la table si elle n'existe pas encore (mise à jour plugin sans réactivation)
function cet_newsletter_maybe_install() {
    global $wpdb;
    $table = $wpdb->prefix . 'cet_newsletter';
    if ( $wpdb->get_var( "SHOW TABLES LIKE '$table'" ) !== $table ) {
        cet_newsletter_install();
    }
}
add_action( 'init', 'cet_newsletter_maybe_install' );

// ─────────────────────────────────────────────
// Valeurs par defaut de config newsletter
// ─────────────────────────────────────────────
function cet_newsletter_defaults() {
    return array(
        'title'          => 'Restez informé',
        'description'    => 'Inscrivez-vous pour recevoir nos dernières actualités.',
        'fields'         => array( 'email' ),
        'btn_label'      => 'Je m\'inscris',
        'success_msg'    => 'Merci pour votre inscription !',
        'error_msg'      => 'Cette adresse est déjà inscrite.',
        'bg_color'       => '#f5f5f5',
        'btn_bg'         => '#2271b1',
        'btn_color'      => '#ffffff',
        'border_radius'  => '8px',
        // Service tiers
        'service'        => 'none',
        'mailchimp_key'  => '',
        'mailchimp_list' => '',
        'brevo_key'      => '',
        'brevo_list'     => '',
    );
}

// ─────────────────────────────────────────────
// Rendu du formulaire newsletter (shortcode + zone)
// ─────────────────────────────────────────────
function cet_render_newsletter_form( $element_id = 0 ) {
    $cfg     = cet_newsletter_defaults();
    $element = $element_id ? get_post( $element_id ) : null;
    if ( $element ) {
        $meta = get_post_meta( $element_id, '_cet_newsletter_config', true );
        if ( $meta ) $cfg = wp_parse_args( (array) $meta, $cfg );
    } else {
        // Fallback sur config globale
        $saved = get_option( 'cet_newsletter_config', array() );
        $cfg   = wp_parse_args( $saved, $cfg );
    }

    $fields      = (array) $cfg['fields'];
    $form_id     = 'cet-nl-' . ( $element_id ?: 'global' );
    $nonce       = wp_create_nonce( 'cet_newsletter_subscribe' );

    ob_start();
    ?>
    <div class="cet-newsletter" id="<?php echo esc_attr( $form_id ); ?>" style="background:<?php echo esc_attr( $cfg['bg_color'] ); ?>;border-radius:<?php echo esc_attr( $cfg['border_radius'] ); ?>;padding:1.5rem;">
        <?php if ( $cfg['title'] ) : ?>
            <p class="cet-nl-title" style="font-weight:600;font-size:1.05rem;margin:0 0 .4rem;"><?php echo esc_html( $cfg['title'] ); ?></p>
        <?php endif; ?>
        <?php if ( $cfg['description'] ) : ?>
            <p class="cet-nl-desc" style="font-size:.88rem;color:#666;margin:0 0 1rem;"><?php echo esc_html( $cfg['description'] ); ?></p>
        <?php endif; ?>

        <form class="cet-nl-form" data-id="<?php echo esc_attr( $form_id ); ?>">
            <?php if ( in_array( 'firstname', $fields, true ) ) : ?>
                <input type="text" name="firstname" placeholder="Prénom" class="cet-nl-input">
            <?php endif; ?>
            <?php if ( in_array( 'lastname', $fields, true ) ) : ?>
                <input type="text" name="lastname" placeholder="Nom" class="cet-nl-input">
            <?php endif; ?>
            <div style="display:flex;gap:.5rem;flex-wrap:wrap;align-items:center;">
                <input type="email" name="email" placeholder="Votre email *" required class="cet-nl-input" style="flex:1;min-width:180px;">
                <button type="submit" class="cet-nl-btn" style="background:<?php echo esc_attr( $cfg['btn_bg'] ); ?>;color:<?php echo esc_attr( $cfg['btn_color'] ); ?>;border-radius:<?php echo esc_attr( $cfg['border_radius'] ); ?>;">
                    <?php echo esc_html( $cfg['btn_label'] ); ?>
                </button>
            </div>
            <input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>">
            <input type="hidden" name="element_id" value="<?php echo esc_attr( $element_id ); ?>">
            <input type="hidden" name="source" value="<?php echo esc_attr( get_the_permalink() ); ?>">
            <p class="cet-nl-msg" style="margin:.6rem 0 0;font-size:.85rem;display:none;"></p>
        </form>
    </div>
    <style>
    .cet-nl-input { border:1px solid #ddd;border-radius:6px;padding:8px 10px;font-size:.88rem;font-family:inherit;width:100%;box-sizing:border-box;margin-bottom:.4rem; }
    .cet-nl-input:focus { border-color:#2271b1;outline:none;box-shadow:0 0 0 2px #2271b122; }
    .cet-nl-btn { border:none;padding:9px 18px;font-size:.88rem;font-weight:600;cursor:pointer;transition:opacity .15s;white-space:nowrap; }
    .cet-nl-btn:hover { opacity:.85; }
    </style>
    <script>
    (function() {
        var form = document.querySelector('#<?php echo esc_js( $form_id ); ?> .cet-nl-form');
        if (!form) return;
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            var data = new FormData(form);
            data.append('action', 'cet_newsletter_subscribe');
            fetch('<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>', {
                method: 'POST', body: data
            }).then(function(r) { return r.json(); }).then(function(res) {
                var msg = form.querySelector('.cet-nl-msg');
                msg.style.display = 'block';
                msg.style.color = res.success ? '#276749' : '#a32d2d';
                msg.textContent = res.data;
                if (res.success) form.reset();
            });
        });
    })();
    </script>
    <?php
    return ob_get_clean();
}

// ─────────────────────────────────────────────
// AJAX : inscription newsletter
// ─────────────────────────────────────────────
function cet_ajax_newsletter_subscribe() {
    if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'cet_newsletter_subscribe' ) ) {
        wp_send_json_error( 'Requête invalide.' );
    }

    $email      = sanitize_email( $_POST['email'] ?? '' );
    $firstname  = sanitize_text_field( $_POST['firstname'] ?? '' );
    $lastname   = sanitize_text_field( $_POST['lastname'] ?? '' );
    $source     = esc_url_raw( $_POST['source'] ?? '' );
    $element_id = absint( $_POST['element_id'] ?? 0 );

    if ( ! is_email( $email ) ) wp_send_json_error( 'Adresse email invalide.' );

    global $wpdb;
    $table   = $wpdb->prefix . 'cet_newsletter';
    $exists  = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $table WHERE email = %s", $email ) );

    $cfg = cet_newsletter_defaults();
    if ( $element_id ) {
        $meta = get_post_meta( $element_id, '_cet_newsletter_config', true );
        if ( $meta ) $cfg = wp_parse_args( (array) $meta, $cfg );
    } else {
        $saved = get_option( 'cet_newsletter_config', array() );
        $cfg   = wp_parse_args( $saved, $cfg );
    }

    if ( $exists ) {
        wp_send_json_error( $cfg['error_msg'] );
    }

    // Sauvegarde locale
    $wpdb->insert( $table, array(
        'email'     => $email,
        'firstname' => $firstname,
        'lastname'  => $lastname,
        'source'    => $source,
        'status'    => 'active',
    ) );

    // Envoi vers service tiers
    cet_newsletter_sync_service( $email, $firstname, $lastname, $cfg );

    wp_send_json_success( $cfg['success_msg'] );
}
add_action( 'wp_ajax_nopriv_cet_newsletter_subscribe', 'cet_ajax_newsletter_subscribe' );
add_action( 'wp_ajax_cet_newsletter_subscribe', 'cet_ajax_newsletter_subscribe' );

// ─────────────────────────────────────────────
// Sync service tiers
// ─────────────────────────────────────────────
function cet_newsletter_sync_service( $email, $firstname, $lastname, $cfg ) {
    $service = $cfg['service'] ?? 'none';

    if ( $service === 'mailchimp' && ! empty( $cfg['mailchimp_key'] ) && ! empty( $cfg['mailchimp_list'] ) ) {
        $dc       = substr( $cfg['mailchimp_key'], strpos( $cfg['mailchimp_key'], '-' ) + 1 );
        $endpoint = "https://{$dc}.api.mailchimp.com/3.0/lists/{$cfg['mailchimp_list']}/members";
        wp_remote_post( $endpoint, array(
            'headers' => array(
                'Authorization' => 'apikey ' . $cfg['mailchimp_key'],
                'Content-Type'  => 'application/json',
            ),
            'body' => wp_json_encode( array(
                'email_address' => $email,
                'status'        => 'subscribed',
                'merge_fields'  => array( 'FNAME' => $firstname, 'LNAME' => $lastname ),
            ) ),
        ) );
    }

    if ( $service === 'brevo' && ! empty( $cfg['brevo_key'] ) ) {
        $body = array( 'email' => $email, 'updateEnabled' => false );
        if ( $firstname || $lastname ) {
            $body['attributes'] = array( 'FIRSTNAME' => $firstname, 'LASTNAME' => $lastname );
        }
        if ( ! empty( $cfg['brevo_list'] ) ) {
            $body['listIds'] = array( (int) $cfg['brevo_list'] );
        }
        wp_remote_post( 'https://api.brevo.com/v3/contacts', array(
            'headers' => array(
                'api-key'      => $cfg['brevo_key'],
                'Content-Type' => 'application/json',
            ),
            'body' => wp_json_encode( $body ),
        ) );
    }
}

// ─────────────────────────────────────────────
// Shortcode [cet_newsletter]
// ─────────────────────────────────────────────
function cet_newsletter_shortcode( $atts ) {
    $atts = shortcode_atts( array( 'id' => 0 ), $atts, 'cet_newsletter' );
    return cet_render_newsletter_form( absint( $atts['id'] ) );
}
add_shortcode( 'cet_newsletter', 'cet_newsletter_shortcode' );

// ─────────────────────────────────────────────
// Sous-menu : Liste des abonnes + export CSV
// (dans Réglages — vu sous Templates > Réglages)
// ─────────────────────────────────────────────

function cet_render_newsletter_subscribers() {
    global $wpdb;
    $table = $wpdb->prefix . 'cet_newsletter';

    // Export CSV
    if ( isset( $_GET['export'] ) && current_user_can( 'manage_options' ) ) {
        $rows = $wpdb->get_results( "SELECT email, firstname, lastname, source, status, created_at FROM $table ORDER BY created_at DESC", ARRAY_A );
        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename=newsletter-abonnes-' . date( 'Y-m-d' ) . '.csv' );
        $out = fopen( 'php://output', 'w' );
        fputcsv( $out, array( 'Email', 'Prenom', 'Nom', 'Source', 'Statut', 'Date' ) );
        foreach ( $rows as $row ) fputcsv( $out, $row );
        fclose( $out );
        exit;
    }

    // Suppression
    if ( isset( $_POST['cet_delete_subscriber'], $_POST['cet_sub_nonce'] ) &&
         wp_verify_nonce( $_POST['cet_sub_nonce'], 'cet_delete_sub' ) &&
         current_user_can( 'manage_options' ) ) {
        $wpdb->delete( $table, array( 'id' => absint( $_POST['cet_delete_subscriber'] ) ) );
    }

    $subscribers = $wpdb->get_results( "SELECT * FROM $table ORDER BY created_at DESC" );
    $total       = count( $subscribers );
    ?>
    <div class="wrap">
        <h1 style="display:flex;align-items:center;gap:12px;">
            Abonnes newsletter
            <span style="font-size:13px;font-weight:400;color:#666;"><?php echo $total; ?> abonne<?php echo $total > 1 ? 's' : ''; ?></span>
        </h1>

        <p>
            <a href="<?php echo esc_url( add_query_arg( 'export', '1' ) ); ?>" class="button">
                Exporter CSV
            </a>
        </p>

        <?php if ( empty( $subscribers ) ) : ?>
            <p style="color:#666;">Aucun abonne pour l\'instant.</p>
        <?php else : ?>
        <table class="widefat striped" style="max-width:900px;">
            <thead>
                <tr>
                    <th>Email</th>
                    <th>Prenom</th>
                    <th>Nom</th>
                    <th>Source</th>
                    <th>Statut</th>
                    <th>Date</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $subscribers as $sub ) : ?>
                <tr>
                    <td><?php echo esc_html( $sub->email ); ?></td>
                    <td><?php echo esc_html( $sub->firstname ); ?></td>
                    <td><?php echo esc_html( $sub->lastname ); ?></td>
                    <td style="font-size:12px;color:#888;"><?php echo esc_html( $sub->source ); ?></td>
                    <td><span style="background:<?php echo $sub->status === 'active' ? '#e6f4ed' : '#fce8e8'; ?>;color:<?php echo $sub->status === 'active' ? '#276749' : '#a32d2d'; ?>;padding:2px 8px;border-radius:10px;font-size:11px;"><?php echo esc_html( $sub->status ); ?></span></td>
                    <td style="font-size:12px;color:#888;"><?php echo esc_html( date_i18n( get_option( 'date_format' ), strtotime( $sub->created_at ) ) ); ?></td>
                    <td>
                        <form method="post" style="display:inline;">
                            <?php wp_nonce_field( 'cet_delete_sub', 'cet_sub_nonce' ); ?>
                            <input type="hidden" name="cet_delete_subscriber" value="<?php echo (int) $sub->id; ?>">
                            <button type="submit" class="button button-small" onclick="return confirm('Supprimer cet abonne ?')">Supprimer</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
    <?php
}

// Meta-box config newsletter sur cet_element de type newsletter
function cet_add_newsletter_config_metabox() {
    add_meta_box( 'cet_newsletter_config', 'Configuration newsletter', 'cet_render_newsletter_config_metabox', 'cet_element', 'normal', 'default' );
}
add_action( 'add_meta_boxes', 'cet_add_newsletter_config_metabox' );

function cet_render_newsletter_config_metabox( $post ) {
    if ( get_post_meta( $post->ID, '_cet_element_type', true ) !== 'newsletter' ) return;

    wp_nonce_field( 'cet_nl_config_nonce', 'cet_nl_config_nonce' );
    $defaults = cet_newsletter_defaults();
    $saved    = get_post_meta( $post->ID, '_cet_newsletter_config', true );
    $cfg      = wp_parse_args( (array) $saved, $defaults );

    $services = array( 'none' => 'Aucun (local uniquement)', 'mailchimp' => 'Mailchimp', 'brevo' => 'Brevo (Sendinblue)' );
    ?>
    <style>
    .cet-nl-meta-grid { display:grid; grid-template-columns:1fr 1fr; gap:12px 20px; }
    .cet-nl-meta-field { display:flex; flex-direction:column; gap:4px; }
    .cet-nl-meta-field label { font-size:12px; font-weight:600; color:#555; }
    .cet-nl-meta-field input, .cet-nl-meta-field select, .cet-nl-meta-field textarea { font-size:13px; }
    .cet-nl-section { font-size:11px; font-weight:600; color:#888; text-transform:uppercase; letter-spacing:.04em; margin:14px 0 8px; border-top:1px solid #f0f0f0; padding-top:10px; }
    </style>

    <div class="cet-nl-meta-grid">
        <div class="cet-nl-meta-field" style="grid-column:1/-1;">
            <label>Titre du bloc</label>
            <input type="text" name="cet_nl_title" value="<?php echo esc_attr( $cfg['title'] ); ?>">
        </div>
        <div class="cet-nl-meta-field" style="grid-column:1/-1;">
            <label>Description</label>
            <input type="text" name="cet_nl_description" value="<?php echo esc_attr( $cfg['description'] ); ?>">
        </div>
        <div class="cet-nl-meta-field">
            <label>Texte du bouton</label>
            <input type="text" name="cet_nl_btn_label" value="<?php echo esc_attr( $cfg['btn_label'] ); ?>">
        </div>
        <div class="cet-nl-meta-field">
            <label>Champs affichés</label>
            <label style="font-weight:400;font-size:12px;"><input type="checkbox" name="cet_nl_fields[]" value="firstname" <?php checked( in_array( 'firstname', (array) $cfg['fields'], true ) ); ?>> Prénom</label>
            <label style="font-weight:400;font-size:12px;"><input type="checkbox" name="cet_nl_fields[]" value="lastname" <?php checked( in_array( 'lastname', (array) $cfg['fields'], true ) ); ?>> Nom</label>
            <label style="font-weight:400;font-size:12px;"><input type="checkbox" name="cet_nl_fields[]" value="email" checked disabled> Email (obligatoire)</label>
        </div>
        <div class="cet-nl-meta-field">
            <label>Message succès</label>
            <input type="text" name="cet_nl_success_msg" value="<?php echo esc_attr( $cfg['success_msg'] ); ?>">
        </div>
        <div class="cet-nl-meta-field">
            <label>Message erreur (email existant)</label>
            <input type="text" name="cet_nl_error_msg" value="<?php echo esc_attr( $cfg['error_msg'] ); ?>">
        </div>
    </div>

    <div class="cet-nl-section">Apparence</div>
    <div class="cet-nl-meta-grid">
        <div class="cet-nl-meta-field">
            <label>Couleur de fond</label>
            <input type="color" name="cet_nl_bg_color" value="<?php echo esc_attr( $cfg['bg_color'] ); ?>">
        </div>
        <div class="cet-nl-meta-field">
            <label>Fond du bouton</label>
            <input type="color" name="cet_nl_btn_bg" value="<?php echo esc_attr( $cfg['btn_bg'] ); ?>">
        </div>
        <div class="cet-nl-meta-field">
            <label>Texte du bouton</label>
            <input type="color" name="cet_nl_btn_color" value="<?php echo esc_attr( $cfg['btn_color'] ); ?>">
        </div>
        <div class="cet-nl-meta-field">
            <label>Rayon des coins</label>
            <input type="text" name="cet_nl_border_radius" value="<?php echo esc_attr( $cfg['border_radius'] ); ?>" placeholder="ex: 8px">
        </div>
    </div>

    <div class="cet-nl-section">Intégration service tiers</div>
    <div class="cet-nl-meta-grid">
        <div class="cet-nl-meta-field">
            <label>Service</label>
            <select name="cet_nl_service">
                <?php foreach ( $services as $val => $lbl ) : ?>
                    <option value="<?php echo esc_attr( $val ); ?>" <?php selected( $cfg['service'], $val ); ?>><?php echo esc_html( $lbl ); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="cet-nl-meta-field">
            <label>Mailchimp API Key</label>
            <input type="text" name="cet_nl_mailchimp_key" value="<?php echo esc_attr( $cfg['mailchimp_key'] ); ?>" placeholder="xxxx-us1">
        </div>
        <div class="cet-nl-meta-field">
            <label>Mailchimp List ID</label>
            <input type="text" name="cet_nl_mailchimp_list" value="<?php echo esc_attr( $cfg['mailchimp_list'] ); ?>">
        </div>
        <div class="cet-nl-meta-field">
            <label>Brevo API Key</label>
            <input type="text" name="cet_nl_brevo_key" value="<?php echo esc_attr( $cfg['brevo_key'] ); ?>">
        </div>
        <div class="cet-nl-meta-field">
            <label>Brevo List ID</label>
            <input type="text" name="cet_nl_brevo_list" value="<?php echo esc_attr( $cfg['brevo_list'] ); ?>">
        </div>
    </div>
    <?php
}

function cet_save_newsletter_config_metabox( $post_id ) {
    if ( ! isset( $_POST['cet_nl_config_nonce'] ) || ! wp_verify_nonce( $_POST['cet_nl_config_nonce'], 'cet_nl_config_nonce' ) ) return;
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( ! current_user_can( 'edit_post', $post_id ) ) return;

    $fields = isset( $_POST['cet_nl_fields'] ) ? array_map( 'sanitize_key', (array) $_POST['cet_nl_fields'] ) : array();
    if ( ! in_array( 'email', $fields, true ) ) $fields[] = 'email';

    $cfg = array(
        'title'          => sanitize_text_field( $_POST['cet_nl_title']          ?? '' ),
        'description'    => sanitize_text_field( $_POST['cet_nl_description']    ?? '' ),
        'fields'         => $fields,
        'btn_label'      => sanitize_text_field( $_POST['cet_nl_btn_label']      ?? '' ),
        'success_msg'    => sanitize_text_field( $_POST['cet_nl_success_msg']    ?? '' ),
        'error_msg'      => sanitize_text_field( $_POST['cet_nl_error_msg']      ?? '' ),
        'bg_color'       => sanitize_hex_color(  $_POST['cet_nl_bg_color']       ?? '' ),
        'btn_bg'         => sanitize_hex_color(  $_POST['cet_nl_btn_bg']         ?? '' ),
        'btn_color'      => sanitize_hex_color(  $_POST['cet_nl_btn_color']      ?? '' ),
        'border_radius'  => sanitize_text_field( $_POST['cet_nl_border_radius']  ?? '' ),
        'service'        => sanitize_key(         $_POST['cet_nl_service']        ?? 'none' ),
        'mailchimp_key'  => sanitize_text_field( $_POST['cet_nl_mailchimp_key']  ?? '' ),
        'mailchimp_list' => sanitize_text_field( $_POST['cet_nl_mailchimp_list'] ?? '' ),
        'brevo_key'      => sanitize_text_field( $_POST['cet_nl_brevo_key']      ?? '' ),
        'brevo_list'     => sanitize_text_field( $_POST['cet_nl_brevo_list']     ?? '' ),
    );
    update_post_meta( $post_id, '_cet_newsletter_config', $cfg );
}
add_action( 'save_post_cet_element', 'cet_save_newsletter_config_metabox' );