<?php
header("Content-Type: application/json");
$input = json_decode(file_get_contents("php://input"), true);

$user_id = $input['user_id'] ?? null;
$amount = $input['amount'] ?? null;

if (!$user_id || !$amount) {
    echo json_encode(["success" => false, "message" => "Missing required fields"]);
    exit;
}

# ? DB Connection (PDO)
require_once "db_connect.php";

$stmt = $conn->prepare("SELECT fcm_token FROM user_devices WHERE user_id = ? AND removed = 0");
$stmt->execute([$user_id]);
$device = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$device) {
    echo json_encode(["success" => false, "message" => "No device token found"]);
    exit;
}

$fcm_token = $device['fcm_token'];

# ? FCM Server Key
$serverKey = "YOUR_FIREBASE_SERVER_KEY_HERE"; // CHANGE THIS ?

# ? Notification Payload
$payload = [
    "to" => $fcm_token,
    "data" => [
        "type" => "credit_alert",
        "amount" => $amount
    ],
    "notification" => [
        "title" => "Credit Alert ",
        "body" => "You received N$amount",
        "sound" => "default"
    ]
];

$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, [
    "Authorization: key=$serverKey",
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
curl_close($ch);

echo json_encode(["success" => true, "message" => "Notification sent", "response" => $result]);
