<?php
header('Content-Type: application/json; charset=utf-8');
require_once("config-secure.php");

// --------------------------
// 1) ตรวจสอบว่าผู้ใช้ล็อกอินหรือยัง
// --------------------------
session_start();
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        "status" => "error",
        "message" => "Unauthenticated"
    ]);
    exit;
}

$user_id = intval($_SESSION['user_id']);

// --------------------------
// 2) ดึงรายการ Beacon ของผู้ใช้
// --------------------------
$sql = "
    SELECT 
        id,
        uuid,
        major,
        minor,
        name,
        notify_type
    FROM beacons
    WHERE user_id = ?
";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$beacons = [];
while ($row = $result->fetch_assoc()) {
    $beacons[] = [
        "id"          => intval($row['id']),
        "uuid"        => $row['uuid'],
        "major"       => intval($row['major']),
        "minor"       => intval($row['minor']),
        "name"        => $row['name'],
        "notify_type" => $row['notify_type']  // <-- เพิ่มตรงนี้
    ];
}

// --------------------------
// 3) ส่งผลลัพธ์กลับไปที่แอป
// --------------------------
echo json_encode([
    "status"  => "success",
    "beacons" => $beacons
], JSON_UNESCAPED_UNICODE);
exit;
