<?php
/**
 * Boxyfy Product Ranking Metabox.
 *
 * Dieses Plugin fügt eine Metabox für den Post-Typ „boxyfy_tsprodukte“ hinzu,
 * in der das Produkt-Ranking innerhalb einer Kategorie angezeigt, bearbeitet
 * und via Drag-and-Drop umsortiert werden kann.
 *
 * @package Boxyfy
 */

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

/**
 * Enqueue CSS/JS nur für tsprodukte-Editing Screens.
 */
add_action( 'admin_enqueue_scripts', 'boxyfy_enqueue_product_ranking_assets_debug' );
function boxyfy_enqueue_product_ranking_assets_debug( $hook ) {
	// Nur auf Edit-/New-Seiten
	if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
		return;
	}

	// Post-Typ prüfen
	$screen = get_current_screen();
	if ( ! $screen || $screen->post_type !== 'boxyfy_tsprodukte' ) {
		return;
	}

	// CSS
	wp_enqueue_style(
		'boxyfy-metabox-ranking-style',
		plugins_url( 'assets/css/metabox_produkt_ranking.css', BOXYFY_PLUGIN_FILE ),
		array(),
		'1.0.0'
	);

	// jQuery UI
	wp_enqueue_script( 'jquery-ui-sortable' );

	// Haupt-Script
	wp_enqueue_script(
		'boxyfy-metabox-ranking-script',
		plugins_url( 'assets/js/metabox_produkt_ranking.js', BOXYFY_PLUGIN_FILE ),
		array( 'jquery', 'jquery-ui-sortable' ),
		'1.0.0',
		true
	);

	global $post;
	if ( isset( $post->ID ) ) {
		wp_add_inline_script(
			'boxyfy-metabox-ranking-script',
			'const boxyfyRankingData = ' . wp_json_encode(
				array(
					'ajaxUrl'            => admin_url( 'admin-ajax.php' ),
					'updateRankingNonce' => wp_create_nonce( 'update_product_rankings' ),
					'removeRankingNonce' => wp_create_nonce( 'remove_product_ranking' ),
					'currentPostId'      => (int) $post->ID,
				)
			) . ';',
			'before'
		);
	}
}

/**
 * Metabox registrieren.
 */
function boxyfy_product_ranking_metabox() {
	add_meta_box(
		'boxyfy_product_ranking',
		__( 'Boxyfy: Produkt-Ranking', 'boxyfy' ),
		'boxyfy_product_ranking_metabox_callback',
		'boxyfy_tsprodukte',
		'normal',
		'high'
	);
}
add_action( 'add_meta_boxes', 'boxyfy_product_ranking_metabox' );

/**
 * Callback-Funktion.
 *
 * @param WP_Post $post Aktueller Post.
 */
function boxyfy_product_ranking_metabox_callback( $post ) {

	// Kategorie holen und Rankings normalisieren
	$terms = wp_get_post_terms( $post->ID, 'boxyfy_tsprodukt_kategorie' );
	if ( $terms && ! is_wp_error( $terms ) && ! empty( $terms ) ) {
		$category = $terms[0];
		boxyfy_normalize_product_rankings( $category->term_id );
	}

	$ranking_value = get_post_meta( $post->ID, 'tsprodukt_ranking', true );
	wp_nonce_field( 'boxyfy_save_product_ranking', 'boxyfy_product_ranking_nonce' );

	// Eingabefeld
	echo '<label for="boxyfy_product_ranking_field">' . esc_html__( 'Produkt-Ranking eingeben:', 'boxyfy' ) . '</label> ';
	echo '<input type="number" id="boxyfy_product_ranking_field" class="boxyfy-ranking-input" name="boxyfy_product_ranking_field" value="' . esc_attr( $ranking_value ) . '" min="1" /> ';
	echo '<span class="boxyfy-ranking-hint">' . esc_html__( 'z.B. 3 für Platz 3', 'boxyfy' ) . '</span>';

	// Produkte derselben Kategorie auflisten
	if ( $terms && ! is_wp_error( $terms ) && ! empty( $terms ) ) {
		$category = $terms[0];

		$args  = array(
			'post_type'      => 'boxyfy_tsprodukte',
			'posts_per_page' => -1,
			'orderby'        => 'meta_value_num',
			'meta_key'       => 'tsprodukt_ranking',
			'order'          => 'ASC',
			'tax_query'      => array(
				array(
					'taxonomy' => 'boxyfy_tsprodukt_kategorie',
					'field'    => 'term_id',
					'terms'    => $category->term_id,
				),
			),
		);
		$query = new WP_Query( $args );

		if ( $query->have_posts() ) {
			echo '<p>' . sprintf(
				/* translators: %s: category name */
				esc_html__( 'Aktuelle Platzierungen in der Kategorie: %s.', 'boxyfy' ),
				'<strong>' . esc_html( $category->name ) . '</strong>'
			) . ' ';
			echo esc_html__( 'Das Ranking kann per Drag-and-Drop mit globaler Wirkung neu sortiert werden.', 'boxyfy' ) . ' ';
			echo esc_html__( 'Darüber hinaus kannst du die Bewertungen aller Produkte (außer dem aktuellen) hier direkt ändern.', 'boxyfy' ) . ' ';
			echo esc_html__( 'Die Produktbewertung des aktuellen Produkts nimmst du wie gewohnt rechts in der Sidebar unter „Produktbewertung“ vor.', 'boxyfy' ) . '</p>';

			echo '<ul id="ranking-list" class="boxyfy-ranking-list">';

			while ( $query->have_posts() ) {
				$query->the_post();
				$product_ranking = get_post_meta( get_the_ID(), 'tsprodukt_ranking', true );
				$bewertung       = get_post_meta( get_the_ID(), '_tsprodukt_bewertung', true );
				$product_title   = get_the_title();
				$short_title     = ( strlen( $product_title ) > 55 ) ? substr( $product_title, 0, 55 ) . '…' : $product_title;
				$product_link    = get_edit_post_link( get_the_ID() );
				$is_current      = ( get_the_ID() === $post->ID );

				$classes   = array( 'boxyfy-ranking-item', $is_current ? 'boxyfy-current-product' : 'boxyfy-other-product' );
				$classes[] = ( 1 === (int) $product_ranking ) ? 'boxyfy-border-gold' :
					( 2 === (int) $product_ranking ? 'boxyfy-border-silver' :
					( 3 === (int) $product_ranking ? 'boxyfy-border-bronze' : 'boxyfy-border-none' ) );

				echo '<li data-post-id="' . esc_attr( get_the_ID() ) . '" data-ranking="' . esc_attr( $product_ranking ) . '" class="' . esc_attr( implode( ' ', $classes ) ) . '">';
				echo '<span class="boxyfy-ranking-title">';
				echo esc_html__( 'Platz', 'boxyfy' ) . ' <span class="current-ranking">' . esc_html( $product_ranking ) . '</span>: ';
				echo '<a href="' . esc_url( $product_link ) . '">' . esc_html( $short_title ) . '</a>';
				echo '</span>';

				echo '<span class="boxyfy-product-rating-wrapper">';
				if ( $is_current ) {
					echo esc_html__( 'Bewertung:', 'boxyfy' ) . ' <input type="number" disabled="disabled" value="' . esc_attr( $bewertung ) . '" class="boxyfy-product-rating-disabled" min="0" /> ' . esc_html__( 'Punkte', 'boxyfy' );
				} else {
					echo esc_html__( 'Bewertung:', 'boxyfy' ) . ' <input type="number" class="product-rating-input" data-post-id="' . esc_attr( get_the_ID() ) . '" value="' . esc_attr( $bewertung ) . '" min="0" /> ' . esc_html__( 'Punkte', 'boxyfy' );
				}
				echo '</span>';

				echo '<input type="hidden" class="ranking-hidden-input" name="boxyfy_product_rankings[' . esc_attr( get_the_ID() ) . ']" value="' . esc_attr( $product_ranking ) . '" />';
				echo '<span class="drag-handle">☰</span>';
				echo '</li>';
			}
			echo '</ul>';
		} else {
			echo '<p>' . esc_html__( 'Keine anderen Produkte in dieser Kategorie mit einem Ranking gefunden.', 'boxyfy' ) . '</p>';
		}
		wp_reset_postdata();
	} else {
		echo '<p>' . esc_html__( 'Bitte vergebe zunächst eine Produktkategorie (rechts), um die Platzierung(en) zu sehen.', 'boxyfy' ) . '</p>';
	}

	// Button „Produkt aus Ranking entfernen“
	wp_nonce_field( 'remove_product_ranking', 'boxyfy_remove_product_ranking_nonce' );
	echo '<p class="boxyfy-remove-product-btn-wrapper">';
	echo '<button id="remove-product-ranking" type="button" class="boxyfy-remove-product-btn">';
	echo '<svg fill="#ffffff" width="19" height="19" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" stroke="#ffffff" class="boxyfy-remove-icon"><path d="M18.8,16l5.5-5.5c0.8-0.8,0.8-2,0-2.8l0,0C24,7.3,23.5,7,23,7c-0.5,0-1,0.2-1.4,0.6L16,13.2l-5.5-5.5 c-0.8-0.8-2.1-0.8-2.8,0C7.3,8,7,8.5,7,9.1s0.2,1,0.6,1.4l5.5,5.5l-5.5,5.5C7.3,21.9,7,22.4,7,23c0,0.5,0.2,1,0.6,1.4 C8,24.8,8.5,25,9,25c0.5,0,1-0.2,1.4-0.6l5.5-5.5l5.5,5.5c0.8,0.8,2.1,0.8,2.8,0c0.8-0.8,0.8-2.1,0-2.8L18.8,16z"/></svg>';
	echo esc_html__( 'aktuelles Produkt aus Ranking entfernen', 'boxyfy' );
	echo '</button></p>';
}

/* ---------- AJAX: RANKINGS SPEICHERN ---------- */
add_action( 'wp_ajax_update_product_rankings', 'boxyfy_update_product_rankings' );
function boxyfy_update_product_rankings() {

	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'update_product_rankings' ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Ungültige Anfrage (Nonce fehlerhaft).', 'boxyfy' ) ) );
	}

	$rankings = isset( $_POST['rankings'] ) && is_array( $_POST['rankings'] )
		? array_map( 'sanitize_text_field', wp_unslash( $_POST['rankings'] ) )
		: array();

	$post_ids = array_keys( $rankings );
	if ( empty( $post_ids ) ) {
		wp_send_json_error( esc_html__( 'Keine gültigen Produkt-IDs.', 'boxyfy' ) );
	}

	$first_product_id = $post_ids[0];
	$terms            = wp_get_post_terms( $first_product_id, 'boxyfy_tsprodukt_kategorie' );
	if ( ! $terms || is_wp_error( $terms ) || empty( $terms ) ) {
		wp_send_json_error( esc_html__( 'Produkt hat keine gültige Kategorie.', 'boxyfy' ) );
	}
	$category = $terms[0];

	foreach ( $post_ids as $pid ) {
		$product_terms = wp_get_post_terms( $pid, 'boxyfy_tsprodukt_kategorie' );
		if ( ! $product_terms || is_wp_error( $product_terms ) || empty( $product_terms ) || $product_terms[0]->term_id !== $category->term_id ) {
			wp_send_json_error( esc_html__( 'Alle Produkte müssen zur gleichen Kategorie gehören.', 'boxyfy' ) );
		}
	}

	asort( $rankings, SORT_NUMERIC );
	$normalized_rankings = array();
	$current_rank        = 1;
	foreach ( $rankings as $post_id => $rank ) {
		$normalized_rankings[ $post_id ] = $current_rank;
		$current_rank++;
	}

	foreach ( $normalized_rankings as $post_id => $rank ) {
		update_post_meta( $post_id, 'tsprodukt_ranking', intval( $rank ) );
	}

	wp_send_json_success( esc_html__( 'Rankings aktualisiert.', 'boxyfy' ) );
}

/* ---------- STANDARD-SAVE ---------- */
add_action( 'save_post_boxyfy_tsprodukte', 'boxyfy_save_product_ranking' );
function boxyfy_save_product_ranking( $post_id ) {

	if ( ! isset( $_POST['boxyfy_product_ranking_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['boxyfy_product_ranking_nonce'] ) ), 'boxyfy_save_product_ranking' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$terms = wp_get_post_terms( $post_id, 'boxyfy_tsprodukt_kategorie' );
	if ( ! $terms || is_wp_error( $terms ) || empty( $terms ) ) {
		return;
	}
	$category = $terms[0];

	$new_ranking = isset( $_POST['boxyfy_product_ranking_field'] ) ? intval( $_POST['boxyfy_product_ranking_field'] ) : null;
	if ( $new_ranking ) {

		$args   = array(
			'post_type'      => 'boxyfy_tsprodukte',
			'posts_per_page' => -1,
			'orderby'        => 'meta_value_num',
			'meta_key'       => 'tsprodukt_ranking',
			'order'          => 'ASC',
			'tax_query'      => array(
				array(
					'taxonomy' => 'boxyfy_tsprodukt_kategorie',
					'field'    => 'term_id',
					'terms'    => $category->term_id,
				),
			),
			'post__not_in'   => array( $post_id ),
		);
		$query = new WP_Query( $args );

		$existing_rankings = array();
		if ( $query->have_posts() ) {
			while ( $query->have_posts() ) {
				$query->the_post();
				$rank = intval( get_post_meta( get_the_ID(), 'tsprodukt_ranking', true ) );
				if ( $rank > 0 ) {
					$existing_rankings[] = $rank;
				}
			}
			wp_reset_postdata();
		}

		if ( in_array( $new_ranking, $existing_rankings, true ) ) {
			foreach ( $query->posts as $other_post ) {
				$other_rank = intval( get_post_meta( $other_post->ID, 'tsprodukt_ranking', true ) );
				if ( $other_rank >= $new_ranking ) {
					update_post_meta( $other_post->ID, 'tsprodukt_ranking', $other_rank + 1 );
				}
			}
		}

		update_post_meta( $post_id, 'tsprodukt_ranking', $new_ranking );
		boxyfy_normalize_product_rankings( $category->term_id );
	}
}

/* ---------- RANKING NORMALISIEREN BEIM LÖSCHEN ---------- */
add_action( 'before_delete_post', 'boxyfy_normalize_rankings_on_delete' );
function boxyfy_normalize_rankings_on_delete( $post_id ) {
	if ( 'boxyfy_tsprodukte' !== get_post_type( $post_id ) ) {
		return;
	}
	$terms = wp_get_post_terms( $post_id, 'boxyfy_tsprodukt_kategorie' );
	if ( ! $terms || is_wp_error( $terms ) || empty( $terms ) ) {
		return;
	}
	boxyfy_normalize_product_rankings( $terms[0]->term_id );
}

/* ---------- RANKINGS NORMALISIEREN ---------- */
function boxyfy_normalize_product_rankings( $category_id ) {
	$args  = array(
		'post_type'      => 'boxyfy_tsprodukte',
		'posts_per_page' => -1,
		'orderby'        => 'meta_value_num',
		'meta_key'       => 'tsprodukt_ranking',
		'order'          => 'ASC',
		'tax_query'      => array(
			array(
				'taxonomy' => 'boxyfy_tsprodukt_kategorie',
				'field'    => 'term_id',
				'terms'    => $category_id,
			),
		),
	);
	$query = new WP_Query( $args );

	if ( $query->have_posts() ) {
		$current_rank = 1;
		while ( $query->have_posts() ) {
			$query->the_post();
			update_post_meta( get_the_ID(), 'tsprodukt_ranking', $current_rank );
			$current_rank++;
		}
		wp_reset_postdata();
	}
}

/* ---------- AJAX: BEWERTUNG DIREKT AKTUALISIEREN ---------- */
add_action( 'wp_ajax_update_product_rating', 'boxyfy_update_product_rating' );
function boxyfy_update_product_rating() {

	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'update_product_rankings' ) ) {
		wp_send_json_error( esc_html__( 'Ungültige Anfrage (Nonce fehlerhaft).', 'boxyfy' ) );
	}

	if ( ! isset( $_POST['post_id'] ) || ! isset( $_POST['new_rating'] ) ) {
		wp_send_json_error( esc_html__( 'Unvollständige Daten.', 'boxyfy' ) );
	}

	$post_id    = intval( $_POST['post_id'] );
	$new_rating = intval( $_POST['new_rating'] );

	if ( $new_rating < 0 ) {
		wp_send_json_error( esc_html__( 'Bewertung darf nicht negativ sein.', 'boxyfy' ) );
	}

	if ( 'boxyfy_tsprodukte' !== get_post_type( $post_id ) ) {
		wp_send_json_error( esc_html__( 'Ungültiger Post-Typ.', 'boxyfy' ) );
	}

	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error( esc_html__( 'Keine Berechtigung, diesen Beitrag zu bearbeiten.', 'boxyfy' ) );
	}

	update_post_meta( $post_id, '_tsprodukt_bewertung', $new_rating );
	wp_send_json_success( esc_html__( 'Bewertung aktualisiert.', 'boxyfy' ) );
}

/* ---------- AJAX: PRODUKT AUS RANKING ENTFERNEN ---------- */
add_action( 'wp_ajax_remove_product_ranking', 'boxyfy_remove_product_ranking' );
function boxyfy_remove_product_ranking() {

	$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
	if ( ! wp_verify_nonce( $nonce, 'remove_product_ranking' ) ) {
		wp_send_json_error( esc_html__( 'Ungültige Anfrage (Nonce fehlerhaft).', 'boxyfy' ) );
	}

	if ( ! isset( $_POST['post_id'] ) ) {
		wp_send_json_error( esc_html__( 'Keine Produkt-ID übermittelt.', 'boxyfy' ) );
	}
	$post_id = intval( $_POST['post_id'] );

	if ( 'boxyfy_tsprodukte' !== get_post_type( $post_id ) ) {
		wp_send_json_error( esc_html__( 'Ungültiger Post-Typ.', 'boxyfy' ) );
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		wp_send_json_error( esc_html__( 'Keine Berechtigung, diesen Beitrag zu bearbeiten.', 'boxyfy' ) );
	}

	delete_post_meta( $post_id, 'tsprodukt_ranking' );

	$terms = wp_get_post_terms( $post_id, 'boxyfy_tsprodukt_kategorie' );
	if ( $terms && ! is_wp_error( $terms ) && ! empty( $terms ) ) {
		boxyfy_normalize_product_rankings( $terms[0]->term_id );
	}

	wp_send_json_success( esc_html__( 'Produkt wurde aus dem Ranking entfernt.', 'boxyfy' ) );
}