<?php

namespace SugarCalendarBookings\Support\Helpers;

/**
 * Slug collision-detection helper.
 *
 * Checks whether a URL slug conflicts with reserved WordPress paths,
 * registered post types, or post-type rewrite slugs.
 *
 * @since 1.5.0
 */
class Slug {

	/**
	 * Reserved WordPress paths that cannot be used as custom slugs.
	 *
	 * @since 1.5.0
	 */
	const RESERVED = [
		'wp-admin',
		'wp-login',
		'feed',
		'comments',
		'trackback',
		'page',
		'category',
		'tag',
		'author',
	];

	/**
	 * Check if a slug is reserved.
	 *
	 * @since 1.5.0
	 *
	 * @param string $slug The slug to check.
	 *
	 * @return bool True if reserved, false otherwise.
	 */
	public static function is_reserved( string $slug ): bool {

		return in_array( $slug, self::RESERVED, true );
	}

	/**
	 * Check if a slug is taken.
	 *
	 * @since 1.5.0
	 *
	 * @param string $slug The slug to check.
	 *
	 * @return bool True if taken, false otherwise.
	 */
	public static function is_taken( string $slug ): bool {

		return self::get_collision_reason( $slug ) !== null;
	}

	/**
	 * Get the specific collision reason for a slug, if any.
	 *
	 * @since 1.5.0
	 *
	 * @param string $slug The slug to check.
	 *
	 * @return string|null Translatable error message, or null if no collision.
	 */
	public static function get_collision_reason( string $slug ): ?string {

		if ( self::is_reserved( $slug ) ) {
			return sprintf(
				/* translators: %1$s - slug value. */
				esc_html__( 'The slug "%1$s" is a reserved WordPress path. Please choose a different slug.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				esc_html( $slug )
			);
		}

		if ( post_type_exists( $slug ) ) {
			return sprintf(
				/* translators: %1$s - slug value. */
				esc_html__( 'The slug "%1$s" conflicts with a registered post type. Please choose a different slug.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				esc_html( $slug )
			);
		}

		foreach ( get_post_types( [], 'objects' ) as $post_type ) {
			$rewrite = $post_type->rewrite ?? false;

			if ( is_array( $rewrite ) && isset( $rewrite['slug'] ) && $rewrite['slug'] === $slug ) {
				return sprintf(
					/* translators: %1$s - slug value. */
					esc_html__( 'The slug "%1$s" conflicts with a post type URL path. Please choose a different slug.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					esc_html( $slug )
				);
			}
		}

		return null;
	}
}
