<?php
/**
 * Quiet newsletter capture — no popup, no ESP.
 *
 * @package Foliora
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handle Join the Reading List.
 */
function foliora_handle_newsletter() {
	if ( ! isset( $_POST['foliora_newsletter_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['foliora_newsletter_nonce'] ) ), 'foliora_newsletter' ) ) {
		wp_safe_redirect( home_url( '/#newsletter' ) );
		exit;
	}

	$email = isset( $_POST['foliora_email'] ) ? sanitize_email( wp_unslash( $_POST['foliora_email'] ) ) : '';
	if ( $email && is_email( $email ) ) {
		$list   = get_option( 'foliora_newsletter_emails', array() );
		$list   = is_array( $list ) ? $list : array();
		$list[] = $email;
		update_option( 'foliora_newsletter_emails', array_values( array_unique( $list ) ) );
	}

	wp_safe_redirect( add_query_arg( 'list', 'joined', home_url( '/#newsletter' ) ) );
	exit;
}
add_action( 'admin_post_nopriv_foliora_newsletter', 'foliora_handle_newsletter' );
add_action( 'admin_post_foliora_newsletter', 'foliora_handle_newsletter' );
