<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\IotMode;
use Illuminate\Support\Facades\Cache;
use PhpMqtt\Client\MqttClient;

class IotModeController extends Controller
{
    /**
     * Mengupdate mode sistem (Admin/User/Wait)
     */
    public function updateMode(Request $request)
    {
        $mode = $request->mode; // misal: 'user'
        $bookId = $request->book_id ?? null;

        // 1. Simpan ke Database sebagai acuan utama
        IotMode::query()->update([
            'mode' => $mode,
            'book_id' => $bookId,
            'updated_at' => now()
        ]);

        Cache::forget('iot_mode_data');

        // 2. Kirim sinyal ke MQTT agar hardware merespon saat itu juga
        $this->publishMqtt([
            'mode' => $mode,
            'book_id' => $bookId,
            'ts' => now()->timestamp
        ]);

        return response()->json([
            'status' => 'ok',
            'mode' => $mode,
            'message' => 'Mode berhasil diperbarui'
        ]);
    }

    /**
     * Reset sistem ke kondisi awal (Standby)
     */
    public function reset()
    {
        IotMode::query()->update([
            'mode' => 'standby',
            'book_id' => null
        ]);

        Cache::forget('iot_mode_data');

        $this->publishMqtt([
            'mode' => 'standby',
            'book_id' => null,
            'ts' => now()->timestamp
        ]);

        return response()->json(['status' => 'reset_ok']);
    }

    /**
     * Fungsi Helper untuk koneksi MQTT
     */
    private function publishMqtt($data)
    {
        try {
            // Sesuaikan IP Broker MQTT Anda (misal: 127.0.0.1 atau IP Local Laptop)
            $mqtt = new MqttClient('127.0.0.1', 1883, 'laravel-publisher-' . uniqid());
            $mqtt->connect();

            // Kirim JSON ke topik rfid/mode
            $mqtt->publish('rfid/mode', json_encode($data), 0);
            
            $mqtt->disconnect();
        } catch (\Exception $e) {
            \Log::error("Gagal mengirim MQTT: " . $e->getMessage());
        }
    }
}

