<?php
/**
 * Отправка e-mail-уведомлений о смене цен (core).
 *
 * @package E2W_Price_Change_Alerts
 */

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

/**
 * Class E2W_Price_Change_Alerts_Mailer
 */
class E2W_Price_Change_Alerts_Mailer {

	/**
	 * Регистрация хуков.
	 */
	public function __construct() {
		add_action( 'e2w_price_change_alerts_send_batch', array( $this, 'send' ) );
	}

	/**
	 * Отправить сводное письмо по пачке изменений.
	 *
	 * @param array $changes Список изменений (product_id, price_type, old, new).
	 */
	public function send( $changes ) {
		$rows = array();

		foreach ( $changes as $change ) {
			$row = $this->prepare_row( $change );

			if ( null !== $row ) {
				$rows[] = $row;
			}
		}

		if ( empty( $rows ) ) {
			return;
		}

		$recipients = $this->get_recipients();

		if ( empty( $recipients ) ) {
			return;
		}

		$count = count( $rows );

		if ( 1 === $count ) {
			$subject = sprintf(
				/* translators: 1: site name, 2: product name. */
				__( '[%1$s] Price changed: %2$s', 'e2w-price-change-alerts' ),
				wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ),
				$rows[0]['name']
			);
		} else {
			$subject = sprintf(
				/* translators: 1: site name, 2: number of changed prices. */
				_n( '[%1$s] Prices changed: %2$d update', '[%1$s] Prices changed: %2$d updates', $count, 'e2w-price-change-alerts' ),
				wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ),
				$count
			);
		}

		if ( array_filter( wp_list_pluck( $rows, 'suspicious' ) ) ) {
			$subject .= ' ' . __( '(suspicious changes!)', 'e2w-price-change-alerts' );
		}

		$sent = wp_mail(
			$recipients,
			$subject,
			$this->render_body( $rows ),
			array( 'Content-Type: text/html; charset=UTF-8' )
		);

		if ( ! $sent && function_exists( 'wc_get_logger' ) ) {
			wc_get_logger()->error(
				sprintf( 'Failed to send price change notification (%d changes).', $count ),
				array( 'source' => 'e2w-price-change-alerts' )
			);
		}
	}

	/**
	 * Подготовить данные строки письма по одному изменению.
	 *
	 * @param array $change Изменение.
	 * @return array|null Null, если товар уже не существует.
	 */
	private function prepare_row( $change ) {
		$product = wc_get_product( $change['product_id'] );

		if ( ! $product ) {
			return null;
		}

		$edit_id = $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id();

		return array(
			'name'       => $product->get_name(),
			'suspicious' => ! empty( $change['suspicious'] ),
			'note'       => isset( $change['suspicious_note'] ) ? (string) $change['suspicious_note'] : '',
			'permalink'  => $product->get_permalink(),
			'edit_link'  => admin_url( 'post.php?post=' . $edit_id . '&action=edit' ),
			'price_type' => 'regular' === $change['price_type']
				? __( 'Regular price', 'e2w-price-change-alerts' )
				: __( 'Sale price', 'e2w-price-change-alerts' ),
			'old'        => $this->format_price( $change['old'] ),
			'new'        => $this->format_price( $change['new'] ),
		);
	}

	/**
	 * Отформатировать цену для письма.
	 *
	 * @param string $value Сырое значение меты.
	 * @return string HTML.
	 */
	private function format_price( $value ) {
		if ( '' === $value || ! is_numeric( $value ) ) {
			return esc_html__( 'not set', 'e2w-price-change-alerts' );
		}

		return wc_price( (float) $value );
	}

	/**
	 * Список получателей: опция → фолбэк admin_email.
	 *
	 * @return string[]
	 */
	private function get_recipients() {
		$settings = get_option( 'e2w_price_change_alerts_settings', array() );
		$emails   = array();

		if ( is_array( $settings ) && isset( $settings['recipients'] ) && is_array( $settings['recipients'] ) ) {
			$emails = array_values( array_filter( array_map( 'sanitize_email', $settings['recipients'] ), 'is_email' ) );
		}

		if ( empty( $emails ) ) {
			$admin_email = get_option( 'admin_email' );
			$emails      = is_email( $admin_email ) ? array( $admin_email ) : array();
		}

		return $emails;
	}

	/**
	 * Собрать HTML-тело письма.
	 *
	 * @param array $rows Подготовленные строки.
	 * @return string
	 */
	private function render_body( $rows ) {
		$intro = 1 === count( $rows )
			? esc_html__( 'A product price has changed on your store:', 'e2w-price-change-alerts' )
			: sprintf(
				/* translators: %d: number of changed prices. */
				esc_html( _n( '%d product price has changed on your store:', '%d product prices have changed on your store:', count( $rows ), 'e2w-price-change-alerts' ) ),
				count( $rows )
			);

		$has_suspicious = (bool) array_filter( wp_list_pluck( $rows, 'suspicious' ) );

		$cell  = 'padding:8px 12px;border:1px solid #ddd;text-align:left;';
		$table = '<table style="border-collapse:collapse;font-family:Arial,sans-serif;font-size:14px;">';

		$table .= '<tr>'
			. '<th style="' . $cell . '">' . esc_html__( 'Product', 'e2w-price-change-alerts' ) . '</th>'
			. '<th style="' . $cell . '">' . esc_html__( 'Price type', 'e2w-price-change-alerts' ) . '</th>'
			. '<th style="' . $cell . '">' . esc_html__( 'Old price', 'e2w-price-change-alerts' ) . '</th>'
			. '<th style="' . $cell . '">' . esc_html__( 'New price', 'e2w-price-change-alerts' ) . '</th>'
			. ( $has_suspicious ? '<th style="' . $cell . '">' . esc_html__( 'Note', 'e2w-price-change-alerts' ) . '</th>' : '' )
			. '<th style="' . $cell . '">' . esc_html__( 'Links', 'e2w-price-change-alerts' ) . '</th>'
			. '</tr>';

		foreach ( $rows as $row ) {
			$links = sprintf(
				'<a href="%1$s">%2$s</a> | <a href="%3$s">%4$s</a>',
				esc_url( $row['permalink'] ),
				esc_html__( 'View', 'e2w-price-change-alerts' ),
				esc_url( $row['edit_link'] ),
				esc_html__( 'Edit', 'e2w-price-change-alerts' )
			);

			$row_style = $row['suspicious'] ? 'background:#fff3e0;' : '';
			$note_cell = '';

			if ( $has_suspicious ) {
				$note      = $row['suspicious'] ? '&#9888; ' . esc_html( $row['note'] ) : '';
				$note_cell = '<td style="' . $cell . '">' . $note . '</td>';
			}

			$table .= '<tr style="' . $row_style . '">'
				. '<td style="' . $cell . '">' . esc_html( $row['name'] ) . '</td>'
				. '<td style="' . $cell . '">' . esc_html( $row['price_type'] ) . '</td>'
				. '<td style="' . $cell . '">' . wp_kses_post( $row['old'] ) . '</td>'
				. '<td style="' . $cell . '">' . wp_kses_post( $row['new'] ) . '</td>'
				. $note_cell
				. '<td style="' . $cell . '">' . $links . '</td>'
				. '</tr>';
		}

		$table .= '</table>';

		return '<p style="font-family:Arial,sans-serif;font-size:14px;">' . $intro . '</p>' . $table;
	}
}
