<?php

if (!isset($_GET['key'])) {
    die("Key not set");
}

if ($_GET['key'] != "324rf98hy7324rvhyn78f34v") {
    die("Incorrect key");
}

$db_host = 'localhost';
$db_user = 'pinger';
$db_pass = '96hb7n8g0y65s3edx7cf4v';
$db_name = 'seabee';

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error); // Added connection error check
}

$computer_name = $_GET['computer_name'] ?? null; // Added null coalescing to avoid undefined index
$computer_name = strtolower(trim($computer_name));

$local_ip = $_GET['local_ip'] ?? null;

$remote_ip = $_SERVER['REMOTE_ADDR']; // Fixed missing semicolon

// Corrected SQL syntax: ON DUPLICATE KEY UPDATE must include column=value pairs
$stmt = $conn->prepare("INSERT INTO pinger (computer_name, local_ip, remote_ip, timestamp) VALUES (?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE local_ip = VALUES(local_ip), remote_ip = VALUES(remote_ip), timestamp = NOW()"); 

if (!$stmt) {
    die("Prepare failed: " . $conn->error); // Check if prepare failed
}

$stmt->bind_param("sss", $computer_name, $local_ip, $remote_ip);

if (!$stmt->execute()) {
    die("Execute failed: " . $stmt->error);
} else {
    echo "OK";
}

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