<?php
require_once '../config/database.php';

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

$device_id = $data['device_id'] ?? null;
$device_model = $data['device_model'] ?? 'Unknown';
$uptime = $data['uptime'] ?? '0';
$ip_address = $_SERVER['REMOTE_ADDR'];

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

try {
    // Verifica se o dispositivo já existe
    $stmt = $pdo->prepare("SELECT * FROM user_connections WHERE device_id = ?");
    $stmt->execute([$device_id]);
    $device = $stmt->fetch();

    $current_time = date('Y-m-d H:i:s');

    if ($device) {
        // Atualiza a última conexão
        $stmt = $pdo->prepare("
            UPDATE user_connections 
            SET last_connection = ?, is_online = 1, ip_address = ?, uptime = ?
            WHERE device_id = ?
        ");
        $stmt->execute([$current_time, $ip_address, $uptime, $device_id]);
    } else {
        // Insere um novo dispositivo
        $stmt = $pdo->prepare("
            INSERT INTO user_connections 
            (device_id, device_model, last_connection, uptime, is_online, ip_address, first_seen)
            VALUES (?, ?, ?, ?, 1, ?, ?)
        ");
        $stmt->execute([$device_id, $device_model, $current_time, $uptime, $ip_address, $current_time]);
    }

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