<?php

function getFCMServerToken() {
    // Extracted from your app/lib/screens/serverkey.dart
    $private_key = "-----BEGIN PRIVATE KEY-----\n" .
        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDYEG75/I1tN+oQ\n" .
        "+U16bWieAWn6FCBtaExn8enhF8GWl0dKzJgBSLJr21Ix4BqN6GwpCCMP5vKTQ/ZF\n" .
        "LVrQzEoJjeEptRqp+gWyaK4E1NwWmoiYqg7QRKI1kfsZdfYRPZepjO7+45CO5Klp\n" .
        "vAiTsKmtLEe98ok1MuslsfZMInEuAVxFBOLSn6tOKuqZkQQ7hhUD5CK3+YyWsxmv\n" .
        "D2+SjkEw62DxkzdoXP0iPgEsOOIMEUTj+RNdxJuHW8mnX8G+G70OekICKi+gI6Gt\n" .
        "SvZ6LGdtjnt1bajdV2y1vlIVInc7eO/uDJWq2rIteoI9OMT/W8PUrHpJosEySZGf\n" .
        "IhTOb7wJAgMBAAECggEASj4vXBAnqrFtaSK5OEnTCoQy3b8/u0h9BLSwKGwI1c2q\n" .
        "ri2qR7qqsHwe/MtkZIHKdLj6j1LM5MSUIYYpsBiakjjh93pnLKQghAMLVNatv8if\n" .
        "ClJZH8CNunmsfj217YusCxNF5mjcufUhr5bwnYs1aq+OAVuPQSv7eCr0Foo5ONSV\n" .
        "1PlmZzo3lzZNsrTTZ8TMsaJsIU9UziQrAppfKfSwV495vDQ2LlO53YwI0Ky5GWOE\n" .
        "OK5h3fHJRtDG27NETVHAYyuMyZsxTih2E0Lwq5+TbA4gmySttuEn6ZM8DnQTAAtY\n" .
        "ACYYpmtd54DS8dtJkVAlGoA69wtE0FaLB2w6K4ilXwKBgQD75PJZ6tgu3rAP8oeG\n" .
        "KagwUTCZAoIcZ5WSa4+BsowaOqrBwuRbQRFgefxdA/mZ91hvsIqC47wyQ6KD7Ief\n" .
        "DDiWqf9ukoY7il5XS67zcOt1xjXISAYYzKXEnCJC0bcxzeMGuqxH1+4COmCEuzzQ\n" .
        "VJLtnGT88Yx4XxI097tXaZTBswKBgQDblftuTZD3st1Omu+G34hvdh1Y+kQDm/sH\n" .
        "2sSzvc3SftK1KQLUmVy37nXN9dvCCOda1CCxitJQfKu1XmvvgoLIHoLLmhDWIduA\n" .
        "Nik5mfnXvqT8/HlIAkrTIumfGX4dM4l8O8gbWC9T/YGak4oRKOF9NRNMxA0foGFp\n" .
        "1GjjJknVUwKBgGIiI7icIXTBFN5hoiLGf9uzBbfWnlHqmP7eIJ5qrOJbEMND5isX\n" .
        "AmoPnB2wusEc97srkArGJj9+0gWLVJrF7BXmTLkLJHh1w6NGvPXifBj6C2HnjViE\n" .
        "AeDC4yYdBb3FdDje6NdkbDk5/Pg46cxP5p3jXASfJhaPE0zHZpj7bRS5AoGAN5X5\n" .
        "9ewwvGNM3m8eH1hKo1yVBUclHHzJyS06Cf4MMjLkh/N/we2oqO72Z1LLdIzoc/eq\n" .
        "5warQrCsjtb+H707+givN3cit/IOLKCJQwmVU2XxQhFvaikaY+Q8m4fKgv3e2dIQ\n" .
        "T8u8/1f3DPg4RSvCGP3sisw+PjlNL4sTmhzBJ/0CgYEA2JbACnS++/0YWIEpFMNQ\n" .
        "tdtlkjeCVNUWHaLjq3y89Lj0jmC9bp5imnsNKo5Rd6Z5RiD89XN5Ia9W4kMK2nQc\n" .
        "E3nH3wM/m4EfFo4hg6hJQY6So+bafx5o5J7v8hKJMxPSdkw3kwfxRlzKJpw0TzeS\n" .
        "Bn347235cfLd1b8XLF+1gFk=\n" .
        "-----END PRIVATE KEY-----\n";
    $client_email = "firebase-adminsdk-fbsvc@dizaartshopping.iam.gserviceaccount.com";
    $scopes = "https://www.googleapis.com/auth/firebase.messaging";

    $header = json_encode(["alg" => "RS256", "typ" => "JWT"]);
    $now = time();
    $claim = json_encode([
        "iss" => $client_email,
        "scope" => $scopes,
        "aud" => "https://oauth2.googleapis.com/token",
        "exp" => $now + 3600,
        "iat" => $now
    ]);

    $base64UrlEncode = function($data) {
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($data));
    };

    $headerStr = $base64UrlEncode($header);
    $claimStr = $base64UrlEncode($claim);
    $signatureInput = $headerStr . '.' . $claimStr;

    $signature = '';
    openssl_sign($signatureInput, $signature, $private_key, "sha256WithRSAEncryption");
    $jwt = $signatureInput . '.' . $base64UrlEncode($signature);

    $ch = curl_init("https://oauth2.googleapis.com/token");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));
    
    $res = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($status === 200) {
        $json = json_decode($res, true);
        return $json['access_token'] ?? '';
    }
    return '';
}

function sendFCMv1Notification($device_token, $title, $body, $image_url = null) {
    if (empty($device_token)) return false;

    // Dynamically generate the server token!
    $server_token = getFCMServerToken();
    if (empty($server_token)) return false;

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

    $data = [
        "message" => [
            "token" => $device_token,
            "notification" => [
                "title" => $title,
                "body" => $body
            ],
            "android" => [
                "priority" => "high",
                "notification" => [
                    "sound" => "default",
                    "channel_id" => "high_importance_channel",
                    "default_vibrate_timings" => true,
                    "default_light_settings" => true
                ]
            ],
            "data" => [
                "click_action" => "FLUTTER_NOTIFICATION_CLICK",
                "title" => $title,
                "body" => $body,
                "type" => "msg"
            ]
        ]
    ];

    // Add image if provided
    if (!empty($image_url)) {
        $data["message"]["notification"]["image"] = $image_url;
        $data["message"]["android"]["notification"]["image"] = $image_url;
        $data["message"]["data"]["image"] = $image_url; // For foreground local notifications
    }

    $headers = [
        'Authorization: Bearer ' . $server_token,
        '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_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $result = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($httpcode != 200) {
        error_log("FCM Error: HTTP $httpcode - $result - $error");
        echo "FCM Error: HTTP $httpcode - $result\n";
    }

    return $httpcode == 200;
}
?>
