<?php

namespace NeurogenesisTheme\Helpers;

defined( 'ABSPATH' ) || exit;

/**
 * Content layouts from assets/content/layouts.json.
 * Per-layout files live under assets/content/{layout-slug}/.
 */
final class ContentLayouts {

	private const MANIFEST_FILES = array( 'layouts.json', 'layout.json' );

	/** @var list<array<string, string>>|null */
	private static $layouts_cache = null;

	/**
	 * @return list<array<string, string>>
	 */
	public static function all(): array {
		if ( null !== self::$layouts_cache ) {
			return self::$layouts_cache;
		}

		$path = self::manifest_path();
		if ( null === $path ) {
			self::$layouts_cache = array();
			return self::$layouts_cache;
		}

		$raw  = file_get_contents( $path );
		$data = is_string( $raw ) ? json_decode( $raw, true ) : null;
		if ( ! is_array( $data ) || empty( $data['layouts'] ) || ! is_array( $data['layouts'] ) ) {
			self::$layouts_cache = array();
			return self::$layouts_cache;
		}

		$out = array();
		foreach ( $data['layouts'] as $layout ) {
			if ( ! is_array( $layout ) ) {
				continue;
			}
			$slug = sanitize_title( (string) ( $layout['layout-slug'] ?? '' ) );
			if ( '' === $slug ) {
				continue;
			}
			$out[] = array(
				'layout-name'        => (string) ( $layout['layout-name'] ?? $slug ),
				'layout-slug'        => $slug,
				'layout-description' => (string) ( $layout['layout-description'] ?? '' ),
				'layout-category'    => (string) ( $layout['layout-category'] ?? '' ),
				'layout-demo-url'    => esc_url_raw( (string) ( $layout['layout-demo-url'] ?? '' ) ),
			);
		}

		self::$layouts_cache = $out;
		return self::$layouts_cache;
	}

	public static function count(): int {
		return count( self::all() );
	}

	/**
	 * @return array<string, string>|null
	 */
	public static function find_by_slug( string $slug ): ?array {
		$slug = sanitize_title( $slug );
		if ( '' === $slug ) {
			return null;
		}
		foreach ( self::all() as $layout ) {
			if ( $layout['layout-slug'] === $slug ) {
				return $layout;
			}
		}

		return null;
	}

	/**
	 * Slug from ?layout= when valid; otherwise the sole layout if count is 1.
	 */
	public static function resolve_active_slug(): ?string {
		$requested = self::slug_from_request();
		if ( null !== $requested ) {
			return $requested;
		}
		if ( 1 === self::count() ) {
			$only = self::all()[0];
			return $only['layout-slug'];
		}

		return null;
	}

	/**
	 * Valid ?layout= slug or null.
	 */
	public static function slug_from_request(): ?string {
		if ( ! isset( $_GET['layout'] ) ) {
			return null;
		}
		$slug = sanitize_title( wp_unslash( (string) $_GET['layout'] ) );
		if ( '' === $slug ) {
			return null;
		}

		return self::find_by_slug( $slug ) ? $slug : null;
	}

	public static function content_dir( string $layout_slug ): string {
		$slug = sanitize_title( $layout_slug );
		if ( '' === $slug ) {
			return '';
		}

		return 'assets/content/' . $slug;
	}

	public static function content_file_path( string $layout_slug, string $filename ): string {
		$dir = self::content_dir( $layout_slug );
		if ( '' === $dir ) {
			return '';
		}

		return $dir . '/' . ltrim( $filename, '/' );
	}

	public static function content_file_uri( string $layout_slug, string $filename ): string {
		$path = self::content_file_path( $layout_slug, $filename );
		if ( '' === $path ) {
			return '';
		}

		return get_template_directory_uri() . '/' . $path;
	}

	/**
	 * Remember active layout for admin asset loading (admin_enqueue_scripts).
	 */
	public static function register_active_slug( ?string $slug = null ): void {
		if ( null === $slug ) {
			$slug = self::resolve_active_slug();
		}
		if ( is_string( $slug ) && '' !== $slug ) {
			neurogenesis_theme_registry_set( 'neurogenesis_theme.import.layout_slug', $slug );
		}
	}

	public static function registered_active_slug(): ?string {
		$slug = neurogenesis_theme_registry_get( 'neurogenesis_theme.import.layout_slug', '' );
		if ( is_string( $slug ) && '' !== $slug ) {
			return sanitize_title( $slug );
		}

		return self::resolve_active_slug();
	}

	/**
	 * Layout slug stored when starter content was previously imported (legacy / companion plugin).
	 */
	public static function imported_layout_slug(): ?string {
		$raw = ThemeOptions::get( ThemeOptions::CONTENT_IMPORTED, '' );
		if ( ! is_string( $raw ) || '' === $raw ) {
			return null;
		}
		$slug = sanitize_title( $raw );
		return '' !== $slug ? $slug : null;
	}

	private static function manifest_path(): ?string {
		$base = get_template_directory() . '/assets/content/';
		foreach ( self::MANIFEST_FILES as $file ) {
			$path = $base . $file;
			if ( is_readable( $path ) ) {
				return $path;
			}
		}

		return null;
	}
}
