<?php
// api/iot_gateway.php (SECURE ENTERPRISE VERSION)
header('Content-Type: text/plain');
include '../config/database.php';

// Pastikan Timezone sama dengan Gemini
date_default_timezone_set('Asia/Jakarta');

$key = $_GET['k'] ?? ''; // API Key
$dev = $_GET['d'] ?? ''; // ID Device (misal: sensor_tanah)
$val = $_GET['v'] ?? ''; // Nilai Sensor (misal: 45%)

if (empty($key)) { die("Error: API Key Kosong"); }

// Jika d = list, kembalikan daftar semua perangkat dalam JSON
if (($_GET['d'] ?? '') === 'list') {
    header('Content-Type: application/json');
    $stmt_key = mysqli_prepare($conn, "SELECT user_id FROM user_api_keys WHERE key_string = ? LIMIT 1");
    mysqli_stmt_bind_param($stmt_key, "s", $key);
    mysqli_stmt_execute($stmt_key);
    $res_key = mysqli_stmt_get_result($stmt_key);
    
    if (mysqli_num_rows($res_key) == 0) { die(json_encode(["error" => "Invalid API Key"])); }
    $data = mysqli_fetch_assoc($res_key);
    $u_id = $data['user_id'];
    
    $res_devs = mysqli_query($conn, "SELECT device_id, label, status, last_value FROM iot_devices WHERE user_id = '$u_id'");
    $devs = [];
    while($r = mysqli_fetch_assoc($res_devs)) { $devs[] = $r; }
    echo json_encode($devs);
    exit;
}

if (empty($dev)) { die("Error: Parameter Kurang"); }

// 1. Cek Validitas API Key (MENGGUNAKAN PREPARED STATEMENT)
$stmt_key = mysqli_prepare($conn, "SELECT user_id FROM user_api_keys WHERE key_string = ? LIMIT 1");
mysqli_stmt_bind_param($stmt_key, "s", $key);
mysqli_stmt_execute($stmt_key);
$res_key = mysqli_stmt_get_result($stmt_key);

if (mysqli_num_rows($res_key) == 0) {
    die("Error: API Key Invalid");
}
$data = mysqli_fetch_assoc($res_key);
$owner_id = $data['user_id'];
mysqli_stmt_close($stmt_key);

// 2. TENTUKAN WAKTU SEKARANG (Heartbeat)
$waktu_skrg = date('Y-m-d H:i:s');

// 3. LOGIKA UPDATE DATA
if ($val !== '') {
    // KASUS A: INI ADALAH SENSOR (Mengirim Data)
    $stmt_upd = mysqli_prepare($conn, "UPDATE iot_devices SET last_value = ?, last_seen = ? WHERE user_id = ? AND device_id = ?");
    mysqli_stmt_bind_param($stmt_upd, "ssss", $val, $waktu_skrg, $owner_id, $dev);
    
    if(mysqli_stmt_execute($stmt_upd)){
        echo "Data Saved: $val";
    } else {
        echo "DB Error";
    }
    mysqli_stmt_close($stmt_upd);

} else {
    // KASUS B: INI ADALAH ALAT BIASA/RELAY (Cuma Tanya Status)
    $stmt_upd = mysqli_prepare($conn, "UPDATE iot_devices SET last_seen = ? WHERE user_id = ? AND device_id = ?");
    mysqli_stmt_bind_param($stmt_upd, "sss", $waktu_skrg, $owner_id, $dev);
    mysqli_stmt_execute($stmt_upd);
    mysqli_stmt_close($stmt_upd);
    
    // Ambil status ON/OFF untuk dikirim balik ke ESP8266
    $stmt_stat = mysqli_prepare($conn, "SELECT status FROM iot_devices WHERE user_id = ? AND device_id = ?");
    mysqli_stmt_bind_param($stmt_stat, "ss", $owner_id, $dev);
    mysqli_stmt_execute($stmt_stat);
    $res_stat = mysqli_stmt_get_result($stmt_stat);
    
    if (mysqli_num_rows($res_stat) > 0) {
        $d_stat = mysqli_fetch_assoc($res_stat);
        echo $d_stat['status']; 
    } else {
        echo "0"; // Default mati jika error
    }
    mysqli_stmt_close($stmt_stat);
}
?>