<?php
require_once 'includes/db_connect.php';

// --- Parameter validieren ---
if (!isset($_GET['apikey'], $_GET['pflanze'], $_GET['sensor'], $_GET['wert'])) {
    http_response_code(400); // Bad Request
    die('Error: Missing parameters.');
}

$api_key = $_GET['apikey'];
$plant_id = (int)$_GET['pflanze'];
$sensor_key = strtolower($_GET['sensor']);
$value = $_GET['wert'];

if (empty($api_key) || empty($plant_id) || empty($sensor_key) || !is_numeric($value)) {
    http_response_code(400);
    die('Error: Invalid parameters.');
}

// --- API-Key validieren und User-ID holen ---
$user_id = null;
$sql_user = "SELECT id FROM users WHERE api_key = ?";
if ($stmt_user = $mysqli->prepare($sql_user)) {
    $stmt_user->bind_param("s", $api_key);
    $stmt_user->execute();
    $result_user = $stmt_user->get_result();
    if ($result_user->num_rows === 1) {
        $user_id = $result_user->fetch_assoc()['id'];
    }
    $stmt_user->close();
}

if ($user_id === null) {
    http_response_code(401); // Unauthorized
    die('Error: Invalid API Key.');
}

// --- Pflanzen-Zugehörigkeit prüfen ---
$sql_plant = "SELECT id FROM plants WHERE id = ? AND user_id = ?";
if ($stmt_plant = $mysqli->prepare($sql_plant)) {
    $stmt_plant->bind_param("ii", $plant_id, $user_id);
    $stmt_plant->execute();
    if ($stmt_plant->get_result()->num_rows === 0) {
        http_response_code(403); // Forbidden
        die('Error: Plant does not belong to user.');
    }
    $stmt_plant->close();
}

// --- Sensor-Typ mappen ---
$sensor_map = [
    'temp' => 'Temperatur',
    'tmp' => 'Temperatur',
    'temperatur' => 'Temperatur',
    'feuchtigkeit' => 'Feuchtigkeit',
    'humidity' => 'Feuchtigkeit',
    'feucht' => 'Feuchtigkeit'
];

if (!array_key_exists($sensor_key, $sensor_map)) {
    http_response_code(400);
    die('Error: Unknown sensor type. Use temp or humidity.');
}
$db_sensor_type = $sensor_map[$sensor_key];

// --- Daten in die Datenbank einfügen ---
$sql_insert = "INSERT INTO sensor_data (plant_id, sensor_type, value) VALUES (?, ?, ?)";
if ($stmt_insert = $mysqli->prepare($sql_insert)) {
    $stmt_insert->bind_param("isd", $plant_id, $db_sensor_type, $value);
    if ($stmt_insert->execute()) {
        http_response_code(200);
        echo "OK";
    } else {
        http_response_code(500);
        die("Error: Could not save data.");
    }
    $stmt_insert->close();
}

$mysqli->close();
?>
