<?php
/**
 * Builds the weekly AI Visibility Report as a self-contained HTML document.
 *
 * The output of this class is sent as the body of an email via wp_mail(),
 * or opened in the browser as a print-friendly preview. Because email
 * clients (Outlook, Gmail webmail, Apple Mail) do not load external CSS
 * and frequently strip stylesheet blocks, all styling is applied as inline
 * style="..." attributes on each element — the canonical pattern for
 * HTML emails. The rendered document contains no stylesheet tag.
 *
 * Native PDF export (TCPDF / mPDF, prefixed-vendored) is on the roadmap.
 *
 * @package WPLens
 */

namespace WPLens\Reports;

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

final class HtmlReportBuilder {

	/**
	 * Style declarations applied inline on each rendered element.
	 *
	 * Keyed by a short token; build_weekly() pulls from here to keep
	 * the HTML output readable while still producing a fully self-styled
	 * document that survives any email client.
	 *
	 * @return array<string, string>
	 */
	private function styles(): array {
		return array(
			'body'       => 'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; color: #1d2327; max-width: 800px; margin: 24px auto; padding: 0 24px; line-height: 1.5;',
			'h1'         => 'margin: 0 0 4px;',
			'h2'         => 'margin: 32px 0 12px; padding-bottom: 6px; border-bottom: 1px solid #c3c4c7;',
			'muted'      => 'color: #646970; margin: 0;',
			'grid'       => 'display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin: 16px 0;',
			'kpi'        => 'padding: 14px; border: 1px solid #c3c4c7; border-radius: 6px; background: #fbfbfc;',
			'kpi_num'    => 'font-size: 28px; font-weight: 600;',
			'kpi_label'  => 'font-size: 11px; color: #50575e; text-transform: uppercase; letter-spacing: 0.04em;',
			'table'      => 'width: 100%; border-collapse: collapse; margin-top: 12px;',
			'th'         => 'padding: 8px 10px; border-bottom: 1px solid #f0f0f1; text-align: left; font-size: 13px; color: #50575e; font-weight: 600; background: #f6f7f7;',
			'td'         => 'padding: 8px 10px; border-bottom: 1px solid #f0f0f1; text-align: left; font-size: 13px;',
			'td_ok'      => 'padding: 8px 10px; border-bottom: 1px solid #f0f0f1; text-align: left; font-size: 13px; color: #117a3a;',
			'td_bad'     => 'padding: 8px 10px; border-bottom: 1px solid #f0f0f1; text-align: left; font-size: 13px; color: #b32d2e;',
			'footer'     => 'margin-top: 40px; font-size: 12px; color: #646970; border-top: 1px solid #c3c4c7; padding-top: 12px;',
			'ok'         => 'color: #117a3a;',
		);
	}

	/**
	 * Returns the raw CSS declaration string for the given style key, or empty
	 * string if the key is unknown. Callers must wrap the result with
	 * esc_attr() at the output site, e.g.
	 *
	 *   <p style="<?php echo esc_attr( $this->s( 'muted' ) ); ?>">…</p>
	 *
	 * Keeping escape at the call site is what the WordPress Coding Standards
	 * (and Plugin Check) recognise as proper output escaping.
	 */
	private function s( string $key ): string {
		$styles = $this->styles();
		return $styles[ $key ] ?? '';
	}

	public function build_weekly(): string {
		$crawler = new \WPLens\Crawler\LogRepository();
		$scans   = new \WPLens\Scans\ScanRepository();
		$cites   = new \WPLens\Citations\CitationRepository();

		$totals    = $crawler->totals_by_bot( 7 );
		$top_pages = $crawler->top_pages( 7, 10 );
		$blind     = $crawler->blind_spots( 30, 10 );
		$total_7d  = $crawler->total_count( 7 );
		$total_30d = $crawler->total_count( 30 );
		$rate      = $cites->citation_rate( 30 );
		$checks    = $cites->recent_checks( 15 );
		$scan_rows = $scans->recent( 10 );

		$site_name = get_bloginfo( 'name' );
		$site_url  = home_url();
		$now       = wp_date( 'F j, Y' );

		ob_start();
		?>
<!DOCTYPE html>
<html lang="<?php echo esc_attr( get_bloginfo( 'language' ) ); ?>">
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?php echo esc_html( sprintf( /* translators: %s site name */ __( 'AI Visibility Report — %s', 'lens-ai-visibility-monitor' ), $site_name ) ); ?></title>
</head>
<body style="<?php echo esc_attr( $this->s( 'body' ) ); ?>">

<h1 style="<?php echo esc_attr( $this->s( 'h1' ) ); ?>"><?php echo esc_html__( 'AI Visibility Report', 'lens-ai-visibility-monitor' ); ?></h1>
<p style="<?php echo esc_attr( $this->s( 'muted' ) ); ?>">
	<strong><?php echo esc_html( $site_name ); ?></strong> &middot;
	<?php echo esc_html( $site_url ); ?> &middot;
	<?php echo esc_html( $now ); ?>
</p>

<div style="<?php echo esc_attr( $this->s( 'grid' ) ); ?>">
	<div style="<?php echo esc_attr( $this->s( 'kpi' ) ); ?>">
		<div style="<?php echo esc_attr( $this->s( 'kpi_label' ) ); ?>"><?php echo esc_html__( 'AI Bot visits — 7 days', 'lens-ai-visibility-monitor' ); ?></div>
		<div style="<?php echo esc_attr( $this->s( 'kpi_num' ) ); ?>"><?php echo esc_html( number_format_i18n( $total_7d ) ); ?></div>
	</div>
	<div style="<?php echo esc_attr( $this->s( 'kpi' ) ); ?>">
		<div style="<?php echo esc_attr( $this->s( 'kpi_label' ) ); ?>"><?php echo esc_html__( 'AI Bot visits — 30 days', 'lens-ai-visibility-monitor' ); ?></div>
		<div style="<?php echo esc_attr( $this->s( 'kpi_num' ) ); ?>"><?php echo esc_html( number_format_i18n( $total_30d ) ); ?></div>
	</div>
	<div style="<?php echo esc_attr( $this->s( 'kpi' ) ); ?>">
		<div style="<?php echo esc_attr( $this->s( 'kpi_label' ) ); ?>"><?php echo esc_html__( 'Citation rate — 30 days', 'lens-ai-visibility-monitor' ); ?></div>
		<div style="<?php echo esc_attr( $this->s( 'kpi_num' ) ); ?>"><?php echo esc_html( $rate ); ?>%</div>
	</div>
</div>

<h2 style="<?php echo esc_attr( $this->s( 'h2' ) ); ?>"><?php echo esc_html__( 'Crawler activity by bot family (7 days)', 'lens-ai-visibility-monitor' ); ?></h2>
<?php if ( empty( $totals ) ) : ?>
	<p><?php echo esc_html__( 'No AI bot visits in the last 7 days.', 'lens-ai-visibility-monitor' ); ?></p>
<?php else : ?>
	<table style="<?php echo esc_attr( $this->s( 'table' ) ); ?>">
		<thead><tr>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Bot', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Family', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Visits', 'lens-ai-visibility-monitor' ); ?></th>
		</tr></thead>
		<tbody>
		<?php foreach ( $totals as $row ) : ?>
			<tr>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $row['bot_slug'] ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $row['bot_family'] ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( number_format_i18n( (int) $row['visits'] ) ); ?></td>
			</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
<?php endif; ?>

<h2 style="<?php echo esc_attr( $this->s( 'h2' ) ); ?>"><?php echo esc_html__( 'Top crawled pages (7 days)', 'lens-ai-visibility-monitor' ); ?></h2>
<?php if ( empty( $top_pages ) ) : ?>
	<p><?php echo esc_html__( 'No crawler hits on individual pages this week.', 'lens-ai-visibility-monitor' ); ?></p>
<?php else : ?>
	<table style="<?php echo esc_attr( $this->s( 'table' ) ); ?>">
		<thead><tr>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'URI', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Visits', 'lens-ai-visibility-monitor' ); ?></th>
		</tr></thead>
		<tbody>
		<?php foreach ( $top_pages as $row ) : ?>
			<tr>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $row['request_uri'] ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( number_format_i18n( (int) $row['visits'] ) ); ?></td>
			</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
<?php endif; ?>

<h2 style="<?php echo esc_attr( $this->s( 'h2' ) ); ?>"><?php echo esc_html__( 'Blind spots (30 days)', 'lens-ai-visibility-monitor' ); ?></h2>
<?php if ( empty( $blind ) ) : ?>
	<p style="<?php echo esc_attr( $this->s( 'ok' ) ); ?>"><?php echo esc_html__( 'Every published post has been visited by an AI bot in the last 30 days.', 'lens-ai-visibility-monitor' ); ?></p>
<?php else : ?>
	<table style="<?php echo esc_attr( $this->s( 'table' ) ); ?>">
		<thead><tr>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Title', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Type', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Modified', 'lens-ai-visibility-monitor' ); ?></th>
		</tr></thead>
		<tbody>
		<?php foreach ( $blind as $row ) : ?>
			<tr>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $row['post_title'] ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $row['post_type'] ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $row['post_modified_gmt'] ); ?></td>
			</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
<?php endif; ?>

<h2 style="<?php echo esc_attr( $this->s( 'h2' ) ); ?>"><?php echo esc_html__( 'Recent citation checks', 'lens-ai-visibility-monitor' ); ?></h2>
<?php if ( empty( $checks ) ) : ?>
	<p><?php echo esc_html__( 'No citation checks recorded yet. Add queries on the Citations page to start tracking.', 'lens-ai-visibility-monitor' ); ?></p>
<?php else : ?>
	<table style="<?php echo esc_attr( $this->s( 'table' ) ); ?>">
		<thead><tr>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'When', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Query', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Cited?', 'lens-ai-visibility-monitor' ); ?></th>
		</tr></thead>
		<tbody>
		<?php foreach ( $checks as $c ) :
			$cited_td_style = (int) $c['cited'] === 1 ? 'td_ok' : 'td_bad';
		?>
			<tr>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $c['checked_at'] ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( (string) ( $c['query'] ?? '' ) ); ?></td>
				<td style="<?php echo esc_attr( $this->s( $cited_td_style ) ); ?>"><?php echo ( (int) $c['cited'] === 1 ) ? esc_html__( 'Yes', 'lens-ai-visibility-monitor' ) : esc_html__( 'No', 'lens-ai-visibility-monitor' ); ?></td>
			</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
<?php endif; ?>

<h2 style="<?php echo esc_attr( $this->s( 'h2' ) ); ?>"><?php echo esc_html__( 'Recent AEO scans', 'lens-ai-visibility-monitor' ); ?></h2>
<?php if ( empty( $scan_rows ) ) : ?>
	<p><?php echo esc_html__( 'No scans this week.', 'lens-ai-visibility-monitor' ); ?></p>
<?php else : ?>
	<table style="<?php echo esc_attr( $this->s( 'table' ) ); ?>">
		<thead><tr>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Post', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Type', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'Score', 'lens-ai-visibility-monitor' ); ?></th>
			<th style="<?php echo esc_attr( $this->s( 'th' ) ); ?>"><?php echo esc_html__( 'When', 'lens-ai-visibility-monitor' ); ?></th>
		</tr></thead>
		<tbody>
		<?php foreach ( $scan_rows as $row ) :
			$title = get_the_title( (int) $row['post_id'] );
		?>
			<tr>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( '' !== $title ? $title : sprintf( '#%d', (int) $row['post_id'] ) ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $row['scan_type'] ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo $row['score'] === null ? '—' : esc_html( (string) (int) $row['score'] ); ?></td>
				<td style="<?php echo esc_attr( $this->s( 'td' ) ); ?>"><?php echo esc_html( $row['created_at'] ); ?></td>
			</tr>
		<?php endforeach; ?>
		</tbody>
	</table>
<?php endif; ?>

<div style="<?php echo esc_attr( $this->s( 'footer' ) ); ?>">
	<?php echo esc_html__( 'Generated by Lens — AI Visibility Monitor.', 'lens-ai-visibility-monitor' ); ?>
</div>

</body>
</html>
		<?php
		return (string) ob_get_clean();
	}
}
