<?php
/**
 * WooCommerce email for a permanent StoreSheet sync failure.
 *
 * Registered through the `woocommerce_email_classes` filter so it appears under
 * WooCommerce → Settings → Emails with the usual enable/subject/heading/type
 * controls and a branded HTML template. It sends itself off the
 * `storesheet_sync_failed` hook that FailureNotifier fires, so all failure
 * email now goes through WooCommerce's mailer instead of a raw wp_mail().
 *
 * Free build: recipient is fixed to the store admin (no recipient form field).
 * The Pro build adds a recipient field so a custom address can be used.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Emails;

defined( 'ABSPATH' ) || exit;

if ( ! class_exists( '\WC_Email' ) ) {
	return;
}

class SyncFailureEmail extends \WC_Email {

	private string $failed_resource = '';
	private int $failed_resource_id = 0;
	private string $failed_error    = '';

	public function __construct() {
		$this->id             = 'storesheet_sync_failure';
		$this->title          = __( 'StoreSheet: sync failure', 'storesheet' );
		$this->description    = __( 'Sent when a StoreSheet sync job to Google Sheets fails permanently.', 'storesheet' );
		$this->customer_email = false;
		$this->template_html  = 'emails/storesheet-sync-failure.php';
		$this->template_plain = 'emails/plain/storesheet-sync-failure.php';
		$this->template_base  = STORESHEET_DIR . 'templates/';

		// Send this email whenever a sync job fails for good.
		add_action( 'storesheet_sync_failed', array( $this, 'trigger_failed' ), 10, 3 );

		parent::__construct();

		// Free: fixed to the admin. Pro adds a 'recipient' field that lands here.
		// Fall back to the admin whenever no recipient is set (field absent in
		// free, or present but left blank in Pro).
		$recipient       = trim( (string) $this->get_option( 'recipient', '' ) );
		$this->recipient = '' !== $recipient ? $recipient : (string) get_option( 'admin_email' );
	}

	public function get_default_subject(): string {
		return __( '[{site_title}] StoreSheet sync failed: {resource} #{resource_id}', 'storesheet' );
	}

	public function get_default_heading(): string {
		return __( 'A StoreSheet sync job failed', 'storesheet' );
	}

	/**
	 * Handle the storesheet_sync_failed hook and send the email.
	 *
	 * @param string $resource    Resource slug (product|order|coupon|…).
	 * @param int    $resource_id The failed job's target ID.
	 * @param string $error       Failure message.
	 */
	public function trigger_failed( string $resource, int $resource_id, string $error ): void {
		$this->setup_locale();

		$this->failed_resource    = $resource;
		$this->failed_resource_id = $resource_id;
		$this->failed_error       = $error;

		$this->placeholders['{resource}']    = '' !== $resource ? $resource : __( 'item', 'storesheet' );
		$this->placeholders['{resource_id}'] = (string) $resource_id;

		if ( $this->is_enabled() && $this->get_recipient() ) {
			$this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
		}

		$this->restore_locale();
	}

	public function get_content_html(): string {
		return wc_get_template_html(
			$this->template_html,
			$this->template_args( false ),
			'',
			$this->template_base
		);
	}

	public function get_content_plain(): string {
		return wc_get_template_html(
			$this->template_plain,
			$this->template_args( true ),
			'',
			$this->template_base
		);
	}

	/**
	 * @param bool $plain_text
	 * @return array<string, mixed>
	 */
	private function template_args( bool $plain_text ): array {
		return array(
			'resource'      => $this->failed_resource,
			'resource_id'   => $this->failed_resource_id,
			'error'         => $this->failed_error,
			'email_heading' => $this->get_heading(),
			'sent_to_admin' => true,
			'plain_text'    => $plain_text,
			'email'         => $this,
		);
	}

	public function init_form_fields(): void {
		$this->form_fields = array(
			'enabled'    => array(
				'title'   => __( 'Enable/Disable', 'storesheet' ),
				'type'    => 'checkbox',
				'label'   => __( 'Enable this email notification', 'storesheet' ),
				'default' => 'yes',
			),
			'subject'    => array(
				'title'       => __( 'Subject', 'storesheet' ),
				'type'        => 'text',
				'desc_tip'    => true,
				/* translators: %s: list of available placeholders */
				'description' => sprintf( __( 'Available placeholders: %s', 'storesheet' ), '<code>{site_title}, {resource}, {resource_id}</code>' ),
				'placeholder' => $this->get_default_subject(),
				'default'     => '',
			),
			'heading'    => array(
				'title'       => __( 'Email heading', 'storesheet' ),
				'type'        => 'text',
				'desc_tip'    => true,
				'placeholder' => $this->get_default_heading(),
				'default'     => '',
			),
			'email_type' => array(
				'title'       => __( 'Email type', 'storesheet' ),
				'type'        => 'select',
				'description' => __( 'Choose which format of email to send.', 'storesheet' ),
				'default'     => 'html',
				'class'       => 'email_type wc-enhanced-select',
				'options'     => $this->get_email_type_options(),
				'desc_tip'    => true,
			),
		);
	}
}
