<?php

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

/*
|--------------------------------------------------------------------------
| DB manual de prueba
|--------------------------------------------------------------------------
| Ajustá estos datos si hace falta
*/
$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 HikvisionNominaService($client);
$result = $service->obtenerUsuarios(0, 100);

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

if (!$result['ok']) {
    echo "Error consultando nómina\n";
    echo "HTTP: " . $result['http_code'] . "\n";
    echo "Error: " . $result['error'] . "\n";
    exit;
}

echo "Usuarios encontrados: " . $result['total'] . "\n\n";

$sql = "
    INSERT INTO reloj_nomina
    (reloj_id, device_user_id, nombre, empleado_no, raw_json, actualizado_en)
    VALUES (?, ?, ?, ?, ?, NOW())
    ON DUPLICATE KEY UPDATE
        nombre = VALUES(nombre),
        empleado_no = VALUES(empleado_no),
        raw_json = VALUES(raw_json),
        actualizado_en = NOW()
";

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

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

foreach ($result['users'] as $userRow) {
    $deviceUserId = (string)$userRow['device_user_id'];
    $nombre       = $userRow['nombre'];
    $empleadoNo   = $userRow['empleado_no'];
    $rawJson      = json_encode($userRow['raw_json'], JSON_UNESCAPED_UNICODE);

    $stmt->bind_param(
        'issss',
        $relojId,
        $deviceUserId,
        $nombre,
        $empleadoNo,
        $rawJson
    );

    $ok = $stmt->execute();

    if ($ok) {
        echo "Guardado: {$deviceUserId} - {$nombre}\n";
    } else {
        echo "Error guardando {$deviceUserId}: " . $stmt->error . "\n";
    }
}

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

echo "\nProceso terminado.\n";