<?php
/**
 * SeedBirthdayEmailUpgrade.php.
 *
 * @package RewardsWP
 */

namespace Awesomemotive\Rewardswp\Database\Upgrades;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractDatabaseUpgrade;
use Awesomemotive\Rewardswp\Notifications\Emails\BirthdayRewardEmail;
use Awesomemotive\Rewardswp\Services\EmailsService;
use Exception;
use function Awesomemotive\Rewardswp\Helpers\rewardswp_log_error;

/**
 * Seed Birthday Email Upgrade
 *
 * Creates the birthday reward email template for existing installations
 * that already ran the 1.1.0 SeedDefaultEmailsUpgrade before the
 * birthday feature was added.
 *
 * @since 1.4.0
 */
class SeedBirthdayEmailUpgrade extends AbstractDatabaseUpgrade {
	/**
	 * The version this upgrade targets.
	 *
	 * @since 1.4.0
	 * @var string
	 */
	protected string $version = '1.4.0';

	/**
	 * Emails service instance.
	 *
	 * @since 1.4.0
	 * @var EmailsService
	 */
	private EmailsService $emails_service;

	/**
	 * Constructor.
	 *
	 * @since 1.4.0
	 *
	 * @param EmailsService $emails_service The emails service instance.
	 */
	public function __construct( EmailsService $emails_service ) {
		$this->emails_service = $emails_service;
	}

	/**
	 * Run the upgrade.
	 *
	 * Seeds the birthday reward email template if it doesn't already exist.
	 *
	 * @since 1.4.0
	 * @return void
	 */
	public function up(): void {
		try {
			if ( ! $this->emails_service->email_exists( 'birthday_reward' ) ) {
				$email_data = $this->emails_service->extract_email_data_from_class( BirthdayRewardEmail::class );
				$this->emails_service->create_email( $email_data );
			}
		} catch ( Exception $e ) {
			rewardswp_log_error(
				'Failed to seed birthday reward email: {message}',
				[
					'message' => $e->getMessage(),
				]
			);
		}
	}
}
