<?php
/**
 * Weekly email digest of newly detected broken links.
 *
 * @package 404Zen
 */

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

class LGBF_Digest {

	/**
	 * Hooks.
	 */
	public static function init() {
		add_action( LGBF_Cron::DIGEST_HOOK, array( __CLASS__, 'send' ) );
	}

	/**
	 * Sends the digest if enabled and there is something to report.
	 */
	public static function send() {
		if ( ! LGBF_Settings::get( 'digest_enabled' ) ) {
			return;
		}

		$last_sent = (int) get_option( 'lgbf_digest_last_sent', 0 );
		if ( ! $last_sent ) {
			$last_sent = time() - WEEK_IN_SECONDS;
		}

		$since  = gmdate( 'Y-m-d H:i:s', $last_sent );
		$broken = LGBF_Links_Store::get_new_broken_since( $since, 100 );

		update_option( 'lgbf_digest_last_sent', time(), false );

		$recipient = LGBF_Settings::digest_recipient();
		if ( ! is_email( $recipient ) ) {
			return;
		}

		if ( empty( $broken ) ) {
			$site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
			/* translators: %s: site name. */
			$subject = sprintf( __( '[%s] 404Zen weekly: all clear', '404zen-broken-link-fixer' ), $site_name );
			$body    = __( 'No new broken links this week — your site is clean.', '404zen-broken-link-fixer' ) . "\n\n"
				. __( 'Another clean week ✨ 404Zen is free and built by a small team — a review on WordPress.org keeps us going →', '404zen-broken-link-fixer' ) . "\n"
				. 'https://wordpress.org/support/plugin/404zen-broken-link-fixer/reviews/#new-post';
			wp_mail( $recipient, $subject, $body );
			return;
		}

		$site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );

		/* translators: 1: site name, 2: number of broken links. */
		$subject = sprintf( __( '[%1$s] 404Zen found %2$d new broken links this week', '404zen-broken-link-fixer' ), $site_name, count( $broken ) );

		$lines   = array();
		$lines[] = sprintf(
			/* translators: %d: number of broken links. */
			__( '404Zen detected %d new broken links on your site this week:', '404zen-broken-link-fixer' ),
			count( $broken )
		);
		$lines[] = '';

		foreach ( $broken as $row ) {
			$post_title = get_the_title( (int) $row['post_id'] );
			if ( ! $post_title ) {
				$post_title = __( '(untitled)', '404zen-broken-link-fixer' );
			}
			$status_label = ( 'timeout' === $row['status'] )
				? __( 'timeout', '404zen-broken-link-fixer' )
				: sprintf( 'HTTP %d', (int) $row['http_status'] );

			$lines[] = sprintf( '- %1$s (%2$s)', $row['url'], $status_label );
			/* translators: %s: post title. */
			$lines[] = '  ' . sprintf( __( 'Found in: %s', '404zen-broken-link-fixer' ), $post_title );
		}

		$lines[] = '';
		$lines[] = __( 'Review and fix them here:', '404zen-broken-link-fixer' );
		$lines[] = admin_url( 'admin.php?page=lgbf-404zen' );
		$lines[] = '';
		$lines[] = __( 'You can turn this digest off in 404Zen → Settings.', '404zen-broken-link-fixer' );

		wp_mail( $recipient, $subject, implode( "\n", $lines ) );
	}
}
