<?php
/**
 * Shared recap formatting function.
 *
 * Formats AI-generated conversation recaps into structured HTML
 * with intro paragraphs, bullet-point details, and follow-up actions.
 * Used by both the admin call detail view and the public transcript viewer.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/includes
 * @since      1.2.0
 */

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

if ( ! function_exists( 'sitestaffr_format_recap_html' ) ) {
	/**
	 * Format recap HTML/text for consistent key-detail bullet rendering.
	 *
	 * If recap already contains an HTML list, it is returned as-is.
	 * If recap contains plain key-detail lines (for example: "Phone: ..."),
	 * those lines are rendered as bullet list items.
	 *
	 * @since  1.0.0
	 * @param  string $text             Raw recap text from database.
	 * @param  bool   $linkify_contacts Whether to wrap phone/email in tel:/mailto: links.
	 * @return string                   Formatted HTML.
	 */
	function sitestaffr_format_recap_html( $text, $linkify_contacts = false ) {
		$recap = trim( stripslashes( (string) $text ) );
		if ( '' === $recap ) {
			return '';
		}

		// Remove redundant leading recap heading if model included it in content.
		$recap = preg_replace(
			'/^\s*(?:<p>\s*)?(?:<strong>\s*)?conversation\s+recap\s*:?(?:\s*<\/strong>)?(?:\s*<\/p>)?\s*(?:<br\s*\/?>\s*)*/i',
			'',
			(string) $recap,
			1
		);

		// Remove leaked transcript turn lines when model starts recap with "Visitor:"/"Caller:" or "AI:".
		$recap = preg_replace(
			'/^\s*(?:<p>\s*)?(?:visitor|caller|ai)\s*:\s*[^<\r\n]+(?:\s*<\/p>)?\s*(?:<br\s*\/?>\s*)*/i',
			'',
			(string) $recap,
			1
		);
		$recap = trim( (string) $recap );
		if ( '' === $recap ) {
			return '';
		}

		// Keep structured HTML formatting when present (lists, tables, onboarding recaps),
		// but still set off the "Suggested follow-up:" line with a divider + tinted callout.
		if ( false !== stripos( $recap, '<ul' ) || false !== stripos( $recap, '<table' ) ) {
			return sitestaffr_wrap_recap_followup( $recap );
		}

		// Normalize HTML separators into line breaks before parsing key-detail lines.
		$normalized = preg_replace( '/<\s*br\s*\/?>/i', "\n", $recap );
		$normalized = preg_replace( '/<\s*\/p\s*>/i', "\n", $normalized );
		$normalized = preg_replace( '/<\s*p[^>]*>/i', '', $normalized );
		$normalized = wp_strip_all_tags( (string) $normalized );

		$lines         = preg_split( '/\r\n|\r|\n/', (string) $normalized );
		$intro_lines   = array();
		$detail_lines  = array();
		$followup_line = '';

		foreach ( (array) $lines as $line ) {
			$line = trim( (string) $line );
			if ( '' === $line ) {
				continue;
			}

			if ( 0 === stripos( $line, 'Suggested follow-up:' ) ) {
				$followup_line = trim( substr( $line, strlen( 'Suggested follow-up:' ) ) );
				continue;
			}

			if ( preg_match( '/^[A-Za-z][A-Za-z\s\/-]{1,40}:\s+.+$/', $line ) ) {
				$detail_lines[] = $line;
				continue;
			}

			$intro_lines[] = $line;
		}

		$html_parts = array();

		if ( ! empty( $intro_lines ) ) {
			$html_parts[] = '<p>' . esc_html( implode( ' ', $intro_lines ) ) . '</p>';
		}

		if ( ! empty( $detail_lines ) ) {
			$list = '<ul>';
			foreach ( $detail_lines as $detail ) {
				$detail_html = esc_html( $detail );

				if ( $linkify_contacts ) {
					// Wrap phone numbers in tel: links.
					$detail_html = preg_replace_callback(
						'/Phone:\s*([\d\-\(\)\+\s]+)/',
						function ( $m ) {
							$raw   = trim( $m[1] );
							$clean = preg_replace( '/[^\d+]/', '', $raw );
							return 'Phone: <a href="tel:' . esc_attr( $clean ) . '">' . esc_html( $raw ) . '</a>';
						},
						$detail_html
					);

					// Wrap email addresses in mailto: links.
					$detail_html = preg_replace_callback(
						'/Email:\s*([^\s<]+@[^\s<]+)/',
						function ( $m ) {
							$email = trim( $m[1] );
							return 'Email: <a href="mailto:' . esc_attr( $email ) . '">' . esc_html( $email ) . '</a>';
						},
						$detail_html
					);
				}

				$list .= '<li>' . $detail_html . '</li>';
			}
			$list .= '</ul>';
			$html_parts[] = $list;
		}

		if ( '' !== $followup_line ) {
			$html_parts[] = '<hr class="sitestaffr-recap-divider" style="border:none;border-top:1px solid #e0e0e0;margin:12px 0;" />';
			$html_parts[] = '<p class="sitestaffr-recap-followup"><strong>' . esc_html__( 'Suggested follow-up:', 'sitestaffr' ) . '</strong> ' . esc_html( $followup_line ) . '</p>';
		}

		if ( empty( $html_parts ) ) {
			return '<p>' . esc_html( $recap ) . '</p>';
		}

		return implode( '', $html_parts );
	}
}

if ( ! function_exists( 'sitestaffr_wrap_recap_followup' ) ) {
	/**
	 * Set off the "Suggested follow-up:" line in already-structured recap HTML with
	 * a divider + tinted callout (`.sitestaffr-recap-followup`), matching the
	 * plain-text recap path and the notification email. Idempotent; a no-op when the
	 * recap has no follow-up line (e.g. onboarding tables, informational recaps).
	 *
	 * @since 1.35.0
	 * @param string $html Structured recap HTML.
	 * @return string
	 */
	function sitestaffr_wrap_recap_followup( $html ) {
		$html = (string) $html;

		// Already set off (idempotent).
		if ( false !== stripos( $html, 'sitestaffr-recap-divider' ) ) {
			return $html;
		}

		// Find the follow-up label (optionally already inside a <p> wrapper).
		if ( ! preg_match( '/(?:<p[^>]*>\s*)?<strong>\s*Suggested follow-up:\s*<\/strong>/i', $html, $matches, PREG_OFFSET_CAPTURE ) ) {
			return $html;
		}

		$pos      = (int) $matches[0][1];
		$pre      = substr( $html, 0, $pos );
		$followup = substr( $html, $pos );

		// Drop an outer <p>...</p> wrapper around the follow-up so we can re-wrap it
		// in the tinted callout paragraph.
		$followup = preg_replace( '/^\s*<p[^>]*>/i', '', $followup );
		$followup = preg_replace( '/<\/p>\s*$/i', '', $followup );

		$divider = '<hr class="sitestaffr-recap-divider" style="border:none;border-top:1px solid #e0e0e0;margin:12px 0;" />';
		$wrapped = '<p class="sitestaffr-recap-followup">' . trim( (string) $followup ) . '</p>';

		return rtrim( $pre ) . $divider . $wrapped;
	}
}
