<?php
/**
 * Frontend widget output — OurNetHelps Mortgage Q&A Assistant
 *
 * @package OurNetHelps_Mortgage_QA_Assistant
 */

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

add_action( 'wp_enqueue_scripts', 'onhmqa_enqueue_frontend' );
function onhmqa_enqueue_frontend() {

	// Only load if widget is enabled
	if ( get_option( 'onhmqa_enabled', '1' ) !== '1' ) return;

	// Page exclusions check
	$exclude_raw = get_option( 'onhmqa_exclude_pages', '' );
	if ( ! empty( $exclude_raw ) ) {
		$current_path = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		$current_path = strtok( $current_path, '?' );
		$excluded     = array_filter( array_map( 'trim', explode( "\n", $exclude_raw ) ) );
		foreach ( $excluded as $path ) {
			if ( $current_path === $path ) return;
		}
	}

	// Enqueue static CSS
	wp_enqueue_style(
		'onhmqa-frontend',
		ONHMQA_PLUGIN_URL . 'assets/frontend.css',
		array(),
		ONHMQA_VERSION
	);

	// Build dynamic CSS (accent color + position — cannot go in a static file)
	$accent   = get_option( 'onhmqa_accent', '#1a56db' );
	if ( ! preg_match( '/^#[0-9a-fA-F]{3,6}$/', $accent ) ) $accent = '#1a56db';
	$position = get_option( 'onhmqa_position', 'bottom-right' );
	$pos_side = ( $position === 'bottom-left' ) ? 'left:20px' : 'right:20px';
	$pos_arrow= ( $position === 'bottom-left' ) ? 'left' : 'right';

	$inline_css = "
		#onhmqa-btn{{$pos_side};background:{$accent};}
		#onhmqa-urgency{{$pos_side};background:{$accent};}
		#onhmqa-popup{{$pos_side};}
		#onhmqa-popup::after{{$pos_arrow}:18px;}
		#onhmqa-box{{$pos_side};}
		#onhmqa-head{background:linear-gradient(135deg,{$accent} 0%,{$accent}dd 100%);}
		.onhmqa-usr{background:{$accent};color:#fff;border-bottom-right-radius:5px;align-self:flex-end;box-shadow:0 2px 8px rgba(0,0,0,.2);}
		.onhmqa-chip{border:1.5px solid {$accent}66;}
		.onhmqa-chip:hover{background:{$accent};color:#fff;border-color:{$accent};box-shadow:0 2px 8px rgba(0,0,0,.15);}
		#onhmqa-inp:focus{border-color:{$accent};background:#fff;box-shadow:0 0 0 3px {$accent}18;}
		#onhmqa-snd{background:{$accent};color:#fff;}
	";
	wp_add_inline_style( 'onhmqa-frontend', $inline_css );

	// Build Q&A JS data from saved pairs
	$qa_json  = get_option( 'onhmqa_qa_pairs', '' );
	$qa_pairs = ( ! empty( $qa_json ) ) ? json_decode( $qa_json, true ) : array();
	if ( ! is_array( $qa_pairs ) ) $qa_pairs = array();

	$qa_js = array();
	foreach ( $qa_pairs as $pair ) {
		if ( empty( $pair['question'] ) || empty( $pair['answer'] ) ) continue;
		if ( ! empty( $pair['keywords'] ) ) {
			$kws = array_values( array_filter( array_map( 'trim', explode( ',', $pair['keywords'] ) ) ) );
		} else {
			$kws = array_values( array_filter(
				array_map( 'trim', explode( ' ', strtolower( $pair['question'] ) ) ),
				function( $w ) { return strlen( $w ) > 3; }
			) );
		}
		$qa_js[] = array(
			'k' => $kws,
			'q' => $pair['question'],
			'a' => $pair['answer'],
		);
	}

	$agent_email   = get_option( 'onhmqa_agent_email', '' );
	$agent_phone   = get_option( 'onhmqa_agent_phone', '' );
	$contact_url   = get_option( 'onhmqa_contact_url', '' );
	$popup_enabled = ( get_option( 'onhmqa_popup_enabled', '1' ) === '1' );
	$popup_delay   = max( 1, (int) get_option( 'onhmqa_popup_delay', 6 ) );
	$welcome       = get_option( 'onhmqa_welcome', 'Hi! Ask me anything about mortgages. Tap a question below or type your own.' );
	$fallback      = get_option( 'onhmqa_fallback_msg', 'Great question. Please call me directly or use the contact form and I will get back to you as soon as possible.' );

	// Enqueue frontend JS
	wp_enqueue_script(
		'onhmqa-frontend',
		ONHMQA_PLUGIN_URL . 'assets/frontend.js',
		array(),
		ONHMQA_VERSION,
		true  // load in footer
	);

	// Pass PHP data to JS via wp_localize_script
	wp_localize_script( 'onhmqa-frontend', 'onhmqaData', array(
		'qa'         => $qa_js,
		'welcome'    => $welcome,
		'fallback'   => $fallback,
		'email'      => $agent_email,
		'phone'      => $agent_phone,
		'contactUrl' => $contact_url,
		'popupOn'    => $popup_enabled,
		'popupDelay' => $popup_delay,
	) );
}

add_action( 'wp_footer', 'onhmqa_render_widget', 99 );
function onhmqa_render_widget() {

	if ( get_option( 'onhmqa_enabled', '1' ) !== '1' ) return;

	$exclude_raw = get_option( 'onhmqa_exclude_pages', '' );
	if ( ! empty( $exclude_raw ) ) {
		$current_path = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		$current_path = strtok( $current_path, '?' );
		$excluded     = array_filter( array_map( 'trim', explode( "\n", $exclude_raw ) ) );
		foreach ( $excluded as $path ) {
			if ( $current_path === $path ) return;
		}
	}

	// Pull display values
	$agent_name    = get_option( 'onhmqa_agent_name', '' );
	$agent_title   = get_option( 'onhmqa_agent_title', 'Mortgage Broker' );
	$agent_license = get_option( 'onhmqa_agent_license', '' );
	$agent_phone   = get_option( 'onhmqa_agent_phone', '' );
	$photo_url     = get_option( 'onhmqa_agent_photo_url', '' );
	$urgency       = get_option( 'onhmqa_urgency', '' );
	$popup_enabled = ( get_option( 'onhmqa_popup_enabled', '1' ) === '1' );
	$popup_text    = get_option( 'onhmqa_popup_text', 'Have mortgage questions?' );
	$show_branding = ( get_option( 'onhmqa_show_branding', '0' ) === '1' );

	// Build photo / initials avatar
	if ( $photo_url ) {
		$photo_html = '<img src="' . esc_url( $photo_url ) . '" alt="' . esc_attr( $agent_name ) . '" style="width:38px;height:38px;border-radius:50%;object-fit:cover;border:2px solid rgba(255,255,255,0.35);flex-shrink:0" />';
	} else {
		$parts    = explode( ' ', trim( $agent_name ) );
		$initials = strtoupper( substr( $parts[0] ?? '', 0, 1 ) . ( isset( $parts[1] ) ? substr( $parts[1], 0, 1 ) : '' ) );
		if ( empty( $initials ) ) $initials = 'MB';
		$photo_html = '<div style="width:38px;height:38px;border-radius:50%;background:rgba(255,255,255,0.22);display:flex;align-items:center;justify-content:center;font-size:15px;font-weight:700;color:#fff;flex-shrink:0;border:2px solid rgba(255,255,255,0.35)">' . esc_html( $initials ) . '</div>';
	}

	// NMLS and phone
	$license_display = $agent_license;
	if ( $agent_license && ! preg_match( '/nmls/i', $agent_license ) ) {
		$license_display = 'NMLS #' . $agent_license;
	}
	$phone_digits = preg_replace( '/[^0-9+]/', '', $agent_phone );

	// Build compact meta row (NMLS · phone)
	$icon_shield = '<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;opacity:.9"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>';
	$icon_phone  = '<svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;opacity:.9"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 12 19.79 19.79 0 0 1 1.61 3.47 2 2 0 0 1 3.59 1h3a2 2 0 0 1 2 1.72c.127.96.361 1.903.7 2.81a2 2 0 0 1-.45 2.11L7.91 8.6a16 16 0 0 0 6 6l.92-.92a2 2 0 0 1 2.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0 1 22 16.92z"/></svg>';
	$sep         = '<span style="opacity:.5;font-weight:400">·</span>';

	$meta_row_style = 'font-size:10px;color:rgba(255,255,255,0.92);font-weight:600;margin-top:4px;display:flex;align-items:center;gap:5px;flex-wrap:wrap;text-shadow:0 1px 3px rgba(0,0,0,.35);';
	$meta_parts = array();
	if ( $agent_license ) {
		$meta_parts[] = $icon_shield . '<span>' . esc_html( $license_display ) . '</span>';
	}
	if ( $agent_phone ) {
		$meta_parts[] = '<a href="tel:' . esc_attr( $phone_digits ) . '" style="color:inherit;text-decoration:none;display:inline-flex;align-items:center;gap:4px">' . $icon_phone . '<span>' . esc_html( $agent_phone ) . '</span></a>';
	}
	$meta_html = '';
	if ( ! empty( $meta_parts ) ) {
		$meta_html = '<div style="' . $meta_row_style . '">' . implode( ' ' . $sep . ' ', $meta_parts ) . '</div>';
	}

	// Name · Title line 1
	$name_title = $agent_name ?: get_bloginfo( 'name' );
	if ( $agent_title ) {
		$name_title .= ' · ' . $agent_title;
	}

	// Branding footer
	$branding_html = $show_branding
		? '<div style="text-align:center;padding:6px 0 4px;border-top:1px solid #e5e7eb;margin-top:4px"><a href="https://ournethelps.com/" target="_blank" rel="noopener" style="font-size:10px;color:#9ca3af;text-decoration:none">Powered by OurNetHelps</a></div>'
		: '';

	// SVG kses allowlist
	$svg_kses = array(
		'div'  => array( 'style' => array() ),
		'a'    => array( 'href' => array(), 'style' => array(), 'target' => array(), 'rel' => array() ),
		'span' => array( 'style' => array() ),
		'svg'  => array( 'width' => array(), 'height' => array(), 'viewbox' => array(), 'fill' => array(), 'stroke' => array(), 'stroke-width' => array(), 'stroke-linecap' => array(), 'stroke-linejoin' => array(), 'style' => array(), 'xmlns' => array() ),
		'path' => array( 'd' => array(), 'fill' => array(), 'stroke' => array() ),
		'line' => array( 'x1' => array(), 'y1' => array(), 'x2' => array(), 'y2' => array() ),
	);

	?>
<!-- OurNetHelps Mortgage Q&A Assistant -->
<?php if ( $urgency ) : ?>
<div id="onhmqa-urgency"><?php echo esc_html( $urgency ); ?></div>
<?php endif; ?>

<?php if ( $popup_enabled ) : ?>
<div id="onhmqa-popup" role="status">
	<button id="onhmqa-popup-x" type="button" aria-label="<?php esc_attr_e( 'Dismiss', 'ournethelps-mortgage-qa-assistant' ); ?>">&times;</button>
	<?php echo esc_html( $popup_text ); ?>
</div>
<?php endif; ?>

<button id="onhmqa-btn" type="button" aria-label="<?php esc_attr_e( 'Open chat', 'ournethelps-mortgage-qa-assistant' ); ?>" aria-expanded="false" aria-controls="onhmqa-box">
	<svg class="onhmqa-ico-chat" viewBox="0 0 24 24" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
	<svg class="onhmqa-ico-close" viewBox="0 0 24 24" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>

<div id="onhmqa-box" role="dialog" aria-modal="true" aria-label="<?php esc_attr_e( 'Mortgage Chat', 'ournethelps-mortgage-qa-assistant' ); ?>">
	<div id="onhmqa-head">
		<?php echo wp_kses_post( $photo_html ); ?>
		<div id="onhmqa-head-info">
			<div id="onhmqa-head-name"><?php echo esc_html( $name_title ); ?></div>
			<?php echo wp_kses( $meta_html, $svg_kses ); ?>
		</div>
		<button id="onhmqa-head-close" type="button" aria-label="<?php esc_attr_e( 'Close chat', 'ournethelps-mortgage-qa-assistant' ); ?>">
			<svg viewBox="0 0 24 24" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
		</button>
	</div>
	<div id="onhmqa-msgs" role="log" aria-live="polite" aria-label="<?php esc_attr_e( 'Chat messages', 'ournethelps-mortgage-qa-assistant' ); ?>"></div>
	<div id="onhmqa-chips" role="group" aria-label="<?php esc_attr_e( 'Quick questions', 'ournethelps-mortgage-qa-assistant' ); ?>"></div>
	<div id="onhmqa-inp-row">
		<input
			id="onhmqa-inp"
			type="text"
			placeholder="<?php esc_attr_e( 'Type your question...', 'ournethelps-mortgage-qa-assistant' ); ?>"
			autocomplete="off"
			autocorrect="off"
			autocapitalize="sentences"
			spellcheck="true"
			aria-label="<?php esc_attr_e( 'Chat message', 'ournethelps-mortgage-qa-assistant' ); ?>"
			maxlength="500"
		/>
		<button id="onhmqa-snd" type="button" aria-label="<?php esc_attr_e( 'Send message', 'ournethelps-mortgage-qa-assistant' ); ?>">
			<svg viewBox="0 0 24 24" aria-hidden="true"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
		</button>
	</div>
	<div id="onhmqa-foot"><?php echo wp_kses_post( $branding_html ); ?></div>
</div>
<!-- /OurNetHelps Mortgage Q&A Assistant -->
	<?php
}
