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

namespace Hafenstudios\Kurato\Admin;

use Hafenstudios\Kurato\Db\ListRepository;

defined( 'ABSPATH' ) || exit;

/**
 * Admin-Seite "Listen" (Etappe K4a).
 *
 * Serverseitige Verwaltung der Verteilerlisten (D3): Tabelle mit Abonnentenzahl,
 * Anlegen ueber ein Formular, Loeschen ueber einen nonce-gesicherten Link. Die
 * Default-Newsletter-Liste ist nicht loeschbar. Aenderungen laufen ueber
 * admin-post (kein JS noetig); Capability hs_manage_contacts.
 */
final class ListsPage {

	public const SLUG            = 'kurato-lists';
	public const ACTION_SAVE     = 'kurato_save_list';
	public const ACTION_DELETE   = 'kurato_delete_list';

	private ListRepository $lists;

	/**
	 * @param ListRepository $lists Listen-Repository.
	 */
	public function __construct( ListRepository $lists ) {
		$this->lists = $lists;
	}

	/**
	 * Registriert die admin-post-Handler.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'admin_post_' . self::ACTION_SAVE, array( $this, 'handle_save' ) );
		add_action( 'admin_post_' . self::ACTION_DELETE, array( $this, 'handle_delete' ) );
	}

	/**
	 * Rendert die Seite.
	 *
	 * @return void
	 */
	public function render(): void {
		if ( ! current_user_can( 'hs_view_contacts' ) ) {
			wp_die( esc_html__( 'Sie haben keine Berechtigung, Listen einzusehen.', 'kurato' ) );
		}

		$can_manage = current_user_can( 'hs_manage_contacts' );
		$notice     = isset( $_GET['msg'] ) ? sanitize_key( wp_unslash( $_GET['msg'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nur Anzeige einer Statusmeldung nach Redirect.

		echo '<div class="wrap hs-kurato-lists">';
		echo '<h1 class="wp-heading-inline">' . esc_html__( 'Listen', 'kurato' ) . '</h1>';
		echo '<hr class="wp-header-end" />';

		if ( 'saved' === $notice ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Liste gespeichert.', 'kurato' ) . '</p></div>';
		} elseif ( 'deleted' === $notice ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Liste geloescht.', 'kurato' ) . '</p></div>';
		}

		$this->render_table();

		if ( $can_manage ) {
			$this->render_create_form();
		}

		echo '</div>';
	}

	/**
	 * Die Listentabelle.
	 *
	 * @return void
	 */
	private function render_table(): void {
		$lists = $this->lists->all();

		if ( array() === $lists ) {
			echo '<p>' . esc_html__( 'Noch keine Listen. Legen Sie unten Ihre erste Liste an.', 'kurato' ) . '</p>';
			return;
		}

		echo '<table class="wp-list-table widefat fixed striped">';
		echo '<thead><tr>';
		echo '<th scope="col">' . esc_html__( 'Name', 'kurato' ) . '</th>';
		echo '<th scope="col">' . esc_html__( 'Bestaetigte Abonnenten', 'kurato' ) . '</th>';
		echo '<th scope="col">' . esc_html__( 'Double-Opt-in', 'kurato' ) . '</th>';
		echo '<th scope="col">' . esc_html__( 'Aktion', 'kurato' ) . '</th>';
		echo '</tr></thead><tbody>';

		$can_manage = current_user_can( 'hs_manage_contacts' );
		foreach ( $lists as $list ) {
			$count      = $this->lists->subscriber_count( (int) $list['id'], 'confirmed' );
			$is_default = ListRepository::DEFAULT_SLUG === $list['slug'];

			echo '<tr>';
			echo '<td><strong>' . esc_html( $list['label'] ) . '</strong>';
			if ( '' !== (string) $list['description'] ) {
				echo '<br /><span class="hs-muted">' . esc_html( $list['description'] ) . '</span>';
			}
			echo '</td>';
			echo '<td>' . esc_html( number_format_i18n( $count ) ) . '</td>';
			echo '<td>' . ( $list['doi_required'] ? esc_html__( 'Ja', 'kurato' ) : esc_html__( 'Nein', 'kurato' ) ) . '</td>';
			echo '<td>';
			if ( $can_manage && ! $is_default ) {
				$url = wp_nonce_url(
					add_query_arg(
						array( 'action' => self::ACTION_DELETE, 'list' => (int) $list['id'] ),
						admin_url( 'admin-post.php' )
					),
					self::ACTION_DELETE . '_' . $list['id']
				);
				echo '<a href="' . esc_url( $url ) . '" class="submitdelete" onclick="return confirm(\'' . esc_js( __( 'Liste und ihre Abos wirklich loeschen?', 'kurato' ) ) . '\');">' . esc_html__( 'Loeschen', 'kurato' ) . '</a>';
			} elseif ( $is_default ) {
				echo '<span class="hs-muted">' . esc_html__( 'Standardliste', 'kurato' ) . '</span>';
			}
			echo '</td>';
			echo '</tr>';
		}

		echo '</tbody></table>';
	}

	/**
	 * Formular zum Anlegen einer Liste.
	 *
	 * @return void
	 */
	private function render_create_form(): void {
		echo '<h2>' . esc_html__( 'Neue Liste', 'kurato' ) . '</h2>';
		echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '" class="hs-kurato-list-form">';
		echo '<input type="hidden" name="action" value="' . esc_attr( self::ACTION_SAVE ) . '" />';
		wp_nonce_field( self::ACTION_SAVE );

		echo '<p><label>' . esc_html__( 'Name', 'kurato' ) . '<br /><input type="text" name="label" required class="regular-text" /></label></p>';
		echo '<p><label>' . esc_html__( 'Beschreibung (optional)', 'kurato' ) . '<br /><textarea name="description" rows="2" class="large-text"></textarea></label></p>';
		echo '<p><label><input type="checkbox" name="doi_required" value="1" checked /> ' . esc_html__( 'Double-Opt-in verlangen (empfohlen)', 'kurato' ) . '</label></p>';
		echo '<p><button type="submit" class="button button-primary">' . esc_html__( 'Liste anlegen', 'kurato' ) . '</button></p>';
		echo '</form>';
	}

	/**
	 * Speichert eine neue Liste (admin-post).
	 *
	 * @return void
	 */
	public function handle_save(): void {
		if ( ! current_user_can( 'hs_manage_contacts' ) ) {
			wp_die( esc_html__( 'Keine Berechtigung.', 'kurato' ) );
		}
		check_admin_referer( self::ACTION_SAVE );

		$label = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : '';
		$desc  = isset( $_POST['description'] ) ? sanitize_textarea_field( wp_unslash( $_POST['description'] ) ) : '';
		$doi   = ! empty( $_POST['doi_required'] );

		if ( '' !== $label ) {
			$this->lists->create( $label, $desc, $doi );
		}

		$this->redirect( 'saved' );
	}

	/**
	 * Loescht eine Liste (admin-post). Die Default-Liste ist geschuetzt.
	 *
	 * @return void
	 */
	public function handle_delete(): void {
		if ( ! current_user_can( 'hs_manage_contacts' ) ) {
			wp_die( esc_html__( 'Keine Berechtigung.', 'kurato' ) );
		}
		$id = isset( $_GET['list'] ) ? absint( wp_unslash( $_GET['list'] ) ) : 0;
		check_admin_referer( self::ACTION_DELETE . '_' . $id );

		$list = $this->lists->get( $id );
		if ( null !== $list && ListRepository::DEFAULT_SLUG !== $list['slug'] ) {
			$this->lists->delete( $id );
		}

		$this->redirect( 'deleted' );
	}

	/**
	 * Leitet zurueck auf die Listen-Seite mit Statusmeldung.
	 *
	 * @param string $msg Statuscode.
	 * @return void
	 */
	private function redirect( string $msg ): void {
		wp_safe_redirect( add_query_arg( array( 'page' => self::SLUG, 'msg' => $msg ), admin_url( 'admin.php' ) ) );
		exit;
	}
}
