<?php
/**
 * Author Management Subpage + Autoren-Metabox.
 *
 * Displays a subpage in the admin area to manage authors, plus a metabox on "boxyfy_tsprodukte"
 * for selecting those authors, and a frontend filter for showing an author box.
 *
 * @package Boxyfy
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

/* ---------------------------------------------
 * 1) Admin-Subpage: Autorenverwaltung
 * --------------------------------------------- */

/**
 * Fügt ein Untermenü für die Autorenverwaltung im Adminbereich hinzu.
 */
function boxyfy_add_autor_menu() {
	// Optional: Lizenzprüfung
	if ( function_exists( 'boxyfy_is_license_valid' ) && ! boxyfy_is_license_valid() ) {
		return;
	}

	add_submenu_page(
		'edit.php?post_type=boxyfy_tsprodukte',  // Parent-Slug (Menü "boxyfy_tsprodukte")
		__( 'Autorenverwaltung', 'boxyfy' ),
		__( 'Autoren-Profile', 'boxyfy' ),
		'manage_options',
		'boxyfy_autoren',
		'boxyfy_render_authors_page'
	);
}
add_action( 'admin_menu', 'boxyfy_add_autor_menu' );

/**
 * Rendert die Seite zur Autorenverwaltung (Admin-Seite).
 */
function boxyfy_render_authors_page() {
	$autoren = get_option( 'boxyfy_autoren_profiles', array() );

	// 1) Neuen Autor hinzufügen
	if ( isset( $_POST['boxyfy_new_author_submit'] ) && check_admin_referer( 'boxyfy_new_author_action', 'boxyfy_new_author_nonce' ) ) {
		$author_name      = isset( $_POST['author_name'] ) ? sanitize_text_field( wp_unslash( $_POST['author_name'] ) ) : '';
		$author_desc      = isset( $_POST['author_desc'] ) ? sanitize_textarea_field( wp_unslash( $_POST['author_desc'] ) ) : '';
		$author_expertise = isset( $_POST['author_expertise'] ) ? sanitize_text_field( wp_unslash( $_POST['author_expertise'] ) ) : '';
		$author_image     = isset( $_POST['author_image_url'] ) ? esc_url_raw( wp_unslash( $_POST['author_image_url'] ) ) : '';
		$author_standard  = isset( $_POST['author_standard'] ) ? 1 : 0;

		$autoren[] = array(
			'name'      => $author_name,
			'desc'      => $author_desc,
			'expertise' => $author_expertise,
			'image'     => $author_image,
			'standard'  => $author_standard,
		);
		update_option( 'boxyfy_autoren_profiles', $autoren );

		echo '<div class="notice notice-success"><p>' . esc_html__( 'Autor erfolgreich hinzugefügt!', 'boxyfy' ) . '</p></div>';
	}

	// 2) Autor löschen
	if ( isset( $_GET['delete_author'] ) && isset( $_GET['boxyfy_nonce'] ) ) {
		$delete_index = absint( wp_unslash( $_GET['delete_author'] ) );
		$nonce        = sanitize_text_field( wp_unslash( $_GET['boxyfy_nonce'] ) );

	if ( ! wp_verify_nonce( $nonce, 'boxyfy_authors_action' ) ) {
		wp_die( esc_html__( 'Sicherheitsüberprüfung fehlgeschlagen.', 'boxyfy' ) );
	}

	if ( isset( $autoren[ $delete_index ] ) ) {
		unset( $autoren[ $delete_index ] );
		$autoren = array_values( $autoren );
		update_option( 'boxyfy_autoren_profiles', $autoren );

		echo '<div class="notice notice-success"><p>' . esc_html__( 'Autor wurde gelöscht!', 'boxyfy' ) . '</p>		</div>';
	}
}


	// 3) Edit-Aktion (GET)
	$edit_index = null;

	if ( isset( $_GET['edit_author'], $_GET['boxyfy_nonce'] ) ) {
		$edit_index = absint( wp_unslash( $_GET['edit_author'] ) );
		$nonce      = sanitize_text_field( wp_unslash( $_GET['boxyfy_nonce'] ) );

		if ( ! wp_verify_nonce( $nonce, 'boxyfy_authors_action' ) ) {
		wp_die( esc_html__( 'Sicherheitsüberprüfung fehlgeschlagen.', 'boxyfy' ) );
		}
	}

	// 4) Autor bearbeiten und speichern (POST)
	if ( isset( $_POST['boxyfy_edit_author_submit'] ) && check_admin_referer( 'boxyfy_edit_author_action', 'boxyfy_edit_author_nonce' ) ) {
	$edit_index = isset( $_POST['edit_index'] ) ? absint( wp_unslash( $_POST['edit_index'] ) ) : null;

		if ( isset( $autoren[ $edit_index ] ) ) {
			$author_standard = isset( $_POST['author_standard'] ) ? 1 : 0;

			$autoren[ $edit_index ]['name']      = sanitize_text_field( wp_unslash( $_POST['author_name'] ) );
			$autoren[ $edit_index ]['desc']      = sanitize_textarea_field( wp_unslash( $_POST['author_desc'] ) );
			$autoren[ $edit_index ]['expertise'] = sanitize_text_field( wp_unslash( $_POST['author_expertise'] ) );
			$autoren[ $edit_index ]['image']     = esc_url_raw( wp_unslash( $_POST['author_image_url'] ) );
			$autoren[ $edit_index ]['standard']  = $author_standard;

			update_option( 'boxyfy_autoren_profiles', $autoren );

			echo '<div class="notice notice-success"><p>' . esc_html__( 'Autor erfolgreich aktualisiert!', 'boxyfy' ) . '</p></div>';
			$edit_index = null;
		}
	}

	?>
	<div class="wrap boxyfy-author-wrap">
		<h1><?php esc_html_e( 'Autorenverwaltung', 'boxyfy' ); ?></h1>
		<p>
			<?php esc_html_e( 'Hier kannst Du Autoren hinzufügen, bearbeiten oder entfernen.', 'boxyfy' ); ?><br>
			<?php esc_html_e( 'Diese Autoren kannst Du später auf Deinen Produktseiten durch Autorenboxen anzeigen lassen.', 'boxyfy' ); ?>
		</p>

		<?php if ( null !== $edit_index && isset( $autoren[ $edit_index ] ) ) : ?>
			<!-- Autor bearbeiten -->
			<?php $autor_edit = $autoren[ $edit_index ]; ?>
			<h2><?php esc_html_e( 'Autor bearbeiten', 'boxyfy' ); ?></h2>
			<form method="post" action="">
				<?php wp_nonce_field( 'boxyfy_edit_author_action', 'boxyfy_edit_author_nonce' ); ?>
				<input type="hidden" name="edit_index" value="<?php echo esc_attr( $edit_index ); ?>">

				<table class="form-table boxyfy-author-table">
					<tr>
						<th><label for="author_name"><?php esc_html_e( 'Autor-Name:', 'boxyfy' ); ?></label></th>
						<td>
							<input
								type="text"
								name="author_name"
								id="author_name"
								required
								class="boxyfy-author-input-wide"
								value="<?php echo esc_attr( $autor_edit['name'] ); ?>"
							>
						</td>
					</tr>
					<tr>
						<th><label for="author_image_url"><?php esc_html_e( 'Autor-Bild-URL:', 'boxyfy' ); ?></label></th>
						<td>
							<input
								type="text"
								name="author_image_url"
								id="author_image_url"
								class="boxyfy-author-input-wide"
								value="<?php echo esc_url( $autor_edit['image'] ); ?>"
								placeholder="https://..."
							>
							<br>
							<button
								type="button"
								class="button upload_image_button"
								data-target="#author_image_url"
							>
								<?php esc_html_e( 'Bild auswählen', 'boxyfy' ); ?>
							</button>
						</td>
					</tr>
					<tr>
						<th><label for="author_desc"><?php esc_html_e( 'Kurzbeschreibung:', 'boxyfy' ); ?></label></th>
						<td>
							<textarea
								name="author_desc"
								id="author_desc"
								class="boxyfy-author-textarea"
							><?php echo esc_textarea( $autor_edit['desc'] ); ?></textarea>
						</td>
					</tr>
					<tr>
						<th><label for="author_expertise"><?php esc_html_e( 'Expertise:', 'boxyfy' ); ?></label></th>
						<td>
							<input
								type="text"
								name="author_expertise"
								id="author_expertise"
								class="boxyfy-author-input-wide"
								value="<?php echo esc_attr( $autor_edit['expertise'] ); ?>"
								placeholder="<?php esc_attr_e( 'Fachgebiet/Spezialgebiet', 'boxyfy' ); ?>"
							>
						</td>
					</tr>
					<tr>
						<th><label for="author_standard"><?php esc_html_e( 'Standard-Autor:', 'boxyfy' ); ?></label></th>
						<td>
							<input
								type="checkbox"
								name="author_standard"
								id="author_standard"
								value="1"
								<?php checked( 1, $autor_edit['standard'] ); ?>
							>
						</td>
					</tr>
				</table>
				<?php submit_button( esc_html__( 'Änderungen speichern', 'boxyfy' ), 'primary', 'boxyfy_edit_author_submit' ); ?>
			</form>
			<hr>
		<?php endif; ?>

		<?php if ( null === $edit_index ) : ?>
			<!-- Neuen Autor hinzufügen -->
			<h2><?php esc_html_e( 'Neuen Autor hinzufügen', 'boxyfy' ); ?></h2>
			<form method="post" action="">
				<?php wp_nonce_field( 'boxyfy_new_author_action', 'boxyfy_new_author_nonce' ); ?>
				<table class="form-table boxyfy-author-table">
					<tr>
						<th><label for="author_name"><?php esc_html_e( 'Autor-Name:', 'boxyfy' ); ?></label></th>
						<td>
							<input
								type="text"
								name="author_name"
								id="author_name"
								required
								class="boxyfy-author-input-wide"
							>
						</td>
					</tr>
					<tr>
						<th><label for="author_image_url"><?php esc_html_e( 'Autor-Bild-URL:', 'boxyfy' ); ?></label></th>
						<td>
							<input
								type="text"
								name="author_image_url"
								id="author_image_url"
								class="boxyfy-author-input-wide"
								placeholder="https://..."
							>
							<br>
							<button
								type="button"
								class="button upload_image_button"
								data-target="#author_image_url"
							>
								<?php esc_html_e( 'Bild auswählen', 'boxyfy' ); ?>
							</button>
						</td>
					</tr>
					<tr>
						<th><label for="author_desc"><?php esc_html_e( 'Kurzbeschreibung:', 'boxyfy' ); ?></label></th>
						<td>
							<textarea
								name="author_desc"
								id="author_desc"
								class="boxyfy-author-textarea"
							></textarea>
						</td>
					</tr>
					<tr>
						<th><label for="author_expertise"><?php esc_html_e( 'Expertise:', 'boxyfy' ); ?></label></th>
						<td>
							<input
								type="text"
								name="author_expertise"
								id="author_expertise"
								class="boxyfy-author-input-wide"
								placeholder="<?php esc_attr_e( 'Fachgebiet/Spezialgebiet', 'boxyfy' ); ?>"
							>
						</td>
					</tr>
					<tr>
						<th><label for="author_standard"><?php esc_html_e( 'Standard-Autor:', 'boxyfy' ); ?></label></th>
						<td>
							<input
								type="checkbox"
								name="author_standard"
								id="author_standard"
								value="1"
							>
						</td>
					</tr>
				</table>
				<?php submit_button( esc_html__( 'Autor hinzufügen', 'boxyfy' ), 'primary', 'boxyfy_new_author_submit' ); ?>
			</form>
		<?php endif; ?>

		<hr>
		<h2><?php esc_html_e( 'Bereits angelegte Autoren', 'boxyfy' ); ?></h2>
		<?php if ( ! empty( $autoren ) ) : ?>
			<table class="widefat fixed striped boxyfy-author-tablelist">
				<thead>
					<tr>
						<th class="boxyfy-author-col-img"><?php esc_html_e( 'Bild', 'boxyfy' ); ?></th>
						<th><?php esc_html_e( 'Name', 'boxyfy' ); ?></th>
						<th><?php esc_html_e( 'Beschreibung', 'boxyfy' ); ?></th>
						<th><?php esc_html_e( 'Expertise', 'boxyfy' ); ?></th>
						<th><?php esc_html_e( 'Standard', 'boxyfy' ); ?></th>
						<th><?php esc_html_e( 'Aktionen', 'boxyfy' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php foreach ( $autoren as $index => $autor ) : ?>
						<tr>
							<td>
								<?php if ( ! empty( $autor['image'] ) ) : ?>
									<img
										src="<?php echo esc_url( $autor['image'] ); ?>"
										alt="<?php esc_attr_e( 'Autor-Bild', 'boxyfy' ); ?>"
										class="boxyfy-author-list-img"
									/>
								<?php else : ?>
									<?php esc_html_e( 'Kein Bild', 'boxyfy' ); ?>
								<?php endif; ?>
							</td>
							<td><?php echo esc_html( $autor['name'] ); ?></td>
							<td><?php echo esc_html( $autor['desc'] ); ?></td>
							<td><?php echo esc_html( $autor['expertise'] ); ?></td>
							<td><?php echo ! empty( $autor['standard'] ) ? esc_html__( 'Ja', 'boxyfy' ) : esc_html__( 'Nein', 'boxyfy' ); ?></td>
							<td>
								<?php
								$edit_link = add_query_arg(
									array(
										'page'         => 'boxyfy_autoren',
										'edit_author'  => $index,
										'boxyfy_nonce' => wp_create_nonce( 'boxyfy_authors_action' ),
									),
									admin_url( 'admin.php' )
								);
								$delete_link = add_query_arg(
									array(
										'page'          => 'boxyfy_autoren',
										'delete_author' => $index,
										'boxyfy_nonce'  => wp_create_nonce( 'boxyfy_authors_action' ),
									),
									admin_url( 'admin.php' )
								);
								?>
								<a href="<?php echo esc_url( $edit_link ); ?>" class="button button-primary">
									<?php esc_html_e( 'Bearbeiten', 'boxyfy' ); ?>
								</a>
								<a href="<?php echo esc_url( $delete_link ); ?>" class="button button-secondary" onclick="return confirm('<?php echo esc_js( __( 'Diesen Autor wirklich löschen?', 'boxyfy' ) ); ?>');">
									<?php esc_html_e( 'Löschen', 'boxyfy' ); ?>
								</a>
							</td>
						</tr>
					<?php endforeach; ?>
				</tbody>
			</table>
		<?php else : ?>
			<p><?php esc_html_e( 'Noch keine Autoren angelegt.', 'boxyfy' ); ?></p>
		<?php endif; ?>
	</div>
	<?php
}

/* ---------------------------------------------
 * 2) Metabox zum Auswählen der Autoren
 * --------------------------------------------- */

function boxyfy_add_author_metabox() {
	add_meta_box(
		'boxyfy_author_metabox',
		__( 'Autoren', 'boxyfy' ),
		'boxyfy_render_author_metabox',
		'boxyfy_tsprodukte',
		'side',
		'default'
	);
}
add_action( 'add_meta_boxes', 'boxyfy_add_author_metabox' );

function boxyfy_render_author_metabox( $post ) {
	$selected_authors = get_post_meta( $post->ID, '_boxyfy_selected_authors', true );
	if ( ! is_array( $selected_authors ) ) {
		$selected_authors = array();
	}
	$autoren = get_option( 'boxyfy_autoren_profiles', array() );

	// Wrapper-Klasse statt Inline-Style
	echo '<div class="boxyfy-author-metabox-list">';
	foreach ( $autoren as $index => $autor ) {
		$is_checked  = in_array( $index, $selected_authors, true );
		$autor_label = $autor['name'];
		if ( ! empty( $autor['standard'] ) ) {
			$autor_label .= ' (' . esc_html__( 'Standard-Autor', 'boxyfy' ) . ')';
		}

		// Label-Klasse statt style
		echo '<label class="boxyfy-author-metabox-item">';
		echo '<input type="checkbox" name="boxyfy_selected_authors[]" value="' . esc_attr( $index ) . '" ' . checked( true, $is_checked, false ) . '> ';
		echo esc_html( $autor_label );
		echo '</label>';
	}
	echo '</div>';

	$manage_link = add_query_arg(
		array(
			'page'         => 'boxyfy_autoren',
			'boxyfy_nonce' => wp_create_nonce( 'boxyfy_authors_action' ),
		),
		admin_url( 'admin.php' )
	);
	// Zusätzliche Klasse für den Button, falls gewünscht
	echo '<a href="' . esc_url( $manage_link ) . '" class="button button-secondary boxyfy-author-manage-link">';
	echo esc_html__( 'Autoren verwalten', 'boxyfy' ) . '</a>';

	wp_nonce_field( 'boxyfy_save_author_metabox', 'boxyfy_author_metabox_nonce' );
}

function boxyfy_save_author_metabox( $post_id ) {
	if (
		! isset( $_POST['boxyfy_author_metabox_nonce'] )
		|| ! wp_verify_nonce(
			sanitize_text_field( wp_unslash( $_POST['boxyfy_author_metabox_nonce'] ) ),
			'boxyfy_save_author_metabox'
		)
	) {
		return;
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}
	if ( 'boxyfy_tsprodukte' !== get_post_type( $post_id ) ) {
		return;
	}
	if ( isset( $_POST['boxyfy_selected_authors'] ) && is_array( $_POST['boxyfy_selected_authors'] ) ) {
		$selected_authors = array_map( 'intval', wp_unslash( $_POST['boxyfy_selected_authors'] ) );
		update_post_meta( $post_id, '_boxyfy_selected_authors', $selected_authors );
	} else {
		delete_post_meta( $post_id, '_boxyfy_selected_authors' );
	}
}
add_action( 'save_post', 'boxyfy_save_author_metabox' );

/* ---------------------------------------------
 * 3) Frontend: Autorenbox an den Inhalt hängen
 * --------------------------------------------- */

function boxyfy_display_authors_box( $content ) {
	global $boxyfy_authors_box_added;
	if ( $boxyfy_authors_box_added || 'boxyfy_tsprodukte' !== get_post_type() ) {
		return $content;
	}
	$post_id = get_the_ID();
	$selected_authors = get_post_meta( $post_id, '_boxyfy_selected_authors', true );
	if ( ! is_array( $selected_authors ) || empty( $selected_authors ) ) {
		return $content;
	}
	$autoren_profiles = get_option( 'boxyfy_autoren_profiles', array() );
	if ( false !== strpos( $content, 'class="autorenbox"' ) ) {
		return $content;
	}

	$authors_html = '<div class="autorenbox">';
	foreach ( $selected_authors as $author_index ) {
		if ( isset( $autoren_profiles[ $author_index ] ) ) {
			$autor = $autoren_profiles[ $author_index ];
			$authors_html .= '<div class="autor">';
			if ( ! empty( $autor['image'] ) ) {
				$authors_html .= '<img
					src="' . esc_url( $autor['image'] ) . '"
					alt="' . esc_attr( $autor['name'] ) . '"
					class="autor-image"
				>';
			}
			$authors_html .= '<strong>' . esc_html( $autor['name'] ) . '</strong><br>';
			$authors_html .= esc_html( $autor['desc'] ) . '<br>';
			$authors_html .= esc_html( $autor['expertise'] );
			$authors_html .= '</div>';
		}
	}
	$authors_html .= '</div>';

	$boxyfy_authors_box_added = true;
	return $content . $authors_html;
}
add_filter( 'the_content', 'boxyfy_display_authors_box', 15 );