<?php

require_once("lib-action/action.php");

use Billing\ModuleTool;

class AddPanelResponse extends MB_Action
{
	public function execute()
	{
		parent::execute();

		if (is_null($params["serverGroupID"] = $serverGroupID = bgpc("serverGroupID")))
			$this->addError(blmsg("TRANS_ACTIONERROR"), "No ServerGroup ID given.");

		if (is_null($parentConfigGroupID = bgpc("parentConfigGroupID")) && ! is_null($panelName = bgpc("panelName")))
		{
			$panelsGroup = Factory()->ConfigGroup(0)->getChild("server")->getChild("serverGroups")->getChild("panel");
			try {
				$panelGroup = $panelsGroup->getChild($panelName);
			} catch (ProductException $e) {
				if (ProductException::E_OBJECT_NOT_FOUND != $e->getCode())
					throw $e;

				// Create new config group for new panel
				$moduleInfo = ModuleTool::getModuleInfo('panel', $panelName);
				$panelGroup = Factory()->ConfigGroup();
				$panelGroup->parent_config_group_id = $panelsGroup->config_group_id;
				$panelGroup->config_group_name = $panelName;
				$panelGroup->config_group_trans_key = $moduleInfo['displayName'];
				$panelGroup->update();
			}
			$parentConfigGroupID = $panelGroup->config_group_id;
		}

		if (is_null($parentConfigGroupID))
			$this->addError(blmsg("TRANS_ACTIONERROR"), "No Panel Name or Parent Config Group ID given.");

		if (0 < $this->getNumErrors())
		{
			$this->addErrorTemplates();
			return $this->hasExecutedSuccessfully();
		}

		if ( "" != ($redirectURL = bgpc("redirectURL")) && "" != ($redirectAction = bgpc("redirectAction")) ) {
			$params = array(
				"serverGroupID" => $serverGroupID,
				"parentConfigGroupID" => $parentConfigGroupID,
			);
			require_once("lib-mbapi/mbapi.php");
			$query = $this->getMBAPIQuery("SetPanels", "insert", $params);
			$data = dispatchMBAPI($query, 1);
			if ( 0 === $this->addMBAPIErrors($data) && 0 == $this->getNumErrors() )
				redirect($redirectURL."?action=".getActionID($redirectAction)."&".bgpc("redirectArgs"));
		} else {
			redirect("modules.php", getActionID("EditPanelConfig"), array("parentConfigGroupID" => $parentConfigGroupID, "serverGroupID" => $serverGroupID));
		}

		$this->addErrorTemplates();
		return $this->hasExecutedSuccessfully();
	}
}