<?php
/**
 * PACK BEACON – SECURE API
 * Verify Beacon Ownership
 * Path: /api-secure/verify_beacon.php
 */

require_once __DIR__ . "/config-secure.php";
require_once __DIR__ . "/auth-secure.php";

require_method("POST");

// ตรวจสอบ Token + Signature
list($raw, $input) = require_secure_json();

/* ============================================================
   รับค่า UUID / Major / Minor
============================================================ */
$uuid  = trim($input["uuid"] ?? "");
$major = intval($input["major"] ?? 0);
$minor = intval($input["minor"] ?? 0);

if ($uuid == "" || $major <= 0 || $minor <= 0) {
    api_json([
        "status" => "error",
        "message" => "Invalid UUID/Major/Minor"
    ]);
}

/* ============================================================
   ค้นหา Beacon ในระบบ
============================================================ */
$stmt = $conn->prepare("
    SELECT 
        beacons.id AS beacon_id,
        beacons.location,
        beacons.user_id,
        users.fullname
    FROM beacons
    LEFT JOIN users ON users.id = beacons.user_id
    WHERE uuid = ? AND major = ? AND minor = ?
    LIMIT 1
");
$stmt->bind_param("sii", $uuid, $major, $minor);
$stmt->execute();
$beacon = $stmt->get_result()->fetch_assoc();

/* ============================================================
   ไม่พบ Beacon
============================================================ */
if (!$beacon) {
    api_json([
        "status" => "not_found",
        "message" => "Beacon not registered"
    ]);
}

/* ============================================================
   ส่งข้อมูลกลับ
============================================================ */
api_json([
    "status" => "success",
    "beacon" => [
        "beacon_id" => intval($beacon["beacon_id"]),
        "location"  => $beacon["location"],
        "user_id"   => intval($beacon["user_id"]),
        "user_name" => $beacon["fullname"]
    ]
]);
