<?php
/**
 * Email notifications for [post_cf_form] frontend submissions.
 *
 * @package Admin and Site Enhancements
 */

defined( 'ABSPATH' ) || exit;

/**
 * Build and send HTML notification emails when notify= is set on the shortcode.
 */
class CFGroup_Form_Notification {

	/**
	 * Parse notify string into a deduplicated list of recipient emails (order preserved).
	 *
	 * @param string $notify_string Comma-separated emails and/or WP usernames.
	 * @return string[] Email addresses.
	 */
	public static function parse_recipients( $notify_string ) {
		if ( ! is_string( $notify_string ) || '' === trim( $notify_string ) ) {
			return array();
		}

		$parts = explode( ',', $notify_string );
		$emails = array();
		$seen   = array();

		foreach ( $parts as $part ) {
			$token = trim( $part );
			if ( '' === $token ) {
				continue;
			}

			$email = '';

			if ( is_email( $token ) ) {
				$email = sanitize_email( $token );
			} else {
				$user = get_user_by( 'login', sanitize_user( $token, true ) );
				if ( $user && ! empty( $user->user_email ) && is_email( $user->user_email ) ) {
					$email = $user->user_email;
				}
			}

			if ( '' === $email ) {
				continue;
			}

			$key = strtolower( $email );
			if ( isset( $seen[ $key ] ) ) {
				continue;
			}
			$seen[ $key ] = true;
			$emails[]     = $email;
		}

		return $emails;
	}

	/**
	 * Best-effort URL of the page the form was submitted from.
	 *
	 * @return string
	 */
	public static function get_submitter_page_url() {
		$ref = wp_get_referer();
		if ( ! empty( $ref ) ) {
			return esc_url_raw( $ref );
		}

		if ( function_exists( 'wp_get_raw_referer' ) ) {
			$raw = wp_get_raw_referer();
			if ( ! empty( $raw ) ) {
				return esc_url_raw( $raw );
			}
		}

		if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
			return esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) );
		}

		return '';
	}

	/**
	 * Format a custom field value for HTML email.
	 *
	 * @param string $field_name Field name.
	 * @param int    $post_id    Post ID.
	 * @return string
	 */
	public static function format_field_value_for_email( $field_name, $post_id ) {
		if ( ! function_exists( 'get_cf' ) ) {
			return '';
		}

		$value = get_cf( $field_name, 'default', $post_id );

		if ( is_array( $value ) || is_object( $value ) ) {
			$encoded = wp_json_encode( $value, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
			return $encoded ? esc_html( $encoded ) : '';
		}

		if ( is_bool( $value ) ) {
			return $value ? '1' : '0';
		}

		if ( is_string( $value ) ) {
			// get_cf may return HTML (links, paragraphs). Allow safe tags in email body.
			return wp_kses_post( $value );
		}

		return esc_html( (string) $value );
	}

	/**
	 * Build HTML email body.
	 *
	 * @param int   $post_id Post ID.
	 * @param array $session Session snapshot from cfgroup_session.
	 * @param string $referrer_url Display URL for "Submitted from".
	 * @return string
	 */
	public static function build_html_body( $post_id, $session, $referrer_url ) {
		$cfg_post = get_post( $post_id );
		if ( ! $cfg_post ) {
			return '';
		}

		$prev_global_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
		$GLOBALS['post']  = $cfg_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited

		$post_type_obj = get_post_type_object( $cfg_post->post_type );
		$post_type_label = $post_type_obj && ! empty( $post_type_obj->labels->singular_name )
			? $post_type_obj->labels->singular_name
			: $cfg_post->post_type;

		$show_title   = ! empty( $session['post_title_show'] );
		$show_content = ! empty( $session['post_content_show'] );
		$excluded     = isset( $session['excluded_fields'] ) ? (array) $session['excluded_fields'] : array();
		$excluded     = array_map( 'trim', $excluded );
		$group_ids    = isset( $session['field_groups'] ) ? (array) $session['field_groups'] : array();

		$inner = '';

		if ( $show_title ) {
			$inner .= '<p><strong>' . esc_html__( 'Title', 'admin-site-enhancements' ) . '</strong><br />';
			$inner .= esc_html( $cfg_post->post_title ) . '</p>';
		}

		if ( $show_content ) {
			$inner .= '<p><strong>' . esc_html__( 'Content', 'admin-site-enhancements' ) . '</strong><br />';
			$inner .= wp_kses_post( $cfg_post->post_content ) . '</p>';
		}

		foreach ( $group_ids as $group_id ) {
			$group_id = (int) $group_id;
			if ( $group_id < 1 ) {
				continue;
			}

			$group_title = get_the_title( $group_id );
			if ( '' !== $group_title ) {
				$inner .= '<h3 style="margin:16px 0 8px;font-size:16px;">' . esc_html( $group_title ) . '</h3>';
			}

			$fields = CFG()->api->get_input_fields( array( 'group_id' => $group_id ), 'post' );
			if ( empty( $fields ) ) {
				continue;
			}

			$field_list = array_values( $fields );
			usort(
				$field_list,
				function ( $a, $b ) {
					$wa = isset( $a->weight ) ? (int) $a->weight : 0;
					$wb = isset( $b->weight ) ? (int) $b->weight : 0;
					return $wa - $wb;
				}
			);

			foreach ( $field_list as $field ) {
				if ( ! is_object( $field ) ) {
					continue;
				}

				if ( isset( $field->parent_id ) && (int) $field->parent_id > 0 ) {
					continue;
				}

				if ( in_array( $field->name, $excluded, true ) ) {
					continue;
				}

				if ( in_array( $field->type, array( 'tab', 'line_break' ), true ) ) {
					continue;
				}

				if ( 'heading' === $field->type ) {
					if ( ! empty( $field->label ) ) {
						$inner .= '<h4 style="margin:12px 0 6px;font-size:14px;">' . esc_html( $field->label ) . '</h4>';
					}
					continue;
				}

				$label = isset( $field->label ) ? $field->label : $field->name;
				$inner .= '<p><strong>' . esc_html( $label ) . '</strong><br />';
				$inner .= self::format_field_value_for_email( $field->name, $post_id );
				$inner .= '</p>';
			}
		}

		$GLOBALS['post'] = $prev_global_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited

		$container_style = 'border:1px solid #ccc;border-radius:5px;padding:16px;margin:0 0 16px;';

		$html  = '<div style="' . esc_attr( $container_style ) . '">' . $inner . '</div>';

		$edit_url = admin_url( 'post.php?post=' . absint( $post_id ) . '&action=edit' );
		/* translators: %s: singular post type label, e.g. Album */
		$edit_text = sprintf( __( 'Edit the %s submission', 'admin-site-enhancements' ), $post_type_label );
		// Inline styles approximate wp-admin .button-primary for HTML email (no external CSS).
		$edit_btn_style = 'display:inline-block;background:#2271b1;border:1px solid #2271b1;border-radius:3px;color:#fff;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;font-size:13px;font-weight:400;line-height:2.15384615;min-height:30px;margin:0;padding:0 12px;text-decoration:none;vertical-align:top;white-space:nowrap;';
		$html            .= '<p style="margin:16px 0 0;">';
		$html            .= '<a href="' . esc_url( $edit_url ) . '" style="' . esc_attr( $edit_btn_style ) . '">' . esc_html( $edit_text ) . '</a>';
		$html            .= '</p>';

		if ( '' === $referrer_url ) {
			/* translators: Used when HTTP referrer is not available */
			$referrer_display = __( 'Unknown', 'admin-site-enhancements' );
		} else {
			$referrer_display = $referrer_url;
		}

		$html .= '<p style="margin:8px 0 0 !important;font-size:12px;color:#555;margin:0;">';
		$html .= esc_html__( 'Submitted from:', 'admin-site-enhancements' ) . ' ';
		if ( '' !== $referrer_url ) {
			$html .= '<a href="' . esc_url( $referrer_url ) . '">' . esc_html( $referrer_display ) . '</a>';
		} else {
			$html .= esc_html( $referrer_display );
		}
		$html .= '</p>';

		return $html;
	}

	/**
	 * Send notification email(s).
	 *
	 * @param int   $post_id Post ID.
	 * @param array $session Session data.
	 * @param string $referrer_url Submitter page URL.
	 * @return bool Whether wp_mail reported success.
	 */
	public static function send( $post_id, $session, $referrer_url ) {
		$post_id = (int) $post_id;
		if ( $post_id < 1 || empty( $session['notify'] ) || ! is_string( $session['notify'] ) ) {
			return false;
		}

		if ( '' === trim( $session['notify'] ) ) {
			return false;
		}

		$all_recipient_emails = self::parse_recipients( $session['notify'] );
		if ( empty( $all_recipient_emails ) ) {
			return false;
		}

		$post = get_post( $post_id );
		if ( ! $post ) {
			return false;
		}

		$post_type_obj = get_post_type_object( $post->post_type );
		$post_type_label = $post_type_obj && ! empty( $post_type_obj->labels->singular_name )
			? $post_type_obj->labels->singular_name
			: $post->post_type;

		/* translators: %s: singular post type label */
		$subject = sprintf( __( 'A new %s has been submitted', 'admin-site-enhancements' ), $post_type_label ) . ' (ID: ' . $post_id . ' )';

		$body = self::build_html_body( $post_id, $session, $referrer_url );

		$to = array_shift( $all_recipient_emails );

		$headers = array( 'Content-Type: text/html; charset=UTF-8' );

		if ( ! empty( $all_recipient_emails ) ) {
			$headers[] = 'Bcc: ' . implode( ', ', $all_recipient_emails );
		}

		$mail_result = wp_mail( $to, $subject, $body, $headers ); // phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.wp_mail_wp_mail

		/**
		 * Fires after a post_cf_form notification is sent (or attempted).
		 *
		 * @since ASE (Custom Field Groups)
		 *
		 * @param int      $post_id           Post ID.
		 * @param bool     $mail_result       wp_mail return value.
		 * @param string[] $recipient_emails  All recipient email addresses (To first, then Bcc order).
		 * @param array    $session           Session snapshot.
		 */
		do_action( 'cfgroup_post_cf_form_notify_sent', $post_id, $mail_result, array_merge( array( $to ), $all_recipient_emails ), $session );

		return (bool) $mail_result;
	}
}
