<?php
/**
 * 247ChatMate — Pro Lead Response Suggestions
 *
 * LEADRESPONSESUGGESTIONS4S
 * - Local JSON/map-driven suggested replies for Pro lead emails.
 * - Uses stable intent keys where available, not only edited chip labels.
 * - No remote calls, no AI calls, no database writes, no entitlement authority.
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_get_default_map' ) ) {
	function matewa_pro_lead_response_suggestions_get_default_map() {
		return array(
			'generic' => array(
				'fallback' => array(
					'subject_hint' => 'Lead follow-up',
					'reply'        => 'Hi {lead_first_name}, thanks for getting in touch. Could you send a little more detail about what you need, your location, and when you would ideally like help?',
				),
			),
			'intents'    => array(),
			'synonyms'   => array(),
			'categories' => array(),
			'verticals'  => array(),
		);
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_get_map' ) ) {
	function matewa_pro_lead_response_suggestions_get_map() {
		static $map = null;

		if ( is_array( $map ) ) {
			return $map;
		}

		$map  = matewa_pro_lead_response_suggestions_get_default_map();
		$file = defined( 'MATEWA_PLUGIN_DIR' ) ? MATEWA_PLUGIN_DIR . 'data/pro-lead-response-suggestions.json' : '';

		if ( '' === $file || ! is_readable( $file ) ) {
			return $map;
		}

		$raw = file_get_contents( $file );
		if ( ! is_string( $raw ) || '' === trim( $raw ) ) {
			return $map;
		}

		$decoded = json_decode( $raw, true );
		if ( ! is_array( $decoded ) ) {
			return $map;
		}

		$map = array_replace_recursive( $map, $decoded );

		return $map;
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_normalise_intent_key' ) ) {
	function matewa_pro_lead_response_suggestions_normalise_intent_key( $value ) {
		$value = is_string( $value ) || is_numeric( $value ) ? strtolower( trim( (string) $value ) ) : '';
		$value = preg_replace( '/[^a-z0-9_.-]+/', '', $value );

		if ( '' === $value ) {
			return '';
		}

		if ( 0 !== strpos( $value, 'intent.' ) ) {
			$value = 'intent.' . ltrim( $value, '.' );
		}

		return $value;
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_get_intent_keys' ) ) {
	function matewa_pro_lead_response_suggestions_get_intent_keys( $lead ) {
		$lead = is_array( $lead ) ? $lead : array();
		$raw  = isset( $lead['intent_keys'] ) ? (string) $lead['intent_keys'] : '';
		$keys = array();

		foreach ( preg_split( '/[,|\s]+/', $raw ) as $candidate ) {
			$key = matewa_pro_lead_response_suggestions_normalise_intent_key( $candidate );
			if ( '' !== $key && ! in_array( $key, $keys, true ) ) {
				$keys[] = $key;
			}
		}

		if ( empty( $keys ) && ! empty( $lead['intent_label'] ) ) {
			$label_key = matewa_pro_lead_response_suggestions_label_to_intent_key( (string) $lead['intent_label'] );
			if ( '' !== $label_key ) {
				$keys[] = $label_key;
			}
		}

		if ( empty( $keys ) ) {
			$keys[] = 'intent.other';
		}

		$non_other = array_values(
			array_filter(
				$keys,
				static function( $key ) {
					return 'intent.other' !== $key;
				}
			)
		);

		return ! empty( $non_other ) ? $non_other : $keys;
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_label_to_intent_key' ) ) {
	function matewa_pro_lead_response_suggestions_label_to_intent_key( $label ) {
		$label = strtolower( trim( wp_strip_all_tags( (string) $label ) ) );
		$label = preg_replace( '/\s+/', ' ', $label );

		if ( '' === $label ) {
			return '';
		}

		$label = str_replace( array( 'get a quote', 'quote request', 'need a price', 'price please' ), 'quote', $label );

		$direct = array(
			'quote'        => 'intent.quote',
			'pricing'      => 'intent.pricing',
			'price'        => 'intent.pricing',
			'availability' => 'intent.availability',
			'book a job'   => 'intent.book_job',
			'booking'      => 'intent.book_job',
			'ask a question' => 'intent.ask_question',
			'question'     => 'intent.ask_question',
			'something else' => 'intent.other',
		);

		foreach ( $direct as $needle => $intent_key ) {
			if ( false !== strpos( $label, $needle ) ) {
				return $intent_key;
			}
		}

		return '';
	}
}


if ( ! function_exists( 'matewa_pro_lead_response_suggestions_normalise_phrase' ) ) {
	function matewa_pro_lead_response_suggestions_normalise_phrase( $value ) {
		$value = is_string( $value ) || is_numeric( $value ) ? (string) $value : '';
		$value = wp_strip_all_tags( $value );
		$value = html_entity_decode( $value, ENT_QUOTES, 'UTF-8' );
		$value = function_exists( 'remove_accents' ) ? remove_accents( $value ) : $value;
		$value = strtolower( $value );
		$value = preg_replace( '/[^a-z0-9]+/', ' ', $value );
		$value = is_string( $value ) ? preg_replace( '/\s+/', ' ', $value ) : '';
		$value = is_string( $value ) ? trim( $value ) : '';

		return $value;
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_get_synonym_keys' ) ) {
	function matewa_pro_lead_response_suggestions_get_synonym_keys( $lead, $map ) {
		$lead     = is_array( $lead ) ? $lead : array();
		$map      = is_array( $map ) ? $map : array();
		$synonyms = isset( $map['synonyms'] ) && is_array( $map['synonyms'] ) ? $map['synonyms'] : array();
		$label    = matewa_pro_lead_response_suggestions_normalise_phrase( $lead['intent_label'] ?? '' );
		$matches  = array();

		if ( '' === $label || empty( $synonyms ) ) {
			return $matches;
		}

		$label_padded = ' ' . $label . ' ';

		foreach ( $synonyms as $synonym_key => $phrases ) {
			$synonym_key = sanitize_key( (string) $synonym_key );
			$phrases     = is_array( $phrases ) ? $phrases : array();

			if ( '' === $synonym_key || empty( $phrases ) ) {
				continue;
			}

			foreach ( $phrases as $phrase ) {
				$needle = matewa_pro_lead_response_suggestions_normalise_phrase( $phrase );

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

				if ( $label === $needle || false !== strpos( $label_padded, ' ' . $needle . ' ' ) ) {
					if ( ! in_array( $synonym_key, $matches, true ) ) {
						$matches[] = $synonym_key;
					}
					break;
				}
			}
		}

		return $matches;
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_get_vertical_key' ) ) {
	function matewa_pro_lead_response_suggestions_get_vertical_key() {
		$key = get_option( 'matewa_vertical_selected', '' );
		$key = is_string( $key ) ? sanitize_key( $key ) : '';

		if ( '' !== $key ) {
			return $key;
		}

		if ( function_exists( 'matewa_get_active_vertical_key' ) ) {
			$key = matewa_get_active_vertical_key();
			$key = is_string( $key ) ? sanitize_key( $key ) : '';

			if ( '' !== $key ) {
				return $key;
			}
		}

		return 'general';
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_get_category_key' ) ) {
	function matewa_pro_lead_response_suggestions_get_category_key( $vertical_key, $map = array() ) {
		$vertical_key = sanitize_key( (string) $vertical_key );
		$map          = is_array( $map ) ? $map : array();

		if ( '' === $vertical_key ) {
			return 'general';
		}

		if ( isset( $map['vertical_categories'][ $vertical_key ] ) ) {
			$mapped = sanitize_key( (string) $map['vertical_categories'][ $vertical_key ] );
			if ( '' !== $mapped ) {
				return $mapped;
			}
		}

		if ( function_exists( 'matewa_get_verticals' ) ) {
			$data       = matewa_get_verticals();
			$categories = isset( $data['categories'] ) && is_array( $data['categories'] ) ? $data['categories'] : array();

			foreach ( $categories as $category_key => $category ) {
				$category_key = sanitize_key( (string) $category_key );
				$verticals    = isset( $category['verticals'] ) && is_array( $category['verticals'] ) ? $category['verticals'] : array();

				if ( in_array( $vertical_key, $verticals, true ) ) {
					return '' !== $category_key ? $category_key : 'general';
				}
			}
		}

		return 'general';
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_pick_reply' ) ) {
	function matewa_pro_lead_response_suggestions_pick_reply( $map, $vertical_key, $category_key, $intent_keys, $synonym_keys = array() ) {
		$map          = is_array( $map ) ? $map : array();
		$intent_keys  = is_array( $intent_keys ) ? $intent_keys : array();
		$synonym_keys = is_array( $synonym_keys ) ? $synonym_keys : array();

		foreach ( $intent_keys as $intent_key ) {
			if ( isset( $map['verticals'][ $vertical_key ][ $intent_key ]['reply'] ) ) {
				return $map['verticals'][ $vertical_key ][ $intent_key ];
			}
		}

		foreach ( $synonym_keys as $synonym_key ) {
			$reply_key = 'synonym.' . sanitize_key( (string) $synonym_key );
			if ( isset( $map['verticals'][ $vertical_key ][ $reply_key ]['reply'] ) ) {
				return $map['verticals'][ $vertical_key ][ $reply_key ];
			}
		}

		if ( isset( $map['verticals'][ $vertical_key ]['fallback']['reply'] ) ) {
			return $map['verticals'][ $vertical_key ]['fallback'];
		}

		foreach ( $intent_keys as $intent_key ) {
			if ( isset( $map['categories'][ $category_key ][ $intent_key ]['reply'] ) ) {
				return $map['categories'][ $category_key ][ $intent_key ];
			}
		}

		foreach ( $synonym_keys as $synonym_key ) {
			$reply_key = 'synonym.' . sanitize_key( (string) $synonym_key );
			if ( isset( $map['categories'][ $category_key ][ $reply_key ]['reply'] ) ) {
				return $map['categories'][ $category_key ][ $reply_key ];
			}
		}

		if ( isset( $map['categories'][ $category_key ]['fallback']['reply'] ) ) {
			return $map['categories'][ $category_key ]['fallback'];
		}

		foreach ( $intent_keys as $intent_key ) {
			if ( isset( $map['intents'][ $intent_key ]['reply'] ) ) {
				return $map['intents'][ $intent_key ];
			}
		}

		foreach ( $synonym_keys as $synonym_key ) {
			$reply_key = 'synonym.' . sanitize_key( (string) $synonym_key );
			if ( isset( $map['generic'][ $reply_key ]['reply'] ) ) {
				return $map['generic'][ $reply_key ];
			}
		}

		if ( isset( $map['generic']['fallback']['reply'] ) ) {
			return $map['generic']['fallback'];
		}

		$default = matewa_pro_lead_response_suggestions_get_default_map();
		return $default['generic']['fallback'];
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_apply_placeholders' ) ) {
	function matewa_pro_lead_response_suggestions_apply_placeholders( $template, $lead, $business_name ) {
		$lead          = is_array( $lead ) ? $lead : array();
		$first_name    = function_exists( 'matewa_pro_lead_routing_get_first_name' ) ? matewa_pro_lead_routing_get_first_name( $lead['name'] ?? '' ) : '';
		$first_name    = '' !== $first_name ? $first_name : 'there';
		$vertical_key  = matewa_pro_lead_response_suggestions_get_vertical_key();
		$vertical_label = function_exists( 'matewa_pro_lead_routing_get_vertical_label' ) ? matewa_pro_lead_routing_get_vertical_label() : '';

		$replacements = array(
			'{lead_first_name}' => $first_name,
			'{lead_name}'       => '' !== trim( (string) ( $lead['name'] ?? '' ) ) ? trim( (string) $lead['name'] ) : $first_name,
			'{business_name}'   => '' !== trim( (string) $business_name ) ? trim( (string) $business_name ) : 'the business',
			'{vertical_label}'  => '' !== trim( (string) $vertical_label ) ? trim( (string) $vertical_label ) : 'this service',
			'{chip_label}'      => '' !== trim( (string) ( $lead['intent_label'] ?? '' ) ) ? trim( (string) $lead['intent_label'] ) : 'your enquiry',
		);

		$message = strtr( (string) $template, $replacements );
		$message = preg_replace( '/\s+/', ' ', $message );
		$message = trim( $message );

		if ( function_exists( 'matewa_pro_lead_routing_limit_textarea' ) ) {
			$message = matewa_pro_lead_routing_limit_textarea( $message, 700 );
		}

		return '' !== $message ? $message : 'Hi ' . $first_name . ', thanks for getting in touch. Could you send a little more detail about what you need, your location, and when you would ideally like help?';
	}
}

if ( ! function_exists( 'matewa_pro_lead_response_suggestions_resolve' ) ) {
	function matewa_pro_lead_response_suggestions_resolve( $lead, $business_name = '' ) {
		$lead         = is_array( $lead ) ? $lead : array();
		$map          = matewa_pro_lead_response_suggestions_get_map();
		$vertical_key = matewa_pro_lead_response_suggestions_get_vertical_key();
		$category_key = matewa_pro_lead_response_suggestions_get_category_key( $vertical_key, $map );
		$intent_keys  = matewa_pro_lead_response_suggestions_get_intent_keys( $lead );
		$synonym_keys = matewa_pro_lead_response_suggestions_get_synonym_keys( $lead, $map );
		$reply_config = matewa_pro_lead_response_suggestions_pick_reply( $map, $vertical_key, $category_key, $intent_keys, $synonym_keys );
		$template     = isset( $reply_config['reply'] ) ? (string) $reply_config['reply'] : '';

		return matewa_pro_lead_response_suggestions_apply_placeholders( $template, $lead, $business_name );
	}
}
