<?php
/**
 * PACK BEACON – SECURE API
 * Send Notification to User (FCM)
 * Path: /api-secure/send_notification.php
 */

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

require_method("POST");

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

/* ============================================================
   อินพุตที่จำเป็น
============================================================ */
$user_id = intval($input["user_id"] ?? 0);
$title   = trim($input["title"] ?? "");
$body    = trim($input["body"] ?? "");

if ($user_id <= 0 || $title == "" || $body == "") {
    api_json([
        "status" => "error",
        "message" => "Missing user_id or title or body"
    ]);
}

/* ============================================================
   อ่าน FCM Token ของผู้ใช้
============================================================ */
$stmt = $conn->prepare("
    SELECT fcm_token
    FROM devices
    WHERE user_id = ?
    ORDER BY id DESC
    LIMIT 1
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$device = $stmt->get_result()->fetch_assoc();

if (!$device) {
    api_json([
        "status" => "error",
        "message" => "User has no registered device"
    ]);
}

$fcm_token = $device["fcm_token"];

/* ============================================================
   เตรียม JSON สำหรับส่ง FCM
============================================================ */
$fcmData = [
    "to" => $fcm_token,
    "notification" => [
        "title" => $title,
        "body" => $body,
        "sound" => "default"
    ],
    "data" => [
        "click_action" => "FLUTTER_NOTIFICATION_CLICK",
        "source" => "pack_beacon_api"
    ]
];

/* ============================================================
   ส่งข้อมูลไป FCM
============================================================ */
$FCM_API_KEY = "YOUR_FCM_SERVER_KEY_HERE";  // <<<< ต้องใส่จริง

$headers = [
    "Authorization: key=" . $FCM_API_KEY,
    "Content-Type: application/json"
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmData));
$result = curl_exec($ch);
curl_close($ch);

/* ============================================================
   บันทึก Log
============================================================ */
$log_msg = "Sent notification to user $user_id: $title";

$stmt = $conn->prepare("
    INSERT INTO logs (user_id, beacon_id, message)
    VALUES (?, NULL, ?)
");
$stmt->bind_param("is", $user_id, $log_msg);
$stmt->execute();

/* ============================================================
   ส่งผลลัพธ์กลับ
============================================================ */
api_json([
    "status" => "success",
    "message" => "Notification sent",
    "fcm_response" => json_decode($result, true)
]);
