<?php
namespace Modules\RemoteData\JsErrorHandler;


class Controller extends \App\Mvc\ControllerAbstract
{
	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['logCollectedErrors'] = ['authType' => 'none', 'checkSection' => false, 'checkOption' => false];
	}

	protected function actionLogCollectedErrors($R)
	{
		$jsonStr = file_get_contents('php://input');
		$json = json_decode($jsonStr);

		if ($json) {
			$logSession = sprintf("%09s-%06s-%05s",
				substr(session_id(), 0, 9),
				substr(md5((string)$json[0]->location??''), 0, 6),
				substr(\Engine\NumberConvertor::baseEncode($json[0]->performance->navigationStart??''), -5)
			);
			\Log::getInstance()->setLogSession($logSession);

			foreach ($json as $jsError) {
				\Log::getInstance()->warning(sprintf("[%s] On page '%s', got js error: %s", __METHOD__, $jsError->location, $jsError->exception->message), [
					'$jsError' => new \Engine\Logger\Context\Json($jsError),
					'$location' => $jsError->location,
				]);
			}

			return new \Engine\Mvc\Response\Json([
				'success' => true,
			]);
		}

		return new \Engine\Mvc\Response\Json([
			'success' => false,
		]);
	}

}
