<?php
	// this is the post view, where the module receives the posts from the chat APIs
	$action = $this->getRequest()->getActionName();

	if ($action) // the view must have a action
	{
		$webhook = Mage::app()->getRequest()->getParam('webhook');
		$key = Mage::app()->getRequest()->getParam('key');
		$customKey = Mage::getStoreConfig('chatbot_enable/general_config/your_custom_key');

		if ($webhook == $customKey) // set webhook eg.: https://store.com/chatbot/chatdata/telegram/webhook/custom_key_here/ -> set webhook
			echo Mage::getModel('chatbot/chatdata')->requestHandler($action, $webhook);
		else if ($key == $customKey) // process request eg.: https://store.com/chatbot/chatdata/telegram/key/custom_key_here/ -> process post requests
			echo Mage::getModel('chatbot/chatdata')->requestHandler($action, null);
		else // error
		{
			$enableLog = Mage::getStoreConfig('chatbot_enable/general_config/enable_post_log');
			if ($enableLog == "1")
			{
				//$visitorData = Mage::getSingleton('core/session')->getVisitorData();
				$remoteAddr = Mage::helper('core/http')->getRemoteAddr(false);
				Mage::log(
					"Error trying to access webhook:\n" .
					//"Visitor Data: \n" . var_export($visitorData, true) . "\n" .
					"IP: " . $remoteAddr . "\n" .
					"API: " . $action . "\n" .
					"Key: " . ($key ? $key : $webhook) . "\n", null, 'chatbot_error.log');
			}
		}
	}
	else
		echo json_encode(array("status" => "error"));
?>