<?php

namespace VendorTasksDokanClickUp\Notifications;

use VendorTasksDokanClickUp\Settings\PluginSettings;

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

/**
 * Email Notifier
 *
 * Sends an admin email when ClickUp task creation permanently fails after all
 * retry attempts. Hooks into vendor_tasks_dokan_clickup_task_failed fired by
 * RetryScheduler once the retry queue is exhausted.
 *
 * @since 1.5.0
 * @package VendorTasksDokanClickUp
 * @subpackage Notifications
 */
class EmailNotifier {

	/**
	 * Class constructor
	 */
	public function __construct() {
		add_action( 'vendor_tasks_dokan_clickup_task_failed', array( $this, 'send_failure_notice' ), 10, 2 );
	}

	/**
	 * Send failure notification to site admin.
	 *
	 * Uses the configured failure_notify_email setting when set; falls back to
	 * the WordPress admin email. Fires only after all retry attempts are exhausted.
	 *
	 * @since 1.5.0
	 *
	 * @param int $vendor_id Vendor user ID.
	 * @param int $attempts  Number of attempts made.
	 */
	public function send_failure_notice( int $vendor_id, int $attempts ): void {
		$vendor = get_userdata( $vendor_id );
		if ( ! $vendor ) {
			return;
		}

		$ps          = new PluginSettings();
		$configured  = sanitize_email( $ps->get_failure_notify_email() );
		$admin_email = ( $configured && is_email( $configured ) ) ? $configured : get_option( 'admin_email' );
		$site_name   = get_bloginfo( 'name' );
		$edit_url    = admin_url( 'user-edit.php?user_id=' . $vendor_id );

		/* translators: %s: site name */
		$subject = sprintf( __( '[%s] ClickUp task creation failed for vendor', 'alamin-vendor-tasks-dokan-clickup' ), $site_name );

		/* translators: 1: vendor name, 2: vendor email, 3: attempt count, 4: edit URL */
		$message = sprintf(
			__(
				"ClickUp task creation has permanently failed for the following vendor after %3\$d retry attempts:\n\nVendor: %1\$s\nEmail:  %2\$s\nEdit:   %4\$s\n\nPlease check WooCommerce logs and create the task manually if needed.\n\nWooCommerce > Status > Logs > alamin-vendor-tasks-dokan-clickup",
				'alamin-vendor-tasks-dokan-clickup'
			),
			$vendor->display_name,
			$vendor->user_email,
			$attempts,
			$edit_url
		);

		wp_mail( $admin_email, $subject, $message );

		vendor_tasks_dokan_clickup()->log(
			sprintf(
				'Failure notification sent for vendor ID %d (%s) after %d attempts.',
				$vendor_id,
				$vendor->user_email,
				$attempts
			),
			'warning'
		);
	}
}
