<?php
header('Content-Type: application/json');
require_once 'db_connection.php';

$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['device_id'])) {
    echo json_encode(['success' => false, 'error' => 'Device ID missing']);
    exit;
}

$deviceId = $data['device_id'];
$isOnline = isset($data['is_online']) ? (int)$data['is_online'] : 0; // Garante que recebe 0 ou 1
$lastConnection = $data['last_connection'] ?? date('Y-m-d H:i:s');

try {
    $stmt = $pdo->prepare("UPDATE user_connections SET 
        is_online = :is_online,
        last_connection = :last_connection
        WHERE device_id = :device_id");
    
    $stmt->execute([
        ':is_online' => $isOnline,
        ':last_connection' => $lastConnection,
        ':device_id' => $deviceId
    ]);

    // Verifica se alguma linha foi afetada
    if ($stmt->rowCount() === 0) {
        // Se não houve atualização, insere novo registro
        $stmt = $pdo->prepare("INSERT INTO user_connections 
            (device_id, device_model, last_connection, uptime, is_online, first_seen) 
            VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $deviceId, 
            $data['device_model'] ?? 'Unknown', 
            $lastConnection, 
            $data['uptime'] ?? '0 seconds', 
            $isOnline,
            $lastConnection
        ]);
    }

    echo json_encode(['success' => true]);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
?>