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

namespace Hafenstudios\Kurato\Admin;

use Hafenstudios\Core\Core;
use Hafenstudios\Kurato\Db\ContactRepository;
use Hafenstudios\Kurato\Db\StageRepository;

defined( 'ABSPATH' ) || exit;

/**
 * Admin-Seite "Kontakte" (Etappe K2).
 *
 * Serverseitig gerenderte Liste (D3): Name, E-Mail, Pipeline-Stufe, Quelle,
 * Datum. Suche und Stufen-Filter ueber GET-Parameter. Leerer Zustand mit Hans.
 * Das Kanban-Board und das Kontaktprofil folgen in K3 (JS auf der REST-API).
 */
final class ContactsListPage {

	private ContactRepository $contacts;

	private StageRepository $stages;

	/**
	 * @param ContactRepository $contacts Kontakt-Repository.
	 * @param StageRepository   $stages   Stufen-Repository.
	 */
	public function __construct( ContactRepository $contacts, StageRepository $stages ) {
		$this->contacts = $contacts;
		$this->stages   = $stages;
	}

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

		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Nur Lese-Filter (Suche/Stufe/Seite), keine Statusaenderung.
		$paged    = isset( $_GET['paged'] ) ? max( 1, absint( wp_unslash( $_GET['paged'] ) ) ) : 1;
		$search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
		$stage_id = isset( $_GET['stage'] ) ? absint( wp_unslash( $_GET['stage'] ) ) : 0;
		// phpcs:enable

		$result = $this->contacts->query(
			array(
				'page'     => $paged,
				'per_page' => 25,
				'search'   => $search,
				'stage_id' => $stage_id,
			)
		);

		$stages    = $this->stages->all();
		$stage_map = array();
		foreach ( $stages as $stage ) {
			$stage_map[ $stage['id'] ] = $stage['label'];
		}

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

		$total = (int) $result['total'];
		if ( 0 === $total && '' === $search && 0 === $stage_id ) {
			$this->render_empty_state();
			echo '</div>';
			return;
		}

		$this->render_filters( $stages, $search, $stage_id );

		if ( 0 === $total ) {
			echo '<p>' . esc_html__( 'Keine Kontakte gefunden. Bitte passen Sie Suche oder Filter an.', 'kurato' ) . '</p>';
		} else {
			$this->render_table( $result['items'], $stage_map );
			$this->render_pagination(
				(int) ceil( $total / max( 1, (int) $result['per_page'] ) ),
				$paged,
				$search,
				$stage_id
			);
		}

		echo '</div>';
	}

	/**
	 * Suchfeld und Stufen-Filter.
	 *
	 * @param array<int, array<string, mixed>> $stages   Alle Stufen.
	 * @param string                           $search   Aktuelle Suche.
	 * @param int                              $stage_id Aktiver Stufen-Filter.
	 * @return void
	 */
	private function render_filters( array $stages, string $search, int $stage_id ): void {
		echo '<form method="get" class="hs-kurato-filters">';
		echo '<input type="hidden" name="page" value="kurato" />';

		echo '<select name="stage" aria-label="' . esc_attr__( 'Nach Stufe filtern', 'kurato' ) . '">';
		echo '<option value="0">' . esc_html__( 'Alle Stufen', 'kurato' ) . '</option>';
		foreach ( $stages as $stage ) {
			printf(
				'<option value="%1$d"%2$s>%3$s</option>',
				(int) $stage['id'],
				selected( $stage_id, (int) $stage['id'], false ),
				esc_html( $stage['label'] )
			);
		}
		echo '</select> ';

		echo '<input type="search" name="s" value="' . esc_attr( $search ) . '" placeholder="' . esc_attr__( 'Nach Name oder E-Mail suchen', 'kurato' ) . '" /> ';
		echo '<button type="submit" class="button">' . esc_html__( 'Filtern', 'kurato' ) . '</button>';
		echo '</form>';
	}

	/**
	 * Die Kontakttabelle.
	 *
	 * @param array<int, array<string, mixed>> $contacts  Kontakte.
	 * @param array<int, string>               $stage_map stage_id => Label.
	 * @return void
	 */
	private function render_table( array $contacts, array $stage_map ): void {
		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__( 'E-Mail', 'kurato' ) . '</th>';
		echo '<th scope="col">' . esc_html__( 'Stufe', 'kurato' ) . '</th>';
		echo '<th scope="col">' . esc_html__( 'Quelle', 'kurato' ) . '</th>';
		echo '<th scope="col">' . esc_html__( 'Hinzugefuegt', 'kurato' ) . '</th>';
		echo '</tr></thead><tbody>';

		foreach ( $contacts as $contact ) {
			$name = '' !== (string) $contact['display_name'] ? (string) $contact['display_name'] : (string) $contact['email'];
			if ( '' === $name ) {
				$name = __( '(ohne Namen)', 'kurato' );
			}
			$stage_label = null !== $contact['stage_id'] ? ( $stage_map[ $contact['stage_id'] ] ?? '' ) : '';
			$date        = get_date_from_gmt( (string) $contact['created_at'], (string) get_option( 'date_format', 'd.m.Y' ) );

			echo '<tr>';
			echo '<td><strong><a href="' . esc_url( ContactPage::url( (int) $contact['id'] ) ) . '">' . esc_html( $name ) . '</a></strong></td>';
			echo '<td>' . esc_html( (string) $contact['email'] ) . '</td>';
			echo '<td>';
			if ( '' !== $stage_label ) {
				echo '<span class="hs-stage-badge">' . esc_html( $stage_label ) . '</span>';
			} else {
				echo '<span class="hs-muted">' . esc_html__( 'ohne Stufe', 'kurato' ) . '</span>';
			}
			echo '</td>';
			echo '<td>' . esc_html( (string) $contact['source'] ) . '</td>';
			echo '<td>' . esc_html( $date ) . '</td>';
			echo '</tr>';
		}

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

	/**
	 * Leerer Zustand mit Hans.
	 *
	 * @return void
	 */
	private function render_empty_state(): void {
		$hans  = Core::instance()->hans();
		$image = $hans->is_enabled() ? $hans->image_url( 31 ) : '';

		echo '<div class="hs-kurato-empty" style="max-width:520px;margin:48px auto;text-align:center;">';
		if ( '' !== $image ) {
			echo '<img src="' . esc_url( $image ) . '" alt="" width="160" height="160" style="object-fit:contain;" loading="lazy" />';
		}
		echo '<h2>' . esc_html__( 'Noch keine Kontakte an Bord', 'kurato' ) . '</h2>';
		echo '<p>' . esc_html__( 'Sobald ueber Leadlotse Anfragen eingehen, laufen die Kontakte hier automatisch ein. Sie koennen Kontakte auch von Hand anlegen.', 'kurato' ) . '</p>';
		echo '</div>';
	}

	/**
	 * Seitennavigation, die Suche und Stufen-Filter beibehaelt.
	 *
	 * @param int    $total_pages Gesamtseiten.
	 * @param int    $current     Aktuelle Seite.
	 * @param string $search      Suche.
	 * @param int    $stage_id    Stufen-Filter.
	 * @return void
	 */
	private function render_pagination( int $total_pages, int $current, string $search, int $stage_id ): void {
		if ( $total_pages <= 1 ) {
			return;
		}
		$base = add_query_arg(
			array(
				'page'  => 'kurato',
				's'     => '' !== $search ? $search : false,
				'stage' => $stage_id > 0 ? $stage_id : false,
				'paged' => '%#%',
			),
			admin_url( 'admin.php' )
		);
		$links = paginate_links(
			array(
				'base'    => $base,
				'format'  => '',
				'current' => $current,
				'total'   => $total_pages,
			)
		);
		if ( $links ) {
			echo '<div class="tablenav"><div class="tablenav-pages">' . wp_kses_post( $links ) . '</div></div>';
		}
	}
}
