<?php
/**
 * Per-user template favorites.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Templates;

final class TemplateFavorites {

	public const META = 'aura_builder_template_favorites';

	/**
	 * @return list<string>
	 */
	public static function list( ?int $user_id = null ): array {
		$uid = $user_id ?: get_current_user_id();
		if ( $uid <= 0 ) {
			return array();
		}
		$raw = get_user_meta( $uid, self::META, true );
		if ( ! is_array( $raw ) ) {
			return array();
		}
		return array_values(
			array_filter(
				array_map( 'strval', $raw ),
				static fn( $id ) => $id !== ''
			)
		);
	}

	public static function is_favorite( string $id, ?int $user_id = null ): bool {
		return in_array( $id, self::list( $user_id ), true );
	}

	/**
	 * @return list<string>
	 */
	public static function toggle( string $id, ?int $user_id = null ): array {
		$uid = $user_id ?: get_current_user_id();
		$id  = sanitize_text_field( $id );
		if ( $uid <= 0 || $id === '' ) {
			return array();
		}
		$list = self::list( $uid );
		$pos  = array_search( $id, $list, true );
		if ( $pos === false ) {
			$list[] = $id;
		} else {
			unset( $list[ $pos ] );
			$list = array_values( $list );
		}
		update_user_meta( $uid, self::META, $list );
		return $list;
	}
}
