<?php
/**
 * 247ChatMate — Weekly Lead Summary Email
 *
 * Checkpoint: WEEKLYSUMMARYEMAILTEXTSNAPSHOT5A14G5JLOCK / HISTORYWEEKLYSUMMARYQA5A14HLOCK / LEADRESCUEWEEKLYSUMMARYINCLUSION5A24ALOCK
 *
 * Purpose:
 * - Send a weekly value summary email to the configured Leads Email address.
 * - Reuse local aggregate-only lead history values already maintained by the plugin.
 *
 * Does:
 * - Uses local WordPress options only.
 * - Sends a lightweight HTML summary via wp_mail.
 * - Schedules one idempotent weekly WP-Cron event.
 *
 * Does not:
 * - Attach CSV files by default.
 * - Store raw chats, IP addresses, visitor IDs, fingerprints or lead transcripts.
 * - Send lead history remotely.
 * - Change widget, chip, vertical, WhatsApp, licence, trial, registry or lifecycle authority.
 */

defined( 'ABSPATH' ) || exit;

if ( ! defined( 'MATEWA_WEEKLY_LEAD_SUMMARY_HOOK' ) ) {
	define( 'MATEWA_WEEKLY_LEAD_SUMMARY_HOOK', 'matewa_weekly_lead_summary_email' );
}

if ( ! function_exists( 'matewa_weekly_lead_summary_add_schedule' ) ) {
	function matewa_weekly_lead_summary_add_schedule( $schedules ) {
		if ( ! isset( $schedules['matewa_weekly'] ) ) {
			$schedules['matewa_weekly'] = array(
				'interval' => WEEK_IN_SECONDS,
				'display'  => __( 'Once weekly', '247chatmate' ),
			);
		}

		return $schedules;
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_next_timestamp' ) ) {
	function matewa_weekly_lead_summary_next_timestamp() {
		if ( ! function_exists( 'wp_timezone' ) ) {
			return time() + WEEK_IN_SECONDS;
		}

		try {
			$timezone = wp_timezone();
			$now      = new DateTimeImmutable( 'now', $timezone );
			$target   = $now->modify( 'next sunday' )->setTime( 18, 0, 0 );

			if ( $target->getTimestamp() <= time() ) {
				$target = $target->modify( '+1 week' );
			}

			return $target->getTimestamp();
		} catch ( Exception $exception ) {
			return time() + WEEK_IN_SECONDS;
		}
	}
}

if ( ! function_exists( 'matewa_schedule_weekly_lead_summary_email' ) ) {
	function matewa_schedule_weekly_lead_summary_email() {
		if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_schedule_event' ) ) {
			return;
		}

		if ( wp_next_scheduled( MATEWA_WEEKLY_LEAD_SUMMARY_HOOK ) ) {
			return;
		}

		wp_schedule_event( matewa_weekly_lead_summary_next_timestamp(), 'matewa_weekly', MATEWA_WEEKLY_LEAD_SUMMARY_HOOK );
	}
}

if ( ! function_exists( 'matewa_clear_weekly_lead_summary_email' ) ) {
	function matewa_clear_weekly_lead_summary_email() {
		if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_unschedule_event' ) ) {
			return;
		}

		$timestamp = wp_next_scheduled( MATEWA_WEEKLY_LEAD_SUMMARY_HOOK );

		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, MATEWA_WEEKLY_LEAD_SUMMARY_HOOK );
		}
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_get_recipient' ) ) {
	function matewa_weekly_lead_summary_get_recipient() {
		$recipient = sanitize_email( (string) get_option( 'matewa_leads_email', '' ) );

		return is_email( $recipient ) ? $recipient : '';
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_get_headers' ) ) {
	function matewa_weekly_lead_summary_get_headers() {
		if ( function_exists( 'matewa_pro_lead_routing_get_email_headers' ) ) {
			$headers = matewa_pro_lead_routing_get_email_headers();

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

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

if ( ! function_exists( 'matewa_weekly_lead_summary_format_number' ) ) {
	function matewa_weekly_lead_summary_format_number( $value ) {
		return number_format_i18n( absint( $value ) );
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_plural' ) ) {
	function matewa_weekly_lead_summary_plural( $count, $singular, $plural = '' ) {
		$count = absint( $count );
		$plural = '' !== $plural ? $plural : $singular . 's';

		return 1 === $count ? $singular : $plural;
	}
}


if ( ! function_exists( 'matewa_weekly_lead_summary_percent_label' ) ) {
	function matewa_weekly_lead_summary_percent_label( $current, $previous ) {
		$current  = absint( $current );
		$previous = absint( $previous );

		if ( 0 === $previous && 0 === $current ) {
			return 'No lead change yet';
		}

		if ( 0 === $previous && 0 < $current ) {
			return 'New lead activity';
		}

		$change = (int) round( ( ( $current - $previous ) / max( 1, $previous ) ) * 100 );

		if ( 0 === $change ) {
			return 'No change';
		}

		return ( 0 < $change ? '+' : '' ) . (string) $change . '%';
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_previous_month_key' ) ) {
	function matewa_weekly_lead_summary_previous_month_key( $current_month_key ) {
		$current_month_key = preg_match( '/^\d{4}-\d{2}$/', (string) $current_month_key ) ? (string) $current_month_key : date_i18n( 'Y-m', current_time( 'timestamp' ) );
		$previous_ts       = strtotime( $current_month_key . '-01 -1 month' );

		return false !== $previous_ts ? date_i18n( 'Y-m', $previous_ts ) : '';
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_previous_snapshot' ) ) {
	function matewa_weekly_lead_summary_previous_snapshot() {
		$snapshot = get_option( 'matewa_weekly_lead_summary_last_snapshot', array() );

		return is_array( $snapshot ) ? $snapshot : array();
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_store_snapshot' ) ) {
	function matewa_weekly_lead_summary_store_snapshot( array $stats, $week_key ) {
		$snapshot = array(
			'week_key'           => sanitize_text_field( (string) $week_key ),
			'week_leads'         => absint( $stats['week_leads'] ?? 0 ),
			'month_leads'        => absint( $stats['month_leads'] ?? 0 ),
			'widget_opens'       => absint( $stats['widget_opens'] ?? 0 ),
			'whatsapp_handoffs'  => absint( $stats['whatsapp_handoffs'] ?? 0 ),
			'phone_only_leads'   => absint( $stats['phone_only_leads'] ?? 0 ),
			'saved_at'           => current_time( 'mysql' ),
		);

		update_option( 'matewa_weekly_lead_summary_last_snapshot', $snapshot, false );
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_value_snapshot' ) ) {
	function matewa_weekly_lead_summary_value_snapshot( array $stats ) {
		$widget_opens      = absint( $stats['widget_opens'] ?? 0 );
		$month_leads       = absint( $stats['month_leads'] ?? 0 );
		$phone_only_leads  = absint( $stats['phone_only_leads'] ?? 0 );
		$whatsapp_handoffs = absint( $stats['whatsapp_handoffs'] ?? 0 );
		$handoff_label     = sanitize_text_field( (string) ( $stats['handoff_rate_label'] ?? 'Waiting for opens' ) );
		$handoff_state     = sanitize_key( (string) ( $stats['handoff_rate_state'] ?? 'waiting' ) );
		$opens_label       = matewa_weekly_lead_summary_format_number( $widget_opens );
		$leads_label       = matewa_weekly_lead_summary_format_number( $month_leads );
		$phone_only_label  = matewa_weekly_lead_summary_format_number( $phone_only_leads );
		$handoffs_label    = matewa_weekly_lead_summary_format_number( $whatsapp_handoffs );

		if ( 0 === $widget_opens && 0 === $month_leads ) {
			$headline = 'Your website is ready to start conversations and capture leads.';
			$detail   = 'As people open the widget, this report will show website chats opened, WhatsApp chats started and leads captured.';
		} elseif ( 'calibrating' === $handoff_state ) {
			$headline = 'Your website started ' . $opens_label . ' ' . matewa_weekly_lead_summary_plural( $widget_opens, 'conversation' ) . ' and captured ' . $leads_label . ' ' . matewa_weekly_lead_summary_plural( $month_leads, 'lead' ) . '.';
			$detail   = 'WhatsApp conversion rate is calibrating while conversation and handoff data settles.';
		} elseif ( 'ready' === $handoff_state ) {
			$headline = 'Your website started ' . $opens_label . ' ' . matewa_weekly_lead_summary_plural( $widget_opens, 'conversation' ) . ' and captured ' . $leads_label . ' ' . matewa_weekly_lead_summary_plural( $month_leads, 'lead' ) . '.';
			$detail   = $handoffs_label . ' WhatsApp ' . matewa_weekly_lead_summary_plural( $whatsapp_handoffs, 'chat was', 'chats were' ) . ' started. WhatsApp conversion rate: ' . $handoff_label . '.';
		} else {
			$headline = 'Your website started ' . $opens_label . ' ' . matewa_weekly_lead_summary_plural( $widget_opens, 'conversation' ) . ' this month.';
			$detail   = 'WhatsApp conversion rate will appear once people start WhatsApp chats from the widget.';
		}

		if ( 0 < $phone_only_leads ) {
			$detail .= ' Phone leads saved: ' . $phone_only_label . '. Phone leads saved are people who entered a mobile number but did not finish the WhatsApp step, so you can still follow up.';
		}

		$output  = '<div style="margin:0 auto 18px; max-width:540px; padding:17px 18px; border-radius:16px; background:#ecfdf5; border:1px solid #bbf7d0; color:#14532d;">';
		$output .= '<p style="margin:0; font-size:16px; line-height:1.5; font-weight:800;">' . esc_html( $headline ) . '</p>';
		$output .= '<p style="margin:8px 0 0; font-size:13px; line-height:1.55; color:#166534;">' . esc_html( $detail ) . '</p>';
		$output .= '</div>';

		return $output;
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_prepare_stats' ) ) {
	function matewa_weekly_lead_summary_prepare_stats() {
		if ( ! function_exists( 'matewa_get_lead_history_aggregates' ) ) {
			return array();
		}

		$history           = matewa_get_lead_history_aggregates();
		$current_month_key = function_exists( 'matewa_lead_history_current_month_key' ) ? matewa_lead_history_current_month_key() : date_i18n( 'Y-m', current_time( 'timestamp' ) );
		$month_row         = array();

		if ( isset( $history['monthly'][ $current_month_key ] ) && is_array( $history['monthly'][ $current_month_key ] ) ) {
			$month_row = $history['monthly'][ $current_month_key ];
		}

		if ( function_exists( 'matewa_lead_history_normalise_month_row' ) ) {
			$month_row = matewa_lead_history_normalise_month_row( $month_row );
		} else {
			$month_row = is_array( $month_row ) ? $month_row : array();
		}

		$previous_snapshot  = matewa_weekly_lead_summary_previous_snapshot();
		$previous_week_key = sanitize_text_field( (string) ( $previous_snapshot['week_key'] ?? '' ) );
		$previous_week_leads = ( '' !== $previous_week_key && $previous_week_key !== ( function_exists( 'matewa_lead_history_current_week_key' ) ? matewa_lead_history_current_week_key() : date_i18n( 'o-W', current_time( 'timestamp' ) ) ) )
			? absint( $previous_snapshot['week_leads'] ?? 0 )
			: null;
		$previous_month_key = matewa_weekly_lead_summary_previous_month_key( $current_month_key );
		$has_previous_month = '' !== $previous_month_key && isset( $history['monthly'][ $previous_month_key ] ) && is_array( $history['monthly'][ $previous_month_key ] );
		$previous_month_row = $has_previous_month ? $history['monthly'][ $previous_month_key ] : array();

		if ( $has_previous_month && function_exists( 'matewa_lead_history_normalise_month_row' ) ) {
			$previous_month_row = matewa_lead_history_normalise_month_row( $previous_month_row );
		}

		$previous_month_leads = $has_previous_month ? absint( $previous_month_row['completed_leads'] ?? 0 ) : null;
		$widget_opens      = absint( $month_row['widget_opens'] ?? 0 );
		$whatsapp_handoffs = absint( $month_row['whatsapp_handoffs'] ?? 0 );
		$handoff_label     = 'Waiting for opens';
		$handoff_state     = 'waiting';

		if ( 0 < $widget_opens ) {
			if ( $whatsapp_handoffs > $widget_opens ) {
				$handoff_label = 'Calibrating';
				$handoff_state = 'calibrating';
			} else {
				$handoff_label = (string) (int) round( ( $whatsapp_handoffs / max( 1, $widget_opens ) ) * 100 ) . '%';
				$handoff_state = 'ready';
			}
		}

		$last_activity = sanitize_text_field( (string) ( $history['last_activity'] ?? '' ) );
		if ( function_exists( 'matewa_lead_history_latest_activity' ) ) {
			$latest_activity = matewa_lead_history_latest_activity( $history );
			if ( '' !== $latest_activity ) {
				$last_activity = sanitize_text_field( (string) $latest_activity );
			}
		}

		$last_activity_label = 'None recorded yet';
		if ( '' !== $last_activity ) {
			$activity_ts = strtotime( $last_activity );
			if ( false !== $activity_ts ) {
				$last_activity_label = date_i18n( get_option( 'date_format', 'j M Y' ) . ' ' . get_option( 'time_format', 'H:i' ), $activity_ts );
			}
		}

		$current_week_leads = absint( $history['week_total'] ?? 0 );
		$current_month_leads = absint( $month_row['completed_leads'] ?? $history['month_total'] ?? 0 );
		$week_compare_label = null !== $previous_week_leads
			? matewa_weekly_lead_summary_percent_label( $current_week_leads, $previous_week_leads )
			: 'Waiting for last week';
		$month_compare_label = null !== $previous_month_leads
			? matewa_weekly_lead_summary_percent_label( $current_month_leads, $previous_month_leads )
			: 'Waiting for last month';

		return array(
			'week_leads'          => $current_week_leads,
			'month_leads'         => $current_month_leads,
			'year_leads'          => absint( $history['yearly_total'] ?? 0 ),
			'week_compare_label'  => $week_compare_label,
			'month_compare_label' => $month_compare_label,
			'lead_emails_sent'    => absint( $month_row['lead_emails_sent'] ?? $history['lead_emails_sent'] ?? 0 ),
			'phone_only_leads'    => absint( $month_row['phone_only_leads'] ?? $history['phone_only_leads'] ?? 0 ),
			'widget_opens'        => $widget_opens,
			'whatsapp_handoffs'   => $whatsapp_handoffs,
			'handoff_rate_label'  => $handoff_label,
			'handoff_rate_state'  => $handoff_state,
			'last_activity'       => $last_activity,
			'last_activity_label' => $last_activity_label,
		);
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_has_activity' ) ) {
	function matewa_weekly_lead_summary_has_activity( array $stats ) {
		$activity_total = absint( $stats['week_leads'] ?? 0 )
			+ absint( $stats['month_leads'] ?? 0 )
			+ absint( $stats['year_leads'] ?? 0 )
			+ absint( $stats['lead_emails_sent'] ?? 0 )
			+ absint( $stats['phone_only_leads'] ?? 0 )
			+ absint( $stats['widget_opens'] ?? 0 )
			+ absint( $stats['whatsapp_handoffs'] ?? 0 );

		return 0 < $activity_total || ! empty( $stats['last_activity'] );
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_stat_row' ) ) {
	function matewa_weekly_lead_summary_stat_row( $label, $value, $note = '' ) {
		$output  = '<tr>';
		$output .= '<td style="padding:10px 12px; border-bottom:1px solid #e5e7eb; color:#475569; font-size:14px;">' . esc_html( $label ) . '</td>';
		$output .= '<td style="padding:10px 12px; border-bottom:1px solid #e5e7eb; color:#0f172a; font-size:16px; font-weight:700; text-align:right;">' . esc_html( $value ) . '</td>';
		$output .= '</tr>';

		if ( '' !== $note ) {
			$output .= '<tr><td colspan="2" style="padding:0 12px 10px; border-bottom:1px solid #e5e7eb; color:#64748b; font-size:12px;">' . esc_html( $note ) . '</td></tr>';
		}

		return $output;
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_metric_tone_styles' ) ) {
	function matewa_weekly_lead_summary_metric_tone_styles( $tone ) {
		$tone = sanitize_key( (string) $tone );

		if ( 'calibrating' === $tone ) {
			return array(
				'border' => 'rgba(245, 158, 11, 0.30)',
				'background' => '#fffbeb',
				'value' => '#92400e',
				'label' => '#713f12',
				'trend' => '#92400e',
			);
		}

		if ( 'waiting' === $tone ) {
			return array(
				'border' => 'rgba(100, 116, 139, 0.18)',
				'background' => 'rgba(248, 250, 252, 0.92)',
				'value' => '#5f6b7a',
				'label' => '#111827',
				'trend' => '#5f6b7a',
			);
		}

		return array(
			'border' => 'rgba(34, 197, 94, 0.22)',
			'background' => '#ffffff',
			'value' => '#111827',
			'label' => '#111827',
			'trend' => '#5f6b7a',
		);
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_orbit_transform' ) ) {
	function matewa_weekly_lead_summary_orbit_transform( $position ) {
		$angles = array(
			1 => 270,
			2 => 330,
			3 => 30,
			4 => 90,
			5 => 150,
			6 => 210,
		);

		$angle = isset( $angles[ absint( $position ) ] ) ? $angles[ absint( $position ) ] : 270;

		return 'translate(-50%, -50%) rotate(' . (string) $angle . 'deg) translate(230px) rotate(-' . (string) $angle . 'deg)';
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_orbit_item' ) ) {
	function matewa_weekly_lead_summary_orbit_item( $position, $value, $label, $trend, $tone = 'ready', $url = '' ) {
		$styles    = matewa_weekly_lead_summary_metric_tone_styles( $tone );
		$transform = matewa_weekly_lead_summary_orbit_transform( $position );
		$tag       = '' !== $url ? 'a' : 'div';
		$href      = '' !== $url ? ' href="' . esc_url( $url ) . '"' : '';

		$item_style = 'position:absolute; z-index:4; top:50%; left:50%; display:block; width:122px; height:122px; padding:14px; border:1px solid ' . $styles['border'] . '; border-radius:999px; background:' . $styles['background'] . '; box-shadow:0 15px 35px rgba(15, 23, 42, 0.08); text-align:center; box-sizing:border-box; text-decoration:none; color:inherit; transform:' . $transform . ';';

		return '<' . $tag . $href . ' style="' . esc_attr( $item_style ) . '">'
			. '<table role="presentation" cellspacing="0" cellpadding="0" style="width:100%; height:100%; border-collapse:collapse;">'
			. '<tr><td style="vertical-align:middle; text-align:center; padding:0;">'
			. '<strong style="display:block; max-width:86px; margin:0 auto 4px; color:' . esc_attr( $styles['value'] ) . '; font-family:Inter, Arial, Helvetica, sans-serif; font-size:19px; font-weight:950; letter-spacing:-0.035em; line-height:1.05; overflow-wrap:anywhere;">' . esc_html( (string) $value ) . '</strong>'
			. '<span style="display:block; margin:0 auto 4px; color:' . esc_attr( $styles['label'] ) . '; font-family:Inter, Arial, Helvetica, sans-serif; font-size:11px; font-weight:900; letter-spacing:-0.01em; line-height:1.18; overflow-wrap:anywhere;">' . esc_html( (string) $label ) . '</span>'
			. '<span style="display:block; max-width:84px; margin:0 auto; color:' . esc_attr( $styles['trend'] ) . '; font-family:Inter, Arial, Helvetica, sans-serif; font-size:10.5px; font-weight:800; line-height:1.18; overflow-wrap:anywhere;">' . esc_html( (string) $trend ) . '</span>'
			. '</td></tr></table>'
			. '</' . $tag . '>';
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_dashboard_radial' ) ) {
	function matewa_weekly_lead_summary_dashboard_radial( array $stats, $dashboard_url ) {
		$year_leads          = matewa_weekly_lead_summary_format_number( $stats['year_leads'] ?? 0 );
		$month_leads         = matewa_weekly_lead_summary_format_number( $stats['month_leads'] ?? 0 );
		$week_leads          = matewa_weekly_lead_summary_format_number( $stats['week_leads'] ?? 0 );
		$lead_emails         = matewa_weekly_lead_summary_format_number( $stats['lead_emails_sent'] ?? 0 );
		$phone_only_leads    = matewa_weekly_lead_summary_format_number( $stats['phone_only_leads'] ?? 0 );
		$last_activity_label = sanitize_text_field( (string) ( $stats['last_activity_label'] ?? 'None recorded yet' ) );
		$handoff_label       = sanitize_text_field( (string) ( $stats['handoff_rate_label'] ?? '—' ) );
		$handoff_state       = sanitize_key( (string) ( $stats['handoff_rate_state'] ?? 'waiting' ) );
		$widget_opens        = absint( $stats['widget_opens'] ?? 0 );
		$whatsapp_handoffs   = absint( $stats['whatsapp_handoffs'] ?? 0 );
		$has_activity        = matewa_weekly_lead_summary_has_activity( $stats );

		$last_lead_short = 'None yet';
		if ( 'None recorded yet' !== $last_activity_label ) {
			$activity_ts = strtotime( $last_activity_label );
			$last_lead_short = false !== $activity_ts ? date_i18n( get_option( 'date_format', 'j M Y' ), $activity_ts ) : $last_activity_label;
		}

		$handoff_summary = 'Waiting for opens';
		$handoff_tone    = 'waiting';
		if ( 'calibrating' === $handoff_state ) {
			$handoff_summary = 'Open data settling';
			$handoff_tone    = 'calibrating';
		} elseif ( 'ready' === $handoff_state ) {
			$handoff_summary = sprintf(
				'%1$d opens / %2$d handoff%3$s',
				$widget_opens,
				$whatsapp_handoffs,
				1 === $whatsapp_handoffs ? '' : 's'
			);
			$handoff_tone = 0 < $whatsapp_handoffs ? 'ready' : 'waiting';
		}

		$output  = '<div style="width:620px; height:590px; max-width:100%; margin:0 auto 4px; position:relative; font-family:Inter, Arial, Helvetica, sans-serif;">';
		$output .= '<div style="position:absolute; z-index:1; top:50%; left:50%; width:520px; height:520px; margin:-260px 0 0 -260px; border:1px dashed rgba(34, 197, 94, 0.24); border-radius:999px; background:radial-gradient(circle, rgba(236, 253, 245, 0.70) 0 25%, rgba(236, 253, 245, 0.26) 26% 50%, transparent 51% 100%);"></div>';
		$output .= '<div style="position:absolute; z-index:2; top:50%; left:50%; width:390px; height:390px; margin:-195px 0 0 -195px; border:1px solid rgba(34, 197, 94, 0.20); border-radius:999px;"></div>';
		$output .= '<div style="position:absolute; z-index:3; top:50%; left:50%; width:230px; height:230px; margin:-115px 0 0 -115px; padding:28px; border:1px solid rgba(34, 197, 94, 0.24); border-radius:999px; background:radial-gradient(circle at 50% 38%, rgba(255,255,255,1), rgba(255,255,255,0.95)); box-shadow:0 20px 50px rgba(15, 23, 42, 0.10), 0 0 0 10px rgba(236, 253, 245, 0.70); text-align:center; box-sizing:border-box;">';
		$output .= '<table role="presentation" cellspacing="0" cellpadding="0" style="width:100%; height:100%; border-collapse:collapse;"><tr><td style="vertical-align:middle; text-align:center;">';
		$output .= '<span style="display:inline-block; width:28px; height:28px; margin:0 auto 8px; border-radius:999px; color:#35b729; font-size:21px; font-weight:900; line-height:28px;">↗</span>';
		$output .= '<strong style="display:block; max-width:170px; margin:0 auto 8px; color:#111827; font-size:48px; font-weight:950; letter-spacing:-0.045em; line-height:0.96;">' . esc_html( $year_leads ) . '</strong>';
		$output .= '<span style="display:block; color:#111827; font-size:12.5px; font-weight:900; line-height:1.2;">Leads this year</span>';
		$output .= '<span style="display:block; margin-top:4px; color:' . ( $has_activity ? '#35b729' : '#5f6b7a' ) . '; font-size:10.5px; font-weight:900; line-height:1.2;">' . esc_html( $has_activity ? 'Website is generating leads' : 'Waiting for first lead' ) . '</span>';
		$output .= '</td></tr></table>';
		$output .= '</div>';

		$output .= matewa_weekly_lead_summary_orbit_item( 1, $month_leads, 'This month', 0 < absint( $stats['month_leads'] ?? 0 ) ? 'Lead activity' : 'Clean month', 0 < absint( $stats['month_leads'] ?? 0 ) ? 'ready' : 'waiting' );
		$output .= matewa_weekly_lead_summary_orbit_item( 2, $week_leads, 'This week', 0 < absint( $stats['week_leads'] ?? 0 ) ? 'Recent leads' : 'No leads yet', 0 < absint( $stats['week_leads'] ?? 0 ) ? 'ready' : 'waiting' );
		$output .= matewa_weekly_lead_summary_orbit_item( 3, $handoff_label, 'Lead activity', $handoff_summary, $handoff_tone );
		$output .= matewa_weekly_lead_summary_orbit_item( 4, $lead_emails, 'Leads emailed', 0 < absint( $stats['lead_emails_sent'] ?? 0 ) ? 'Sent to inbox' : 'None sent yet', 0 < absint( $stats['lead_emails_sent'] ?? 0 ) ? 'ready' : 'waiting' );
		$output .= matewa_weekly_lead_summary_orbit_item( 5, $last_lead_short, 'Last lead', $has_activity ? 'Latest activity' : 'Not recorded yet', $has_activity ? 'ready' : 'waiting' );
		$output .= matewa_weekly_lead_summary_orbit_item( 6, 'View', 'History', 'Open panel', 'ready', $dashboard_url );

		if ( 0 < absint( $stats['phone_only_leads'] ?? 0 ) ) {
			$output .= '<div style="position:absolute; left:50%; bottom:10px; z-index:5; width:210px; margin-left:-105px; padding:7px 10px; border:1px solid rgba(34,197,94,0.16); border-radius:999px; background:rgba(236,253,245,0.78); color:#166534; font-size:10.5px; font-weight:850; line-height:1.2; text-align:center;">Phone leads saved: ' . esc_html( $phone_only_leads ) . '</div>';
		}

		$output .= '</div>';

		return $output;
	}
}


if ( ! function_exists( 'matewa_weekly_lead_summary_comparison_card' ) ) {
	function matewa_weekly_lead_summary_comparison_card( array $stats ) {
		$week_compare  = sanitize_text_field( (string) ( $stats['week_compare_label'] ?? 'Waiting for last week' ) );
		$month_compare = sanitize_text_field( (string) ( $stats['month_compare_label'] ?? 'Waiting for last month' ) );

		$output  = '<div style="margin:16px auto 0; max-width:540px; padding:15px 16px; border-radius:14px; background:#f0fdf4; border:1px solid #bbf7d0; color:#14532d;">';
		$output .= '<div style="margin:0 0 9px; font-size:13px; font-weight:900; letter-spacing:.02em; text-transform:uppercase; color:#15803d;">Progress snapshot</div>';
		$output .= '<table role="presentation" cellspacing="0" cellpadding="0" style="width:100%; border-collapse:collapse;">';
		$output .= '<tr><td style="padding:5px 0; font-size:13px; line-height:1.45; color:#166534;">This week vs last week</td><td align="right" style="padding:5px 0; font-size:13px; line-height:1.45; color:#0f172a; font-weight:900;">' . esc_html( $week_compare ) . '</td></tr>';
		$output .= '<tr><td style="padding:5px 0; font-size:13px; line-height:1.45; color:#166534;">This month vs last month</td><td align="right" style="padding:5px 0; font-size:13px; line-height:1.45; color:#0f172a; font-weight:900;">' . esc_html( $month_compare ) . '</td></tr>';
		$output .= '</table>';
		$output .= '<p style="margin:9px 0 0; font-size:12.5px; line-height:1.55; color:#166534;">These comparisons use leads captured on this website. If there is not enough previous data yet, the report will show a waiting message.</p>';
		$output .= '</div>';

		return $output;
	}
}


if ( ! function_exists( 'matewa_weekly_lead_summary_text_fallback' ) ) {
	function matewa_weekly_lead_summary_text_fallback( array $stats ) {
		$rows = array(
			'Leads this year'             => matewa_weekly_lead_summary_format_number( $stats['year_leads'] ?? 0 ),
			'Leads this month'            => matewa_weekly_lead_summary_format_number( $stats['month_leads'] ?? 0 ),
			'Leads this week'             => matewa_weekly_lead_summary_format_number( $stats['week_leads'] ?? 0 ),
			'Website chats opened'       => matewa_weekly_lead_summary_format_number( $stats['widget_opens'] ?? 0 ),
			'WhatsApp chats started'      => matewa_weekly_lead_summary_format_number( $stats['whatsapp_handoffs'] ?? 0 ),
			'WhatsApp conversion rate'    => sanitize_text_field( (string) ( $stats['handoff_rate_label'] ?? 'Waiting for opens' ) ),
			'Leads emailed to inbox'      => matewa_weekly_lead_summary_format_number( $stats['lead_emails_sent'] ?? 0 ),
			'Phone leads saved'           => matewa_weekly_lead_summary_format_number( $stats['phone_only_leads'] ?? 0 ),
			'Most recent lead'            => sanitize_text_field( (string) ( $stats['last_activity_label'] ?? 'None recorded yet' ) ),
		);

		$output = '<table role="presentation" cellspacing="0" cellpadding="0" style="width:100%; max-width:540px; margin:18px auto 0; border-collapse:collapse; border:1px solid #e5e7eb; border-radius:14px; overflow:hidden; background:#ffffff;">';
		foreach ( $rows as $label => $value ) {
			$output .= '<tr>';
			$output .= '<td style="padding:10px 14px; border-bottom:1px solid #e5e7eb; color:#475569; font-size:13px; font-weight:700;">' . esc_html( $label ) . '</td>';
			$output .= '<td style="padding:10px 14px; border-bottom:1px solid #e5e7eb; color:#0f172a; font-size:13px; font-weight:800; text-align:right;">' . esc_html( $value ) . '</td>';
			$output .= '</tr>';
		}
		$output .= '</table>';

		return $output;
	}
}

if ( ! function_exists( 'matewa_weekly_lead_summary_build_email' ) ) {
	function matewa_weekly_lead_summary_build_email( array $stats ) {
		$business_name = function_exists( 'matewa_pro_lead_routing_get_business_name' ) ? matewa_pro_lead_routing_get_business_name() : get_bloginfo( 'name' );
		$dashboard_url = admin_url( 'admin.php?page=247chatmate' );
		$logo_url      = defined( 'MATEWA_PLUGIN_URL' ) ? MATEWA_PLUGIN_URL . 'admin/assets/247trademate-logo.png' : '';

		return '<!doctype html><html><body style="margin:0; padding:0; background:#f8fafc; font-family:Inter, Arial, Helvetica, sans-serif; color:#0f172a;">'
			. '<div style="max-width:700px; margin:0 auto; padding:28px 16px;">'
			. '<div style="background:#ffffff; border:1px solid #e2e8f0; border-radius:18px; overflow:hidden; box-shadow:0 18px 48px rgba(15, 23, 42, 0.08);">'
			. '<div style="padding:22px 24px 18px; background:#0f172a; color:#ffffff;">'
			. '<table role="presentation" cellspacing="0" cellpadding="0" style="width:100%; border-collapse:collapse; margin:0 0 16px;"><tr>'
			. '<td style="width:48px; vertical-align:middle; padding:0 12px 0 0;">' . ( '' !== $logo_url ? '<img src="' . esc_url( $logo_url ) . '" alt="247ChatMate" width="42" height="42" style="display:block; width:42px; height:42px; border-radius:12px;" />' : '' ) . '</td>'
			. '<td style="vertical-align:middle; padding:0;"><p style="margin:0; color:#86efac; font-size:13px; font-weight:800; letter-spacing:.08em; text-transform:uppercase;">247ChatMate Weekly Summary</p><p style="margin:4px 0 0; color:#cbd5e1; font-size:12px; line-height:1.4;">Website enquiries, widget opens and WhatsApp activity</p></td>'
			. '</tr></table>'
			. '<h1 style="margin:0; font-size:23px; line-height:1.25;">Your website lead report</h1>'
			. '<p style="margin:12px 0 0; color:#cbd5e1; font-size:14px; line-height:1.6;">Here is what your website captured this week for ' . esc_html( $business_name ) . '.</p>'
			. '</div>'
			. '<div style="padding:22px 10px 28px;">'
			. matewa_weekly_lead_summary_value_snapshot( $stats )
			. matewa_weekly_lead_summary_text_fallback( $stats )
			. matewa_weekly_lead_summary_comparison_card( $stats )
			. '<div style="margin:18px auto 0; max-width:540px; padding:16px; border-radius:14px; background:#f8fafc; border:1px solid #e2e8f0; color:#475569; font-size:14px; line-height:1.6;">'
			. '<strong>Note:</strong> These numbers are counted on this website only. No visitor IDs, IP addresses or chat messages are stored in this report.'
			. '</div>'
			. '<p style="margin:20px 0 0; font-size:14px; line-height:1.6; color:#475569; text-align:center;"><a href="' . esc_url( $dashboard_url ) . '" style="display:inline-block; padding:12px 18px; border-radius:999px; background:#16a34a; color:#ffffff; text-decoration:none; font-weight:700;">View dashboard</a></p>'
			. '</div>'
			. '<div style="padding:16px 24px; border-top:1px solid #e2e8f0; color:#64748b; font-size:12px; line-height:1.5; text-align:center;">247ChatMate — helping your website start more conversations.</div>'
			. '</div>'
			. '</div>'
			. '</body></html>';
	}
}


if ( ! function_exists( 'matewa_weekly_lead_summary_default_test_stats' ) ) {
	function matewa_weekly_lead_summary_default_test_stats() {
		return array(
			'week_leads'          => 0,
			'month_leads'         => 0,
			'year_leads'          => 0,
			'week_compare_label'  => 'Waiting for last week',
			'month_compare_label' => 'Waiting for last month',
			'lead_emails_sent'    => 0,
			'phone_only_leads'    => 0,
			'widget_opens'        => 0,
			'whatsapp_handoffs'   => 0,
			'handoff_rate_label'  => 'Waiting for opens',
			'handoff_rate_state'  => 'waiting',
			'last_activity_label' => 'None recorded yet',
		);
	}
}

if ( ! function_exists( 'matewa_send_weekly_lead_summary_email' ) ) {
	function matewa_send_weekly_lead_summary_email( $force_test = false ) {
		$recipient = matewa_weekly_lead_summary_get_recipient();
		if ( '' === $recipient ) {
			return false;
		}

		$stats = matewa_weekly_lead_summary_prepare_stats();
		if ( empty( $stats ) ) {
			if ( $force_test && function_exists( 'matewa_weekly_lead_summary_default_test_stats' ) ) {
				$stats = matewa_weekly_lead_summary_default_test_stats();
			} else {
				return false;
			}
		}

		if ( ! $force_test && ! matewa_weekly_lead_summary_has_activity( $stats ) ) {
			return false;
		}

		$current_week = function_exists( 'matewa_lead_history_current_week_key' ) ? matewa_lead_history_current_week_key() : date_i18n( 'o-W', current_time( 'timestamp' ) );
		$last_sent    = sanitize_text_field( (string) get_option( 'matewa_weekly_lead_summary_last_sent_week', '' ) );

		if ( ! $force_test && $last_sent === $current_week ) {
			return false;
		}

		$subject = $force_test ? 'Test: Your weekly 247ChatMate lead summary' : 'Your weekly 247ChatMate lead summary';
		$subject = wp_specialchars_decode( $subject, ENT_QUOTES );
		$message = matewa_weekly_lead_summary_build_email( $stats );
		$headers = matewa_weekly_lead_summary_get_headers();

		if ( function_exists( 'matewa_fallback_mail_send' ) ) {
			$delivery_result = matewa_fallback_mail_send(
				$force_test ? 'weekly_summary_test' : 'weekly_summary',
				$recipient,
				$subject,
				$message,
				$headers,
				array( 'summary_type' => $force_test ? 'test' : 'scheduled' )
			);
			$sent = ! empty( $delivery_result['sent'] );
			$queued = ! empty( $delivery_result['queued'] );
		} else {
			$sent = wp_mail( $recipient, $subject, $message, $headers );
			$queued = false;
		}

		if ( $sent && ! $force_test ) {
			update_option( 'matewa_weekly_lead_summary_last_sent_week', $current_week, false );
			matewa_weekly_lead_summary_store_snapshot( $stats, $current_week );
		}

		return (bool) ( $sent || $queued );
	}
}


if ( ! function_exists( 'matewa_send_weekly_lead_summary_test_email' ) ) {
	function matewa_send_weekly_lead_summary_test_email() {
		return matewa_send_weekly_lead_summary_email( true );
	}
}

if ( ! function_exists( 'matewa_handle_weekly_lead_summary_test_request' ) ) {
	function matewa_handle_weekly_lead_summary_test_request() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
		if ( '247chatmate' !== $page || empty( $_POST['matewa_weekly_summary_action'] ) ) {
			return;
		}

		check_admin_referer( 'matewa_weekly_summary_test_nonce', 'matewa_weekly_summary_test_nonce' );

		$action = sanitize_key( wp_unslash( $_POST['matewa_weekly_summary_action'] ) );
		if ( 'send_test' !== $action ) {
			wp_safe_redirect( admin_url( 'admin.php?page=247chatmate&matewa_saved_section=setup&matewa_scroll_target=lead_tools&matewa_weekly_summary_notice=unknown_action#matewa-setup-lead-tools' ) );
			exit;
		}

		$recipient = matewa_weekly_lead_summary_get_recipient();
		if ( '' === $recipient ) {
			wp_safe_redirect( admin_url( 'admin.php?page=247chatmate&matewa_saved_section=setup&matewa_scroll_target=lead_tools&matewa_weekly_summary_notice=missing_recipient#matewa-setup-lead-tools' ) );
			exit;
		}

		$sent = matewa_send_weekly_lead_summary_test_email();
		$notice = $sent ? 'test_sent' : 'test_failed';
		if ( function_exists( 'matewa_fallback_mail_get_last_result' ) ) {
			$last_delivery_result = matewa_fallback_mail_get_last_result();
			if ( ! empty( $last_delivery_result['queued'] ) && empty( $last_delivery_result['sent'] ) ) {
				$notice = 'test_queued';
			}
		}

		wp_safe_redirect( admin_url( 'admin.php?page=247chatmate&matewa_saved_section=setup&matewa_scroll_target=lead_tools&matewa_weekly_summary_notice=' . $notice . '#matewa-setup-lead-tools' ) );
		exit;
	}
}

add_filter( 'cron_schedules', 'matewa_weekly_lead_summary_add_schedule' );
add_action( 'admin_init', 'matewa_handle_weekly_lead_summary_test_request', 4 );
add_action( 'init', 'matewa_schedule_weekly_lead_summary_email' );
add_action( MATEWA_WEEKLY_LEAD_SUMMARY_HOOK, 'matewa_send_weekly_lead_summary_email' );

if ( defined( 'MATEWA_MAIN_FILE' ) && function_exists( 'register_deactivation_hook' ) ) {
	register_deactivation_hook( MATEWA_MAIN_FILE, 'matewa_clear_weekly_lead_summary_email' );
}
