<?php

/**
 * Consent-gated lifecycle notifications.
 *
 * Emails the developer on install / activation / deactivation, but only after
 * the administrator opts in. Required for GDPR (explicit opt-in, withdrawable)
 * and the WordPress.org "no tracking without consent" guideline.
 *
 * @package    Esraw
 * @subpackage Esraw/includes
 */

namespace EasyShippingRate;

class Notifications {

	/**
	 * Master switch for the whole lifecycle-notification feature. Off for now:
	 * no consent modal, no settings checkbox, no emails. Flip to true to bring
	 * everything back — the code stays in place.
	 */
	const ENABLED = false;

	const CONSENT_OPTION  = 'esraw_usage_consent';
	const PENDING_OPTION  = 'esraw_notify_pending';
	const INSTALLED_FLAG  = 'esraw_notify_installed_sent';
	const SNOOZE_OPTION   = 'esraw_consent_snooze_until';
	const DECLINES_OPTION = 'esraw_consent_declines';
	const NONCE           = 'esraw-usage-consent';

	// Stop asking after this many declines.
	const MAX_DECLINES = 2;

	public static function on_activation() {
		if ( ! self::ENABLED ) {
			return;
		}
		// Defer the email: consent may not be granted yet. flush_pending() sends it.
		$event = get_option( self::INSTALLED_FLAG ) ? 'activated' : 'installed';
		update_option( self::PENDING_OPTION, $event );

		// Ask again on every activation until the admin has opted in.
		if ( 'yes' !== get_option( self::CONSENT_OPTION ) ) {
			delete_option( self::CONSENT_OPTION );
			delete_option( self::SNOOZE_OPTION );
			delete_option( self::DECLINES_OPTION );
		}
	}

	public static function on_deactivation() {
		if ( ! self::ENABLED ) {
			return;
		}
		// Send now: the plugin will not run again to send it later.
		if ( 'yes' === get_option( self::CONSENT_OPTION ) ) {
			self::send( 'deactivated' );
		}
	}

	public static function handle_consent_action() {
		if ( ! self::ENABLED ) {
			return;
		}
		if ( ! isset( $_GET['esraw_consent'] ) ) {
			return;
		}
		check_admin_referer( self::NONCE );
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$choice = sanitize_key( wp_unslash( $_GET['esraw_consent'] ) );
		if ( 'yes' === $choice ) {
			update_option( self::CONSENT_OPTION, 'yes' );
		} elseif ( 'decline' === $choice ) {
			self::decline();
		}

		wp_safe_redirect( remove_query_arg( array( 'esraw_consent', '_wpnonce' ) ) );
		exit;
	}

	private static function decline() {
		$declines = (int) get_option( self::DECLINES_OPTION, 0 ) + 1;
		update_option( self::DECLINES_OPTION, $declines );

		// Refused MAX_DECLINES times: stop asking for good.
		if ( $declines >= self::MAX_DECLINES ) {
			update_option( self::CONSENT_OPTION, 'no' );
			delete_option( self::PENDING_OPTION );
			delete_option( self::SNOOZE_OPTION );
			return;
		}

		update_option( self::SNOOZE_OPTION, time() + 2 * WEEK_IN_SECONDS );
	}

	public static function flush_pending() {
		if ( ! self::ENABLED ) {
			return;
		}
		if ( 'yes' !== get_option( self::CONSENT_OPTION ) ) {
			return;
		}
		$event = get_option( self::PENDING_OPTION );
		if ( ! $event ) {
			return;
		}
		self::send( $event );
		delete_option( self::PENDING_OPTION );
		if ( 'installed' === $event ) {
			update_option( self::INSTALLED_FLAG, 1 );
		}
	}

	public static function enqueue_assets() {
		if ( ! self::should_ask_consent() ) {
			return;
		}
		wp_enqueue_style( 'esraw-tailwind', ESRAW_URL . 'src/Admin/css/tailwind.build.css', array(), ESRAW_VERSION );
	}

	public static function render_consent_modal() {
		if ( ! self::should_ask_consent() ) {
			return;
		}

		$allow_url   = wp_nonce_url( add_query_arg( 'esraw_consent', 'yes' ), self::NONCE );
		$decline_url = wp_nonce_url( add_query_arg( 'esraw_consent', 'decline' ), self::NONCE );
		?>
		<div class="esraw-fixed esraw-inset-0 esraw-z-[100000] esraw-flex esraw-items-center esraw-justify-center esraw-bg-black/60 esraw-p-4">
			<div class="esraw-relative esraw-w-full esraw-max-w-md esraw-overflow-hidden esraw-rounded-xl esraw-bg-white esraw-shadow-2xl">
				<a href="<?php echo esc_url( $decline_url ); ?>" class="esraw-absolute esraw-right-3 esraw-top-3 esraw-flex esraw-text-white/80 esraw-no-underline hover:esraw-text-white" aria-label="<?php esc_attr_e( 'Dismiss', 'easy-shipping-rate' ); ?>">
					<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>
				</a>
				<div class="esraw-flex esraw-flex-col esraw-items-center esraw-gap-3 esraw-bg-brand esraw-px-6 esraw-py-7 esraw-text-center">
					<span class="esraw-flex esraw-h-12 esraw-w-12 esraw-items-center esraw-justify-center esraw-rounded-full esraw-bg-white/20">
						<span class="dashicons dashicons-email-alt esraw-text-white" aria-hidden="true"></span>
					</span>
					<h2 class="esraw-m-0 esraw-p-0 esraw-text-xl esraw-font-bold esraw-text-white">
						<?php esc_html_e( 'Stay in touch?', 'easy-shipping-rate' ); ?>
					</h2>
				</div>
				<div class="esraw-px-6 esraw-py-6 esraw-text-center">
					<p class="esraw-m-0 esraw-mb-5 esraw-text-sm esraw-leading-relaxed esraw-text-gray-600">
						<?php
						esc_html_e( 'May we email the developer when Easy Shipping Rate is installed, activated or deactivated? This helps us understand adoption and guides future free features. We only send the event, the plugin version and the date. You can decline and keep using the plugin, and change this anytime in the settings.', 'easy-shipping-rate' );
						?>
					</p>
					<div class="esraw-flex esraw-flex-col esraw-gap-3">
						<a href="<?php echo esc_url( $allow_url ); ?>" class="esraw-inline-flex esraw-items-center esraw-justify-center esraw-rounded-md esraw-bg-brand esraw-px-5 esraw-py-3 esraw-text-sm esraw-font-semibold esraw-text-white esraw-no-underline esraw-shadow hover:esraw-bg-brand-dark">
							<?php esc_html_e( 'Allow notifications', 'easy-shipping-rate' ); ?>
						</a>
						<a href="<?php echo esc_url( $decline_url ); ?>" class="esraw-text-xs esraw-text-gray-500 esraw-no-underline hover:esraw-text-gray-700">
							<?php esc_html_e( 'No thanks', 'easy-shipping-rate' ); ?>
						</a>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	private static function should_ask_consent() {
		if ( ! self::ENABLED ) {
			return false;
		}
		if ( ! current_user_can( 'manage_options' ) || false !== get_option( self::CONSENT_OPTION ) ) {
			return false;
		}
		$snooze = (int) get_option( self::SNOOZE_OPTION, 0 );
		return ! ( $snooze && time() < $snooze );
	}

	/**
	 * @param string $event installed|activated|deactivated
	 */
	private static function send( $event ) {
		$to = defined( 'ESRAW_NOTIFY_EMAIL' ) ? ESRAW_NOTIFY_EMAIL : '';
		if ( ! $to || ! is_email( $to ) ) {
			return;
		}

		$body = implode(
			"\n",
			array(
				sprintf( 'Event: %s', $event ),
				sprintf( 'Plugin version: %s', defined( 'ESRAW_VERSION' ) ? ESRAW_VERSION : '' ),
				sprintf( 'Date: %s UTC', gmdate( 'Y-m-d H:i:s' ) ),
			)
		);

		wp_mail( $to, sprintf( '[Easy Shipping Rate] %s', $event ), $body );
	}
}
