<?php

class vB5_Frontend_Controller_Json extends vB5_Frontend_Controller
{
	// Important reminder: add new actions to vB5_Route_Json::$controllerActionAllowlist

	public function __construct()
	{
		parent::__construct();

		// Taken from Api_InterfaceLight::init() -- disable notices/warnings as
		// they'll just break any JSON output.
		$config = vB5_Config::instance();
		if (!$config->report_all_ajax_errors)
		{
			vB::silentWarnings();
		}
	}

	private function returnJson(mixed $data) : void
	{
		if (is_array($data))
		{
			$data = json_encode($data, true);
		}

		//This function needs to be kept in sync with the implmentation in applicationlight.php
		if (headers_sent($file, $line))
		{
			throw new Exception("Cannot send response, headers already sent. File: $file Line: $line");
		}

		header('Content-Type: application/manifest+json;');
		echo $data;
	}

	public function actionManifest()
	{
		//the api init can redirect.  We need to make sure that happens before we echo anything
		$api = Api_InterfaceAbstract::instance();


		//This function needs to be kept in sync with the implmentation in applicationlight.php
		if (headers_sent($file, $line))
		{
			throw new Exception("Cannot send response, headers already sent. File: $file Line: $line");
		}

		// we're using json, so we need UTF-8, but the API method should've already guaranteed that.
		// Skip the conversion here. (Also one reason we're avoiding prepJson(), other being so we can
		// customize the header)
		$check = $api->callApi('site', 'getAppManifest');
		$manifestJson = $check['manifest'] ?? [];
		$this->returnJson($manifestJson);
	}

	// this is a GET because this is meant for when we don't have a security token and need to fetch one to make
	// a subsequent POST.
	public function actionGetSecurityToken()
	{
		$api = Api_InterfaceAbstract::instance();

		// Warning: session refresh probably won't work here, because the serviceworker that calls this cannot update
		// cookies even if the server sends back a set-cookie header.

		$userinfo = $api->callApi('user', 'fetchUserinfo');
		// For security reasons, this MUST only ever return the current session's security token.
		$result = [
			'securitytoken' => $userinfo['securitytoken'],
			// mainly meant for debugging.
			'userid' => $userinfo['userid'],
		];

		// we may want to add some extra common data
		// $page['phrasedate'] = $options->get('miscoptions.phrasedate');
		// $page['optionsdate'] = $options->get('miscoptions.optionsdate');

		$this->returnJson($result);
	}
}
