<?php
/**
 * Consent-first email opt-ins. Nothing is stored or sent without an
 * explicit user action; every record carries source + consent timestamp.
 *
 * @package 404Zen
 */

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

class LGBF_Optin {

	const OPTION = 'lgbf_optins';

	/**
	 * Records an explicit opt-in locally and relays it to the list endpoint.
	 *
	 * @param string $email  Email address.
	 * @param string $source dashboard_card|digest_settings.
	 * @return true|WP_Error
	 */
	public static function record( $email, $source ) {
		$email = sanitize_email( $email );
		if ( ! is_email( $email ) ) {
			return new WP_Error( 'lgbf_bad_email', __( 'Please enter a valid email address.', '404zen-broken-link-fixer' ) );
		}

		$clicks = get_option( 'zenplugins_promo_click' );
		$ref    = ( is_array( $clicks ) && ! empty( $clicks['404zen']['src'] ) ) ? sanitize_key( $clicks['404zen']['src'] ) : '';

		$entry = array(
			'email'      => $email,
			'source'     => sanitize_key( $source ) . ( $ref ? '_via_' . $ref : '' ),
			'consent_at' => gmdate( 'c' ),
		);

		$optins = get_option( self::OPTION, array() );
		if ( ! is_array( $optins ) ) {
			$optins = array();
		}
		$optins[ md5( $email . '|' . $entry['source'] ) ] = $entry;
		update_option( self::OPTION, $optins, false );

		// Relay to the flat-store endpoint we control (ESP swap comes later).
		wp_remote_post(
			'https://zenplugins.org/subscribe.php',
			array(
				'timeout' => 8,
				'body'    => array(
					'email'      => $email,
					'source'     => 'plugin_' . $entry['source'],
					'consent_at' => $entry['consent_at'],
				),
			)
		);

		return true;
	}

	/**
	 * Whether any opt-in has been recorded (hides the dashboard card).
	 *
	 * @return bool
	 */
	public static function has_optin() {
		$optins = get_option( self::OPTION, array() );

		return is_array( $optins ) && ! empty( $optins );
	}

}
