<?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) {
			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();

		$events_model = new EventsModel();

		// For multichannels
		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);
	}
}