<?php

// https://community.ui.com/questions/PHP-client-class-to-access-the-UniFi-controller-API-updates-and-discussion/86cff6e2-06ad-46a2-8e0d-d91004f78752#answer/a309924b-1b8a-4c8b-bb15-98cd0be105d7

require_once('client.php');
require_once('config.php');
// $debug = true
$site_id = 'default';

// Device State
if (strtolower($_GET["type"]) == "status") {
	if (strtolower(!empty($_GET["mac"]))) {

		$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
		$set_debug_mode   = $unifi_connection->set_debug($debug);
		$loginresults     = $unifi_connection->login(); // always true regardless of site id
		$getid_result = $unifi_connection->stat_client($_GET["mac"]);
		sleep(1);

		//echo print_r($getid_result, true);
		if (property_exists($getid_result[0], "blocked")) {
			$status = $getid_result[0]->blocked;
		}
		if ($status == 1) {
			echo '1'; // Blocked
		} else {
			echo '0'; // Unblocked
		}	
 	}
}

// Block Device
if (strtolower($_GET["type"]) == "block") {
	if (strtolower(!empty($_GET["mac"]))) {

		$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
		$set_debug_mode   = $unifi_connection->set_debug($debug);
		$loginresults     = $unifi_connection->login(); // always true regardless of site id
		$block_result = $unifi_connection->block_sta($_GET["mac"]);
		sleep(1);

    	$getid_result = $unifi_connection->stat_client($_GET["mac"]);
		if (property_exists($getid_result[0], "oui")) {
			if (property_exists($getid_result[0], "name")) {
            			$name = $getid_result[0]->name;
        		} else {
            			$name = $getid_result[0]->hostname;
				}
				echo $name, ' is blocked<br>';
    		} else {
				echo 'ERROR: Device NOT blocked<br>';
		}
		echo 'Finish Blocked';
	}
}

// Unblock Device
if (strtolower($_GET["type"]) == "unblock") {
	if (strtolower(!empty($_GET["mac"]))) {

		$unifi_connection = new UniFi_API\Client($controlleruser, $controllerpassword, $controllerurl, $site_id, $controllerversion);
		$set_debug_mode   = $unifi_connection->set_debug($debug);
		$loginresults     = $unifi_connection->login(); // always true regardless of site id
		$block_result = $unifi_connection->unblock_sta($_GET["mac"]);
		sleep(1);

    	$getid_result = $unifi_connection->stat_client($_GET["mac"]);
		if (property_exists($getid_result[0], "oui")) {
			if (property_exists($getid_result[0], "name")) {
            			$name = $getid_result[0]->name;
        		} else {
            			$name = $getid_result[0]->hostname;
				}
				echo $name, ' is unblocked<br>';
    		} else {
				echo 'ERROR: Device NOT unblocked<br>';
		}
		echo 'Finish Unblocked';
	}
}

//echo '<br>Unifi Devices block and unblock by mac-address';