<?php

namespace SHServ\Controllers;

use \SHServ\Models\Devices;

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) {
			return $this -> utils() -> response_error("unknown_device", ["device_id"]);
		}

		if(!$device -> auth() -> is_active()) {
			return $this -> utils() -> response_error("error_of_device_auth");
		}

		ignore_user_abort(true);
		set_time_limit(10);

		ob_start();
		http_response_code(200);
		header("Content-Type: application/json; charset=utf-8");
		echo json_encode(['status' => 'ok']);

		$size = ob_get_length();
		header("Content-Length: {$size}");
		ob_end_flush();
		flush();

		$result = events() -> app_call(
			"{$device -> device_type}.{$event_name}",
			[
				"device" => $device,
				"data" => $data	
			]
		);

		return $this -> utils() -> response_success([
			"result" => $result
		]);
	}
}