<?php
require_once __DIR__ . '/bootstrap.php';

use PhpMqtt\Client\MqttClient;
use PhpMqtt\Client\ConnectionSettings;

$input = json_decode(file_get_contents('php://input'), true) ?: [];
$topic = $input['topic'] ?? null;
$payload = array_key_exists('payload', $input) ? $input['payload'] : null;
$qos = isset($input['qos']) ? (int)$input['qos'] : 0;
$retain = isset($input['retain']) ? (bool)$input['retain'] : false;

if (!$topic || $payload === null) {
    json_error('topic y payload son obligatorios', 422);
}

$host = envv('MQTT_HOST', 'localhost');
$port = (int) envv('MQTT_PORT', 1883);
$useTls = filter_var(envv('MQTT_TLS', '0'), FILTER_VALIDATE_BOOLEAN);
$username = envv('MQTT_USUARIO', envv('MQTT_USERNAME'));
$password = envv('MQTT_CONTRASENA', envv('MQTT_PASSWORD'));
$clientId = envv('MQTT_CLIENT_ID', 'esp-backend-' . bin2hex(random_bytes(3)));

try {
    $settings = (new ConnectionSettings())
        ->setUsername($username)
        ->setPassword($password)
        ->setUseTls($useTls)
        ->setKeepAliveInterval(60)
        ->setConnectTimeout(10)
        ->setSocketTimeout(5)
        ->setTlsSelfSignedAllowed(true); // ajustar según CA

    $mqtt = new MqttClient($host, $port, $clientId);
    $mqtt->connect($settings, true);
    $mqtt->publish($topic, is_string($payload) ? $payload : json_encode($payload), $qos, $retain);
    $mqtt->disconnect();

    json_success(['topic' => $topic, 'payload' => $payload]);
} catch (Throwable $e) {
    json_error('Fallo al publicar MQTT: ' . $e->getMessage(), 500);
}
