<?php

/**
 * Emoji picker data endpoint — the safe emoji set + the active locale's search keywords + the viewer's
 * quick shelf, plus a favorites bump. Auto-registered by 3/classes/api/api.php as /peepso/v1/emoji.
 *
 * GET  /peepso/v1/emoji            → { set:[{glyph,keywords,group}], groups:[…], quick:[…], search:bool }
 * GET  /peepso/v1/emoji?quick=1    → { quick:[…] } only (cheap refresh once the set is client-cached)
 * POST /peepso/v1/emoji {glyph}    → records one use of $glyph for the viewer, returns fresh { quick:[…] }
 *
 * The full payload is fetched once when the picker first opens (the set is ~1.2k glyphs); the client then
 * caches set/groups in localStorage and only re-fetches `quick`. Auth = any logged-in user; the glyph is
 * validated against the safe set before it is recorded.
 */
class PeepSo3_REST_V1_Endpoint_Emoji extends PeepSo3_REST_V1_Endpoint
{
	/** GET — the full picker payload (or just the quick shelf when ?quick is present). */
	public function read(WP_REST_Request $request)
	{
		if (!is_user_logged_in()) {
			return array('error' => 'auth');
		}

		if ($request->get_param('quick')) {
			return array('quick' => PeepSoEmoji::quick_shelf());
		}

		return PeepSoEmoji::data_for_client();
	}

	/** POST — bump the viewer's favorite count for $glyph; returns the refreshed quick shelf. */
	public function create(WP_REST_Request $request)
	{
		if (!is_user_logged_in()) {
			return array('error' => 'auth');
		}

		$glyph = (string) $request->get_param('glyph');
		if (!PeepSoEmoji::is_allowed($glyph)) {
			return array('error' => 'invalid');
		}

		PeepSoEmoji::bump_favorite($glyph);
		return array('success' => TRUE, 'quick' => PeepSoEmoji::quick_shelf());
	}

	protected function can_read()
	{
		return is_user_logged_in();
	}

	protected function can_create()
	{
		return is_user_logged_in();
	}
}
