<?php
/**
 * @package Hafenstudios\Leadlotse
 */

namespace Hafenstudios\Leadlotse\Admin;

use Hafenstudios\Leadlotse\Db\EntryRepository;
use Hafenstudios\Leadlotse\Events\EventCapacity;
use Hafenstudios\Leadlotse\Events\ParticipantList;
use Hafenstudios\Leadlotse\Events\ParticipantsExport;
use Hafenstudios\Leadlotse\Events\TicketPage;
use Hafenstudios\Leadlotse\Forms\FormPostType;

defined( 'ABSPATH' ) || exit;

/**
 * Teilnehmer-Sicht je RSVP-Formular (L-R1), erreichbar aus der Inbox
 * (`admin.php?page=leadlotse-inbox&ll_view=participants&form=N`) und aus der
 * Formularliste. Serverseitig gerendert (kein JS noetig): Tabelle mit
 * Summenzeile plus Export-Button "Fuer Excel exportieren" (CSV, UTF-8-BOM,
 * Semikolon; Entscheidung LR1).
 */
final class ParticipantsPage {

	public const EXPORT_ACTION = 'leadlotse_export_participants';

	private EntryRepository $entries;

	/**
	 * @param EntryRepository $entries Entry-Repository.
	 */
	public function __construct( EntryRepository $entries ) {
		$this->entries = $entries;
	}

	/**
	 * Verdrahtet den Export-Handler.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'admin_post_' . self::EXPORT_ACTION, array( $this, 'handle_export' ) );
	}

	/**
	 * URL der Teilnehmer-Sicht eines Formulars.
	 *
	 * @param int $form_id Formular-ID.
	 * @return string
	 */
	public static function url( int $form_id ): string {
		return add_query_arg(
			array(
				'page'    => Menu::INBOX_SLUG,
				'll_view' => 'participants',
				'form'    => $form_id,
			),
			admin_url( 'admin.php' )
		);
	}

	/**
	 * Rendert die Teilnehmer-Tabelle.
	 *
	 * @param int $form_id Formular-ID.
	 * @return void
	 */
	public function render( int $form_id ): void {
		if ( ! current_user_can( 'hs_view_entries' ) ) {
			wp_die( esc_html__( 'Sie haben keine Berechtigung, Anfragen einzusehen.', 'leadlotse' ) );
		}

		$post       = get_post( $form_id );
		$definition = FormPostType::get_definition( $form_id );

		echo '<div class="wrap hs-leadlotse-participants">';
		echo '<h1 class="wp-heading-inline">' . esc_html__( 'Teilnehmer', 'leadlotse' ) . '</h1>';

		if ( ! $post || null === $definition ) {
			echo '<p>' . esc_html__( 'Dieses Formular wurde nicht gefunden.', 'leadlotse' ) . '</p></div>';
			return;
		}

		$export_url = wp_nonce_url(
			add_query_arg(
				array(
					'action' => self::EXPORT_ACTION,
					'form'   => $form_id,
				),
				admin_url( 'admin-post.php' )
			),
			self::EXPORT_ACTION
		);
		echo ' <a href="' . esc_url( $export_url ) . '" class="page-title-action">' . esc_html__( 'Fuer Excel exportieren', 'leadlotse' ) . '</a>';
		echo '<hr class="wp-header-end" />';

		$event = (array) ( $definition['settings']['event'] ?? array() );
		echo '<p class="hs-participants-meta"><strong>' . esc_html( (string) $post->post_title ) . '</strong>';
		$date = TicketPage::format_event_date( (string) ( $event['date'] ?? '' ) );
		if ( '' !== $date ) {
			echo ' &middot; ' . esc_html( $date );
		}
		if ( '' !== (string) ( $event['location'] ?? '' ) ) {
			echo ' &middot; ' . esc_html( (string) $event['location'] );
		}
		echo '</p>';

		$list   = ( new ParticipantList( $this->entries ) )->for_form( $form_id, $definition );
		$labels = ParticipantList::status_labels();

		$capacity = EventCapacity::capacity( $definition );
		if ( $capacity > 0 ) {
			echo '<p>' . esc_html(
				sprintf(
					/* translators: 1: belegte Plaetze, 2: Kapazitaet */
					__( 'Belegt: %1$d von %2$d Plaetzen.', 'leadlotse' ),
					(int) $list['total_persons'],
					$capacity
				)
			) . '</p>';
		}

		echo '<table class="wp-list-table widefat fixed striped">';
		echo '<thead><tr>';
		foreach ( array(
			__( 'Vorname', 'leadlotse' ),
			__( 'E-Mail', 'leadlotse' ),
			__( 'Telefon', 'leadlotse' ),
			__( 'Begleitpersonen', 'leadlotse' ),
			__( 'Personen gesamt', 'leadlotse' ),
			__( 'Status', 'leadlotse' ),
			__( 'Anmeldezeit', 'leadlotse' ),
		) as $head ) {
			echo '<th scope="col">' . esc_html( $head ) . '</th>';
		}
		echo '</tr></thead><tbody>';

		if ( array() === $list['rows'] ) {
			echo '<tr><td colspan="7">' . esc_html__( 'Noch keine Anmeldungen.', 'leadlotse' ) . '</td></tr>';
		}

		foreach ( $list['rows'] as $row ) {
			$timestamp = strtotime( (string) $row['created_at'] );
			echo '<tr>';
			echo '<td>' . esc_html( (string) $row['first_name'] ) . '</td>';
			echo '<td><a href="mailto:' . esc_attr( (string) $row['email'] ) . '">' . esc_html( (string) $row['email'] ) . '</a></td>';
			echo '<td>' . esc_html( (string) $row['phone'] ) . '</td>';
			echo '<td>' . (int) $row['companions'] . '</td>';
			echo '<td>' . (int) $row['persons'] . '</td>';
			echo '<td>' . esc_html( (string) ( $labels[ $row['status'] ] ?? $row['status'] ) ) . '</td>';
			echo '<td>' . esc_html( false !== $timestamp ? gmdate( 'd.m.Y H:i', $timestamp ) : (string) $row['created_at'] ) . '</td>';
			echo '</tr>';
		}

		echo '</tbody><tfoot><tr>';
		echo '<th scope="row">' . esc_html__( 'Gesamt', 'leadlotse' ) . '</th>';
		echo '<th></th><th></th>';
		echo '<th>' . (int) $list['total_companions'] . '</th>';
		echo '<th>' . (int) $list['total_persons'] . '</th>';
		echo '<th colspan="2">' . esc_html(
			sprintf(
				/* translators: %d: Anzahl Anmeldungen */
				_n( '%d Anmeldung', '%d Anmeldungen', count( $list['rows'] ), 'leadlotse' ),
				count( $list['rows'] )
			)
		) . '</th>';
		echo '</tr></tfoot></table>';

		echo '<p><a href="' . esc_url( admin_url( 'admin.php?page=' . Menu::INBOX_SLUG ) ) . '">&larr; ' . esc_html__( 'Zurueck zu den Anfragen', 'leadlotse' ) . '</a></p>';
		echo '</div>';
	}

	/**
	 * Export-Handler (admin-post.php): liefert die CSV-Datei aus.
	 *
	 * @return void
	 */
	public function handle_export(): void {
		if ( ! current_user_can( 'hs_view_entries' ) ) {
			wp_die( esc_html__( 'Sie haben keine Berechtigung, Anfragen einzusehen.', 'leadlotse' ) );
		}
		check_admin_referer( self::EXPORT_ACTION );

		$form_id    = isset( $_GET['form'] ) ? absint( wp_unslash( $_GET['form'] ) ) : 0;
		$definition = FormPostType::get_definition( $form_id );
		if ( null === $definition ) {
			wp_die( esc_html__( 'Dieses Formular wurde nicht gefunden.', 'leadlotse' ) );
		}

		$list = ( new ParticipantList( $this->entries ) )->for_form( $form_id, $definition );
		$csv  = ParticipantsExport::build( $list );

		nocache_headers();
		header( 'Content-Type: text/csv; charset=UTF-8' );
		header( 'Content-Disposition: attachment; filename="teilnehmer-' . $form_id . '-' . gmdate( 'Y-m-d' ) . '.csv"' );
		header( 'Content-Length: ' . strlen( $csv ) );

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSV-Datei-Download, kein HTML-Kontext.
		echo $csv;
		exit;
	}
}
