<?php

namespace SHServ\Controllers;

use \SHServ\Models\Devices;
use \SHServ\Models\EventsModel;

class EventsController extends \SHServ\Middleware\Controller {

	/**
	 * Тригерит ивенты от устройств
	 * @param  String $event_name Like a "click"
	 * @param  String $device_id  device_hard_id
	 * @param  String $data  Arguments from device to event handlers
	 */

	public function new_event($event_name, $device_id, $data) {
		$devices_model = new Devices();
		$device = $devices_model -> by_hard_id($device_id);

		if(!$device) {
			logging() -> warn('php:Events', 'Event from unknown device', ['device_hard_id' => $device_id, 'event_name' => $event_name]);
			return $this -> utils() -> response_error("unknown_device", ["device_id"]);
		}

		if(!$device -> auth() -> is_active()) {
			logging() -> warn('php:Events', 'Event from device with inactive auth', ['device_id' => $device -> id(), 'alias' => $device -> alias, 'event_name' => $event_name]);
			return $this -> utils() -> response_error("error_of_device_auth");
		}

		logging() -> info('php:Events', 'Event received', [
			'device_id' => $device -> id(),
			'alias' => $device -> alias,
			'event_name' => $event_name,
			'channel' => $data["channel"] ?? null,
		]);

		$device -> touch_last_contact();

		if($device -> connection_status != "active") {
			$device -> connection_status = "active";
			$device -> update();
		}

		ignore_user_abort(true);
		set_time_limit(10);

		$response = json_encode(['status' => 'ok']);

		http_response_code(200);
		header("Content-Type: application/json; charset=utf-8");
		header("Content-Length: " . strlen($response));
		header("Connection: close");

		echo $response;

		if (function_exists('fastcgi_finish_request')) {
			fastcgi_finish_request();
		} else {
			ob_flush();
			flush();
		}

		$events_model = new EventsModel();

		if(isset($data["channel"])) {
			$events_model -> channel_alias_device_event_call($device, $event_name, intval($data["channel"]), $data);
			$events_model -> channel_device_event_call($device, $event_name, intval($data["channel"]), $data);
		}

		$events_model -> alias_device_event_call($device, $event_name, $data);
		$events_model -> global_device_event_call($device, $event_name, $data);
		$events_model -> global_any_device_event_call($device, $event_name, $data);
	}
}
