<?php
/**
 * Handles the browser return from Stripe Checkout.
 *
 * @package Donatico\Frontend
 */

declare(strict_types=1);

namespace Donatico\Frontend;

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

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

/**
 * Detects ?donatico_action=success|cancel in the query string and renders
 * a full thank-you (or cancellation) page using the active WordPress theme's
 * header and footer.
 *
 * Hooked to init so it can add a template_redirect action before any output.
 */
class ThankYouPage {

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

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

	/**
	 * Detect a Stripe return URL and queue the template_redirect renderer.
	 * Hooked to init by Plugin::defineFrontendHooks().
	 *
	 * @return void
	 */
	public function handleReturn(): void {
		// phpcs:disable WordPress.Security.NonceVerification.Recommended
		$action     = isset( $_GET['donatico_action'] ) ? sanitize_key( wp_unslash( $_GET['donatico_action'] ) ) : '';
		$session_id = isset( $_GET['session_id'] ) ? sanitize_text_field( wp_unslash( $_GET['session_id'] ) ) : '';
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		if ( ! $action || ! in_array( $action, array( 'success', 'cancel' ), true ) || ! $session_id ) {
			return;
		}

		// Load the donation now (during init) so it's available in the closure.
		$donation        = $this->repository->findByStripeSessionId( $session_id );
		$currency        = (string) get_option( 'donatico_currency', 'USD' );
		$currency_symbol = Currency::getSymbol( $currency );

		// Render our page instead of the normal WordPress template.
		add_action(
			'template_redirect',
			function () use ( $action, $donation, $currency, $currency_symbol ) {
				$this->renderPage( $action, $donation, $currency, $currency_symbol );
			}
		);
	}

	// -------------------------------------------------------------------------
	// Renderer
	// -------------------------------------------------------------------------

	/**
	 * Output a complete page using the theme's header/footer.
	 *
	 * @param string        $action          'success' or 'cancel'.
	 * @param Donation|null $donation        Donation loaded from DB, or null if not found.
	 * @param string        $currency        ISO currency code.
	 * @param string        $currency_symbol Currency symbol.
	 * @return void
	 */
	private function renderPage(
		string $action,
		?Donation $donation,
		string $currency,
		string $currency_symbol
	): void {
		// Enqueue form CSS so the thank-you template can use .donatico-* classes.
		wp_enqueue_style(
			'donatico-form',
			DONATICO_PLUGIN_URL . 'assets/css/form.css',
			array(),
			DONATICO_VERSION
		);

		get_header();

		$template = DONATICO_PLUGIN_DIR . 'templates/frontend/thank-you.php';

		if ( file_exists( $template ) ) {
			include $template;
		} else {
			echo '<div style="padding:2rem;max-width:640px;margin:auto">';
			if ( $action === 'success' ) {
				echo '<h1>' . esc_html__( 'Thank you for your donation!', 'donatico' ) . '</h1>';
			} else {
				echo '<h1>' . esc_html__( 'Donation cancelled.', 'donatico' ) . '</h1>';
				echo '<p><a href="' . esc_url( home_url( '/' ) ) . '">' . esc_html__( 'Return to homepage', 'donatico' ) . '</a></p>';
			}
			echo '</div>';
		}

		get_footer();
		exit;
	}
}
