<?php

require_once 'fcm_helper.php';

function sendNotif($conn, $user_id, $title, $body, $data = [])
{
    /// 🔥 ambil token
    $q = mysqli_query($conn, "
        SELECT fcm_token FROM users WHERE id = $user_id
    ");

    $user = mysqli_fetch_assoc($q);
    $token = $user['fcm_token'] ?? null;

    /// 🔥 simpan ke DB
    $stmt = $conn->prepare("
        INSERT INTO notifications (user_id, title, body)
        VALUES (?, ?, ?)
    ");
    $stmt->bind_param("iss", $user_id, $title, $body);
    $stmt->execute();

    /// 🔥 kirim FCM
    if (!empty($token)) {
        sendFCM(
            $token,
            $title,
            $body,
            $data
        );
    }
}