<?php
/**
 * Dashboard analytics page.
 *
 * @package Donatico\Admin
 */

declare(strict_types=1);

namespace Donatico\Admin;

use Donatico\Database\DonationRepository;
use Donatico\Models\Donation;

/**
 * Renders the Donatico dashboard with summary stats and recent donations.
 */
class Dashboard {

	/** @var DonationRepository */
	private DonationRepository $repository;

	/**
	 * @param DonationRepository $repository
	 */
	public function __construct( DonationRepository $repository ) {
		$this->repository = $repository;
	}

	/**
	 * Render the dashboard page.
	 * Callback registered via add_menu_page().
	 *
	 * @return void
	 */
	public function render(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'donatico' ) );
		}

		$stats    = $this->repository->getStats();
		$recent   = $this->repository->findAll( array( 'limit' => 5, 'status' => Donation::STATUS_COMPLETED ) );
		$currency = get_option( 'donatico_currency', 'USD' );
		$goal     = (int) get_option( 'donatico_goal_amount', 0 );

		// Progress towards goal (percent, capped at 100).
		$progress = 0;
		if ( $goal > 0 ) {
			$raised_major = $stats['total_amount'] / 100;
			$progress     = min( 100, (int) round( ( $raised_major / $goal ) * 100 ) );
		}

		// MRR + active-subscriber cards — premium only. SubscriptionTable is
		// stripped from the free build (@fs_premium_only), so this call must
		// stay behind class_exists() or the free dashboard fatals.
		$subscription_stats = null;
		if ( class_exists( '\Donatico\Database\SubscriptionTable' ) ) {
			$subscription_stats = \Donatico\Database\SubscriptionTable::getSubscriptionStats();
		}

		include DONATICO_PLUGIN_DIR . 'templates/admin/dashboard.php';
	}
}
