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

namespace Awesomemotive\Rewardswp\Database\Upgrades;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractDatabaseUpgrade;
use Awesomemotive\Rewardswp\Notifications\Emails\AdvocateRewardEmail;
use Awesomemotive\Rewardswp\Notifications\Emails\PointsEarnedEmail;
use Awesomemotive\Rewardswp\Notifications\Emails\PointsExpirationEmail;
use Awesomemotive\Rewardswp\Notifications\Emails\RewardRedemptionEmail;
use Awesomemotive\Rewardswp\Notifications\Emails\FriendRewardEmail;
// use Awesomemotive\Rewardswp\Notifications\Emails\WelcomeMemberPointsEmail; // Temporarily disabled
use Awesomemotive\Rewardswp\Services\EmailsService;
use Exception;
use function Awesomemotive\Rewardswp\Helpers\rewardswp_log_error;

/**
 * Seed Default Emails Upgrade
 *
 * Creates default email templates for the RewardsWP email management system.
 *
 * @since 1.0.0
 */
/**
 * Class SeedDefaultEmailsUpgrade.
 */
class SeedDefaultEmailsUpgrade extends AbstractDatabaseUpgrade {
	/**
	 * The version this upgrade targets.
	 *
	 * @since 1.0.0
	 * @var string
	 */
	protected string $version = '1.1.0';

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

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

	/**
	 * Run the upgrade.
	 *
	 * Seeds default email templates in the database.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function up(): void {
		$default_emails = $this->get_default_emails();

		foreach ( $default_emails as $email_data ) {
			try {
				// Check if email already exists.
				if ( ! $this->emails_service->email_exists( $email_data['name'] ) ) {
					$this->emails_service->create_email( $email_data );
				}
			} catch ( Exception $e ) {
				// Log error but continue with other emails.
				rewardswp_log_error(
					'Failed to create default email {email_name}: {message}',
					[
						'email_name' => $email_data['name'] ?? '',
						'message'    => $e->getMessage(),
					]
				);
			}
		}
	}

	/**
	 * Get default email templates data from existing email classes.
	 *
	 * @since 1.1.0
	 *
	 * @return array Array of default email data.
	 */
	private function get_default_emails(): array {
		$email_classes = [
			FriendRewardEmail::class,
			AdvocateRewardEmail::class,
			PointsEarnedEmail::class,
			PointsExpirationEmail::class,
			RewardRedemptionEmail::class,
			// WelcomeMemberPointsEmail::class, // Temporarily disabled
		];

		return $this->emails_service->extract_multiple_email_data( $email_classes );
	}
}
