<?php

require 'db_connection.php';

// Crear conexión
$conn = new mysqli($servername, $username, $password, $dbname, $port);
if ($conn->connect_error) {
    die("Error en la conexión: " . $conn->connect_error);
}

// Consulta para contar usuarios que ingresaron hoy (sin 'VEHICULO' en su nombre)
$sql_usuarios_ingreso_hoy = "
SELECT COUNT(DISTINCT n.usrid) AS total_usuarios_ingreso_hoy
FROM t_lg202411 n
LEFT JOIN t_usr u ON n.usrid = u.usrid
WHERE n.EVT = 4102 
    AND FROM_UNIXTIME(n.DEVDT, '%Y-%m-%d') = CURDATE()
    AND u.NM NOT LIKE '%VEHICULO%'  -- Excluir usuarios con 'VEHICULO' en su nombre
";
$result_usuarios_ingreso_hoy = $conn->query($sql_usuarios_ingreso_hoy);
$total_usuarios_ingreso_hoy = $result_usuarios_ingreso_hoy->num_rows > 0 ? $result_usuarios_ingreso_hoy->fetch_assoc()['total_usuarios_ingreso_hoy'] : 0;

// Consulta para contar vehículos que ingresaron hoy (usuarios con 'VEHICULO' en su nombre)
$sql_vehiculos_ingreso_hoy = "
SELECT COUNT(DISTINCT n.usrid) AS total_vehiculos_ingreso_hoy
FROM t_lg202411 n
LEFT JOIN t_usr u ON n.usrid = u.usrid
WHERE n.EVT = 4102 
    AND FROM_UNIXTIME(n.DEVDT, '%Y-%m-%d') = CURDATE()
    AND u.NM LIKE '%VEHICULO%'  -- Incluir solo usuarios con 'VEHICULO' en su nombre
";
$result_vehiculos_ingreso_hoy = $conn->query($sql_vehiculos_ingreso_hoy);
$total_vehiculos_ingreso_hoy = $result_vehiculos_ingreso_hoy->num_rows > 0 ? $result_vehiculos_ingreso_hoy->fetch_assoc()['total_vehiculos_ingreso_hoy'] : 0;

// Consulta para contar dispositivos con registros hoy
$sql_dispositivos_hoy = "
SELECT COUNT(DISTINCT DEVUID) AS total_dispositivos_hoy
FROM t_lg202411
WHERE FROM_UNIXTIME(DEVDT, '%Y-%m-%d') = CURDATE()
";
$result_dispositivos_hoy = $conn->query($sql_dispositivos_hoy);
$total_dispositivos_hoy = $result_dispositivos_hoy->num_rows > 0 ? $result_dispositivos_hoy->fetch_assoc()['total_dispositivos_hoy'] : 0;

// Cerrar la conexión
$conn->close();

// Devolver los contadores como JSON
echo json_encode([
    'usuarios_ingreso_hoy' => $total_usuarios_ingreso_hoy,
    'vehiculos_ingreso_hoy' => $total_vehiculos_ingreso_hoy,
    'dispositivos_hoy' => $total_dispositivos_hoy
]);
