<?php
/**
 * Attribution & copyright: head meta + RSS feed footer (milestone M4).
 *
 * When a scraper republishes your RSS feed, the attribution line travels with
 * the content — turning the theft into a backlink and a clear ownership signal.
 * All output is escaped and SEO-neutral.
 *
 * @package Copyfend
 */

defined( 'ABSPATH' ) || exit;

/**
 * Adds copyright meta to the head and an attribution footer to feed items.
 */
class CShield_Attribution {

	/**
	 * Settings handler.
	 *
	 * @var CShield_Settings
	 */
	private $settings;

	/**
	 * Constructor.
	 *
	 * @param CShield_Settings $settings Settings handler.
	 */
	public function __construct( CShield_Settings $settings ) {
		$this->settings = $settings;

		if ( $settings->get( 'copyright_meta' ) ) {
			add_action( 'wp_head', array( $this, 'head_meta' ), 1 );
		}

		if ( $settings->get( 'rss_attribution' ) ) {
			add_filter( 'the_content_feed', array( $this, 'rss_attribution' ), 30 );
			add_filter( 'the_excerpt_rss', array( $this, 'rss_attribution' ), 30 );
		}
	}

	/**
	 * Resolve the copyright holder (falls back to the site name).
	 *
	 * @return string
	 */
	private function holder() {
		$holder = trim( (string) $this->settings->get( 'copyright_holder', '' ) );
		return '' !== $holder ? $holder : (string) get_bloginfo( 'name' );
	}

	/**
	 * Output a copyright meta tag in the document head.
	 */
	public function head_meta() {
		$holder = $this->holder();
		if ( '' === $holder ) {
			return;
		}
		echo '<meta name="copyright" content="' . esc_attr( '© ' . gmdate( 'Y' ) . ' ' . $holder ) . '" />' . "\n";
	}

	/**
	 * Append an attribution footer to feed content.
	 *
	 * @param string $content Feed item content.
	 * @return string
	 */
	public function rss_attribution( $content ) {
		$link = '<a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_bloginfo( 'name' ) ) . '</a>';
		$line = sprintf(
			'<p>&copy; %1$s %2$s. %3$s</p>',
			esc_html( gmdate( 'Y' ) ),
			esc_html( $this->holder() ),
			sprintf(
				/* translators: %s: linked site name */
				esc_html__( 'This article appeared first on %s.', 'copyfend' ),
				$link // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $link is built from esc_url + esc_html above.
			)
		);
		return $content . $line;
	}
}
