<?php
/**
 * Email notifications: notify the site owner, confirm to the prospect.
 *
 * @package Briefify
 */

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

/**
 * Class Briefify_Email
 */
class Briefify_Email {

	/**
	 * Send the structured brief notification to the site owner.
	 *
	 * @param int   $post_id Submission post ID.
	 * @param array $data    Sanitized field data.
	 * @param array $config  Template configuration (for labels).
	 */
	public function send_notification( $post_id, $data, $config ) {
		$settings = get_option( 'briefify_settings', array() );
		$to       = ! empty( $settings['notification_email'] ) ? $settings['notification_email'] : get_option( 'admin_email' );
		$to       = apply_filters( 'briefify_notification_email', $to, $post_id, $data );

		/* translators: %s: project type or generic "brief" label. */
		$subject = sprintf( __( '[NR Brief Builder] New brief submission — %s', 'nr-brief-builder' ), ! empty( $data['project_type'] ) ? $data['project_type'] : __( 'Brief', 'nr-brief-builder' ) );

		$body = $this->render_template(
			'notification',
			array(
				'post_id' => $post_id,
				'data'    => $data,
				'config'  => $config,
			)
		);

		$this->send( $to, $subject, $body, $data['name'], $data['email'] );
	}

	/**
	 * Send the automatic confirmation email to the prospect.
	 *
	 * @param array $data   Sanitized field data.
	 * @param array $config Template configuration.
	 */
	public function send_confirmation( $data, $config ) {
		if ( empty( $data['email'] ) || ! is_email( $data['email'] ) ) {
			return;
		}

		$settings = get_option( 'briefify_settings', array() );

		// Defaults to enabled: existing installs that predate this setting
		// (option not yet migrated) keep sending, matching prior behavior.
		$enabled = ! isset( $settings['send_confirmation'] ) || (bool) $settings['send_confirmation'];
		$enabled = apply_filters( 'briefify_send_confirmation_email', $enabled, $data, $config );

		if ( ! $enabled ) {
			return;
		}

		$subject = ! empty( $settings['confirmation_subject'] )
			? $settings['confirmation_subject']
			: __( 'Your brief has been received', 'nr-brief-builder' );

		$body = $this->render_template(
			'confirmation',
			array(
				'data'   => $data,
				'config' => $config,
			)
		);

		$this->send( $data['email'], $subject, $body );
	}

	/**
	 * Send a simple branded test email to verify delivery/formatting.
	 *
	 * @param string $to Recipient address.
	 * @return bool True if wp_mail() reported success.
	 */
	public function send_test( $to ) {
		if ( ! is_email( $to ) ) {
			return false;
		}

		$subject = __( '[NR Brief Builder] Test email', 'nr-brief-builder' );

		$body  = '<div style="font-family:-apple-system,sans-serif;max-width:480px;margin:0 auto;">';
		$body .= '<div style="background:linear-gradient(90deg,#2bd4bf,#4f7cff);padding:16px 24px;border-radius:12px 12px 0 0;">';
		$body .= '<strong style="color:#04111f;">NR Brief Builder</strong></div>';
		$body .= '<div style="background:#0a1628;padding:24px;border-radius:0 0 12px 12px;color:#f4f8ff;">';
		$body .= '<p>' . esc_html__( 'This is a test email sent from the NR Brief Builder settings.', 'nr-brief-builder' ) . '</p>';
		/* translators: %s: site name. */
		$body .= '<p>' . sprintf( esc_html__( 'If you received this, notifications for %s are working correctly.', 'nr-brief-builder' ), esc_html( get_bloginfo( 'name' ) ) ) . '</p>';
		$body .= '</div></div>';

		return (bool) $this->send( $to, $subject, $body );
	}

	/**
	 * Render an email template partial into a string.
	 *
	 * @param string $name Template file name (without extension).
	 * @param array  $vars Variables extracted into the template scope.
	 * @return string
	 */
	private function render_template( $name, $vars ) {
		$file = BRIEFIFY_PLUGIN_DIR . 'templates/emails/' . $name . '.php';

		if ( ! file_exists( $file ) ) {
			return '';
		}

		extract( $vars ); // phpcs:ignore WordPress.PHP.DontExtract -- controlled, fixed key set from within this class.

		ob_start();
		include $file;
		return ob_get_clean();
	}

	/**
	 * Send an HTML email with a temporary content-type filter and optional Reply-To.
	 *
	 * @param string $to        Recipient.
	 * @param string $subject   Subject.
	 * @param string $body      HTML body.
	 * @param string $reply_name  Optional reply-to display name.
	 * @param string $reply_email Optional reply-to email.
	 * @return bool Whether wp_mail() reported the message as sent.
	 */
	private function send( $to, $subject, $body, $reply_name = '', $reply_email = '' ) {
		$set_html = function () {
			return 'text/html';
		};

		add_filter( 'wp_mail_content_type', $set_html );

		$headers = array();
		if ( $reply_email && is_email( $reply_email ) ) {
			$headers[] = sprintf( 'Reply-To: %s <%s>', $reply_name, $reply_email );
		}

		$sent = wp_mail( $to, $subject, $body, $headers );

		remove_filter( 'wp_mail_content_type', $set_html );

		return $sent;
	}
}
