<?php

namespace App\Observers;

use App\Models\IotMode;
use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;

class IotModeObserver
{
    /**
     * =========================
     * TRIGGER SETIAP UPDATE DB
     * =========================
     */
   public function updated(IotMode $iotMode): void
{
    logger()->info("Observer updated: ".$iotMode->mode);

    $this->publish($iotMode);
}

    public function created(IotMode $iotMode): void
    {
        $this->publish($iotMode);
    }

    /**
     * =========================
     * MQTT PUBLISH (FIX FINAL)
     * =========================
     */
    private function publish(IotMode $iotMode): void
    {
        try {
            $mqtt = new MqttClient(
                '127.0.0.1',
                1883,
                'observer-' . uniqid()
            );

            // 🔥 CONNECTION SETTINGS (STABIL)
            $connectionSettings = (new ConnectionSettings)
                ->setKeepAliveInterval(60)
                ->setConnectTimeout(3);

            $mqtt->connect($connectionSettings, true);

            // 🔥 PAYLOAD FINAL (STANDARIZED)
            $payload = json_encode([
                'mode' => $iotMode->mode,
                'book_id' => $iotMode->book_id,
                'ts' => now()->timestamp,
                'source' => 'observer'
            ]);

            // 🔥 PUBLISH REALTIME (IMPORTANT FIX)
            $mqtt->publish(
                'rfid/mode',
                $payload,
                1,      // QoS 1 (anti loss)
                false    // RETAIN (INI WAJIB BIAR ESP32 TIDAK KETINGGALAN)
            );

            $mqtt->disconnect();

        } catch (\Exception $e) {
            logger()->error("MQTT Observer Error: " . $e->getMessage());
        }
    }
}

