<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MonitoringController;
use App\Http\Controllers\KontrolController;
use App\Http\Controllers\BlogController;
use App\Http\Controllers\TentangController;
use App\Http\Controllers\DeviceController;
use App\Http\Controllers\RiwayatController;
use App\Libraries\phpMQTT;
Route::get('/', function () {
    return view('welcome');
});

// routes/web.php
Route::get('/ui', function () {
    return view('ui');
})->name('ui');

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home')->middleware('auth');
Route::get('/tentang', [TentangController::class, 'index'])->name('tentang')->middleware('auth');
Route::get('/monitoring', [MonitoringController::class, 'index'])->middleware('auth');
Route::get('/blogs', [BlogController::class, 'index'])->name('blog.index')->middleware('auth');
Route::get('/blogs/{id}', [BlogController::class, 'show'])->name('blog.show');
Route::delete('/blogs/{id}', [BlogController::class, 'destroy'])->name('blogs.destroy')->middleware('auth');
Route::get('/blog/create', [BlogController::class, 'create'])->name('blogs.create')->middleware('auth');
Route::post('/blogs', [BlogController::class, 'store'])->name('blogs.store')->middleware('auth');
Route::get('/kontrol', [DeviceController::class, 'index'])->middleware('auth');
Route::get('/riwayat', [RiwayatController::class, 'index'])->middleware('auth');
Route::get('/riwayat/filter', [RiwayatController::class, 'filterByDate'])->name('riwayat.filter');

Route::get('/mqtt-test', function() {
    $mqtt = new phpMQTT('broker.hivemq.com', 1883, 'ClientID');
    if($mqtt->connect()) {
        echo "Connected to MQTT broker";
        $mqtt->close();
    } else {
        echo "Failed to connect";
    }
});

Route::get('/mqtt-publish', function() {
    $mqtt = new phpMQTT('broker.hivemq.com', 1883, 'ClientID');
    if ($mqtt->connect()) {
        // Isi pesan yang akan dipublikasikan ke topik "test/topic"
        $pesan = "Ini adalah pesan dari Laravel";

        // Publish pesan ke topik "test/topic"
        $mqtt->publish("test/topic", $pesan);

        $mqtt->close();
        echo "Message published successfully";
    } else {
        echo "Failed to connect to MQTT broker";
    }
});


Route::get('/mqtt-subscribe', function() {
    $mqtt = new phpMQTT('broker.hivemq.com', 1883, 'ClientID');
    if ($mqtt->connect()) {
        // Subscribe ke topik "test/topic"
        $mqtt->subscribe("test/topic", function($topic, $msg) {
            echo "Received message on topic $topic: $msg";
        });
        $mqtt->close();
    } else {
        echo "Failed to connect to MQTT broker";
    }
});
