<?php

function getAccessToken() {
    $jsonKey = json_decode(file_get_contents(__DIR__ . '/../config/firebase.json'), true);

    $header = base64_encode(json_encode(["alg"=>"RS256","typ"=>"JWT"]));

    $now = time();
    $payload = base64_encode(json_encode([
        "iss" => $jsonKey['client_email'],
        "scope" => "https://www.googleapis.com/auth/firebase.messaging",
        "aud" => $jsonKey['token_uri'],
        "exp" => $now + 3600,
        "iat" => $now
    ]));

    $signatureInput = $header . "." . $payload;

    openssl_sign($signatureInput, $signature, $jsonKey['private_key'], 'sha256');

    $jwt = $signatureInput . "." . base64_encode($signature);

    $ch = curl_init($jsonKey['token_uri']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion" => $jwt
    ]));

    $response = json_decode(curl_exec($ch), true);

    return $response['access_token'];
}

function sendFCM($token, $title, $body, $data = []) {

    $accessToken = getAccessToken();
    $projectId = "golftracker-65deb"; // 🔥 sesuaikan

    $url = "https://fcm.googleapis.com/v1/projects/$projectId/messages:send";

    $payload = [
        "message" => [
            "token" => $token,

            /// 🔥 WAJIB → BIAR MUNCUL NOTIF
            "notification" => [
                "title" => $title,
                "body" => $body
            ],

            /// 🔥 DATA UNTUK DEEP LINK
            "data" => array_map('strval', $data)
        ]
    ];

    $headers = [
        "Authorization: Bearer $accessToken",
        "Content-Type: application/json"
    ];

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

    $result = curl_exec($ch);

    if ($result === false) {
        return curl_error($ch);
    }

    curl_close($ch);

    return $result;
}