<?php
/**
 * ReportGenerator
 *
 * Builds the HTML content for scheduled email reports.
 *
 * @package Relatedly\Admin\Email
 * @since   2.0.0
 */

namespace Relatedly\Admin\Email;

use Relatedly\Core\Options;
use Relatedly\Core\Cache;
use Relatedly\Admin\Statistics\DataProvider;

defined( 'ABSPATH' ) || exit;

/**
 * Builds scheduled report email markup.
 *
 * @since 2.0.0
 */
class ReportGenerator {

	/**
	 * Plugin settings repository.
	 *
	 * @since 2.0.0
	 * @var Options
	 */
	private Options $options;

	/**
	 * Statistics data provider.
	 *
	 * @since 2.0.0
	 * @var DataProvider
	 */
	private DataProvider $data;

	/**
	 * Create the report generator.
	 *
	 * @since 2.0.0
	 * @param Options $options Plugin settings repository.
	 * @param Cache   $cache   Cache service.
	 */
	public function __construct( Options $options, Cache $cache ) {
		$this->options = $options;
		$this->data    = new DataProvider( $cache );
	}

	/**
	 * Build the full HTML email body for the report.
	 *
	 * @since 2.0.0
	 */
	public function build(): string {
		$end       = gmdate( 'Y-m-d' );
		$frequency = (string) $this->options->get( 'email_reports_frequency', 'weekly' );
		$days      = ( 'monthly' === $frequency ) ? 30 : 7;
		$start     = gmdate( 'Y-m-d', strtotime( "-{$days} days" ) );

		$summary = $this->options->get( 'email_reports_include_summary', true )
			? $this->data->get_summary( $start, $end )
			: null;

		$top_count = (int) $this->options->get( 'email_reports_top_posts_count', 10 );
		$top_posts = $this->options->get( 'email_reports_include_top_posts', true )
			? $this->data->get_top_clicked( $start, $end, $top_count )
			: [];

		$site_name = get_bloginfo( 'name' );
		$period    = $start . ' – ' . $end;

		ob_start();
		include RELATEDLY_PLUGIN_DIR . 'src/Admin/Email/templates/email-report.php';
		return (string) ob_get_clean();
	}
}
