<?php

require_once __DIR__ . '/../../app/services/hikvision/HikvisionClient.php';
require_once __DIR__ . '/../../app/services/hikvision/HikvisionDeviceService.php';

$dbHost = '127.0.0.1';
$dbUser = 'root';
$dbPass = '';
$dbName = 'comercio';

$mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName);

if ($mysqli->connect_error) {
    die('Error de conexión MySQL: ' . $mysqli->connect_error);
}

$mysqli->set_charset('utf8mb4');

$relojId = 1;

$client = new HikvisionClient([
    'ip'       => '192.168.100.254',
    'port'     => 80,
    'user'     => 'admin',
    'pass'     => '28251714.',
    'protocol' => 'http',
]);

$service = new HikvisionDeviceService($client);
$result = $service->detectar();

header('Content-Type: text/plain; charset=utf-8');

if (!$result['ok']) {
    echo "No se pudo detectar el dispositivo\n";
    print_r($result);
    exit;
}

$modelo   = $result['resumen']['modelo'] ?? null;
$serial   = $result['resumen']['serial_number'] ?? null;
$firmware = $result['resumen']['firmware_version'] ?? null;

$sql = "
    UPDATE relojes_biometricos
    SET modelo = ?,
        serial_number = ?,
        firmware_version = ?,
        ultimo_ping = NOW()
    WHERE id = ?
";

$stmt = $mysqli->prepare($sql);

if (!$stmt) {
    die('Error preparando UPDATE: ' . $mysqli->error);
}

$stmt->bind_param('sssi', $modelo, $serial, $firmware, $relojId);

if ($stmt->execute()) {
    echo "Reloj actualizado correctamente\n\n";
    echo "Modelo: {$modelo}\n";
    echo "Serial: {$serial}\n";
    echo "Firmware: {$firmware}\n";
} else {
    echo "Error actualizando reloj: " . $stmt->error . "\n";
}

$stmt->close();
$mysqli->close();