<?php
/*
** Copyright (C) 2021-2026 initMAX s.r.o.
**
** This program is free software: you can redistribute it and/or modify it under the terms of
** the GNU Affero General Public License as published by the Free Software Foundation, version 3.
**
** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
** See the GNU Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public License along with this program.
** If not, see <https://www.gnu.org/licenses/>.
**/


namespace Modules\TetrisMAX\Actions\Widgets;

use CControllerResponseData;
use CControllerWidget;
use Modules\TetrisMAX\Includes\GamePayload;
use Modules\TetrisMAX\Services\WidgetTranslator;

/**
 * v1 (Zabbix 6.0/6.2) tetrisMAX view action.
 *
 * The base class is the ONLY real difference from the manifest-v2 controller:
 * 6.0/6.2 have CControllerWidget, 6.4+ have CControllerDashboardWidgetView.
 * Everything the player sees comes from the shared GamePayload - the same code
 * the 6.4+ controller runs - so the two trees cannot deal a different set of
 * pieces or apply the FREE lock differently.
 */
class tetrisMAXView extends CControllerWidget {

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

		$this->setType(tetrisMAXForm::WIDGET_TYPE);
		$this->setValidationRules([
			'name' => 'string',
			'fields' => 'json',
			'dynamic_hostid' => 'db hosts.hostid',
			'templateid' => 'db dashboard.templateid',
			// The 6.0/6.2 shell spreads its own tile size into every update
			// request. The game sizes itself in CSS and does not read them, but
			// an undeclared input fails validation before doAction() ever runs.
			'content_width' => 'int32|ge 1|le 65535',
			'content_height' => 'int32|ge 1|le 65535',
			'contents_width' => 'int32|ge 1|le 65535',
			'contents_height' => 'int32|ge 1|le 65535'
		]);
	}

	protected function doAction() {
		// 6.4+ has Zabbix fill $this->fields_values; here the form does. That
		// one line is the whole bridge - everything downstream is shared code.
		$fields_values = $this->getForm()->getFieldsData();

		$this->setResponse(new CControllerResponseData(
			GamePayload::build($fields_values) + [
				'name' => $this->getInput('name', WidgetTranslator::translate('widget.name')),
				'user' => [
					'debug_mode' => $this->getDebugMode()
				]
			]
		));
	}
}
