<?php
/**
 * Meta class for cart recovery emails.
 *
 * @package EDD\Pro\CartRecovery\Emails
 * @copyright Copyright (c) 2026, Sandhills Development, LLC
 * @license https://opensource.org/licenses/GPL-2.0 GNU Public License
 * @since 3.6.5
 */

namespace EDD\Pro\CartRecovery\Emails;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

use EDD\EventManagement\SubscriberInterface;

/**
 * Meta class for cart recovery emails.
 *
 * @since 3.6.5
 */
class Meta implements SubscriberInterface {

	/**
	 * Gets the subscribed events.
	 *
	 * @since 3.6.5
	 * @return array
	 */
	public static function get_subscribed_events(): array {
		return array(
			'edd_email_added'   => array( 'update_email_meta', 10, 2 ),
			'edd_email_updated' => array( 'update_email_meta', 10, 2 ),
		);
	}

	/**
	 * Updates the email meta.
	 *
	 * @since 3.6.5
	 * @param int|string $id   The email ID.
	 * @param array      $data The form data.
	 */
	public function update_email_meta( $id, $data = array() ) {
		if ( empty( $data['sender'] ) || 'edd' !== $data['sender'] ) {
			return;
		}
		if ( empty( $data['context'] ) || 'abandoned_cart' !== $data['context'] ) {
			return;
		}

		$email = edd_get_email( $id );
		if ( ! $email ) {
			return;
		}

		$template = $email->get_template();
		$unit     = $template ? $template->get_metadata( 'unit' ) : HOUR_IN_SECONDS;
		$delay    = ! empty( $data['delay'] ) ? ( absint( $data['delay'] ) * $unit ) : $template->get_metadata( 'delay' );
		edd_update_email_meta( $id, 'delay', $delay );

		if ( ! empty( $data['type'] ) && 'custom' === $data['type'] ) {
			edd_update_email_meta( $id, 'type', 'custom' );
		}

		// Save discount code selection.
		if ( isset( $data['discount_code'] ) ) {
			$discount_code = absint( $data['discount_code'] );
			if ( $discount_code > 0 ) {
				edd_update_email_meta( $id, 'discount_code', $discount_code );
			} else {
				edd_delete_email_meta( $id, 'discount_code' );
			}
		}
	}
}
