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

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

class RDZ_Optin {

	const OPTION = 'rdz_optin';

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

		$entry = array(
			'email'      => $email,
			'source'     => sanitize_key( $source ),
			'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://redirectzen.com/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 );
	}
}
