<?php
header("Content-Type: application/json; charset=utf-8");

$serviceAccountFile = "noti.json";

$title = trim($_GET['title'] ?? '');
$body  = trim($_GET['body'] ?? '');
$image = trim($_GET['imagelink'] ?? '');
$topic = trim($_GET['topic'] ?? '');
$token = trim($_GET['token'] ?? '');
$extra = trim($_GET['extra'] ?? '');

if ($title == '' || $body == '') {
    exit(json_encode([
        "status" => false,
        "message" => "Title and Body required"
    ]));
}

if (!file_exists($serviceAccountFile)) {
    exit(json_encode([
        "status" => false,
        "message" => "noti.json file not found"
    ]));
}

function base64UrlEncode($data)
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function getAccessToken($jsonFile)
{
    $credentials = json_decode(file_get_contents($jsonFile), true);

    $header = [
        "alg" => "RS256",
        "typ" => "JWT"
    ];

    $now = time();

    $payload = [
        "iss"   => $credentials['client_email'],
        "scope" => "https://www.googleapis.com/auth/firebase.messaging",
        "aud"   => "https://oauth2.googleapis.com/token",
        "iat"   => $now,
        "exp"   => $now + 3600
    ];

    $jwtHeader  = base64UrlEncode(json_encode($header));
    $jwtPayload = base64UrlEncode(json_encode($payload));

    $signatureInput = $jwtHeader . "." . $jwtPayload;

    openssl_sign(
        $signatureInput,
        $signature,
        $credentials['private_key'],
        "SHA256"
    );

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

    $postData = [
        "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion"  => $jwt
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://oauth2.googleapis.com/token");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        return false;
    }

    curl_close($ch);

    $result = json_decode($response, true);

    return $result['access_token'] ?? false;
}

$accessToken = getAccessToken($serviceAccountFile);

if (!$accessToken) {
    exit(json_encode([
        "status" => false,
        "message" => "Access token generation failed"
    ]));
}

$credentials = json_decode(file_get_contents($serviceAccountFile), true);

$projectId = $credentials['project_id'];

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

$message = [
    "message" => [

        "notification" => [
            "title" => $title,
            "body"  => $body
        ],

        "data" => [
            "title" => $title,
            "body"  => $body,
            "image" => $image,
            "extra" => $extra
        ],

        "android" => [
            "priority" => "HIGH",
            "notification" => [
                "sound" => "default"
            ]
        ]
    ]
];

if ($image != '') {
    $message["message"]["android"]["notification"]["image"] = $image;
}

if ($token != '') {
    $message["message"]["token"] = $token;
} elseif ($topic != '') {
    $message["message"]["topic"] = $topic;
} else {
    exit(json_encode([
        "status" => false,
        "message" => "Token or Topic required"
    ]));
}

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

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $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($message));

$response = curl_exec($ch);

$error = curl_error($ch);

curl_close($ch);

if ($error) {
    echo json_encode([
        "status" => false,
        "message" => $error
    ]);
    exit;
}

$result = json_decode($response, true);

if (isset($result['name'])) {
    echo json_encode([
        "status" => true,
        "message" => "Notification Sent Successfully",
        "response" => $result
    ]);
} else {
    echo json_encode([
        "status" => false,
        "message" => "Failed",
        "response" => $result
    ]);
}
?>