<?php
// Requiere que tengas instalada la librería firebase/php-jwt
// Instala con: composer require firebase/php-jwt
require 'vendor/autoload.php';

use Firebase\JWT\JWT;

$json ='{
  "type": "service_account",
  "project_id": "gbco-wms",
  "private_key_id": "d6c53873d7b4eba992280ba3593d57c6d7ddb191",
  "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDczE5DXYF0QMT7\nuushrsPqglrpcNF+6vIbKp/JKrZSLxEqCXn5TOSxXcfg7LGLP7g/geKJckdEjI0T\nF2QkJLvnpPJt00ssOu9tSk4+82Nc/1iRrmTR4hhYpL/wkBCPDGii8rbfgbAU8eEI\n0SXkPoZ+gbLTixmjyJ+L3zslKx3CXzXtpGvQxf+3+hF/lC3BanM4nI6SSvLG5RPU\nTbgNRF/O5f7n2t9vJSRH2G64SJE+ErGoUOyxZ9IJv9/caoMD0Lva/g3YIuCxnvfg\n1lNXr/I4WyukeOK4TYDQfZMdM3mSL/Ix6EHIYH8BkWZeAqHQ2SyyeG8sItQj4b02\nNP7X2gyzAgMBAAECggEAJDDAqz4KV/m9z90FaVHx/uA68oRxcjIkWNuVsS11EOdy\nEsfW3EwEOCY8+tsRBtf85Tvu28SFdfDrtrNg0KPMwN1Cd0noymkmkW1ager24Gli\nJQ7Gq7g5cV4fr9iNPkU0aXELFHt3VxeGYSGW6mBtPxMXMqFcJIJf1FdUpHT6vb77\nTVdKId/XCmDR25YOopMseqqOp05/UrOYEFXnlZ98lY4c5L/RcDqX/VNZF4NS1tl3\n5lAFOgP9Zjf4JJJYMPtBaHQRM3HApneMAHHwzH+KAsZ/KZSXuyV9NEalBrAWnvae\nWwsobxypyS4oxnA8IF34skxpw/Ute5fjnsxMihprgQKBgQD8hZcyfmOz4PlXERgL\n6NRuKa9D5VqxCEQtIhKBokilU964mWW5J/QxpN+eE3TOGVX7Zt4BCQiwFtNyt8lg\nVWGZIOkzW16goK7agx4CDBEMVLJC4wXBuRTyweLfIeG+u6mmcBY8QDeoZLPU9DF2\ny9PH6Co0ajpBiapYBuKVygwhoQKBgQDf1trbNOGJITfSTR9fvuZnGw5vF/aIizm9\nR0aCvPyIpcQO/xTFCy6nncrbicrLDS8iRB612Eq/I0TtudoTNPQPPU+tpdRn6FL1\nFzorrbQw/9EXRfWx/sNLbeMSnAN7qLDHvNPML7fCaD8WnkU3BDVdifsyyfDtVclo\nK9gramQ10wKBgA+ylkWTSctizt00uNP0s0/t03FbDpo2s1ZC6feZCP8OCahcENDD\nxRBY+XWwK/Cr7oZkTKSv1RRtNtPIzQHqDNkiDJ0ervE5S+VVhUYHTgAAO9yglDkI\nsl6s4teQGaJrtA4epaM1MsCLEgrI61JBNXcV3ZnIiLqOPkKemvNIzhxBAoGBAMOz\nAzF3sF/GDRnul6mMK8ClZR834jFLGDYmJL2VIW0PELTTy4Li3e1qBbufYw/X/QeG\naxsteVxXJ6J4RPNZ7q+MOSdmvqgB9NWXcyJRAiN85X/liIQQawp9jnPstxbcS4K1\n0q7IYW602cOaqIULRuT7CAZFjEDUKfzLqHl80RRFAoGAA2wabhuoC/7V4nEUuLQs\nyOqdczxkSQJI61FpLTU3g2DsOfZHor5WPDLmL6zIgmeJMZjlVraAfWj2mEJsbjhT\nGGeDEMPP69GuW04RGYLWql5PaWbBJQaioZT7ZqBNkeQQ8WImt43qbZ9LJ9wzVHi/\nQLHaT97fXUn6ZASGWSj3wys=\n-----END PRIVATE KEY-----\n",
  "client_email": "firebase-adminsdk-fbsvc@gbco-wms.iam.gserviceaccount.com",
  "client_id": "106877768691289401587",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-fbsvc%40gbco-wms.iam.gserviceaccount.com",
  "universe_domain": "googleapis.com"
}';
$serviceAccount=json_decode($json,true);

/* Uso
try {
    $token = getAccessToken($json);
    echo "Access Token: " . $token . PHP_EOL;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}*/

   $title  = 'Sin título';
    $body   = 'Sin mensaje';
    $token  = "en--2pWKSWKcdPqPpBf1I6:APA91bFNG1lFxXaduj7t31IjpOh2mRjProRAtJO-zQmxo4L8nppCV2vPzkjPL-657kGGQMlympCs-vs-RmkAiABZuLq_sg1V3C6M3EKl-WILxDynvUuAjh0";

    try {
        //$serviceAccountFile = __DIR__ . "/service-account.json"; // Ruta a tu JSON
        $projectId = "gbco-wms"; // Tu project_id en Firebase

        $result = sendNotification($title, $body, $token, $json, $projectId);

        header('Content-Type: application/json');
        echo json_encode($result, JSON_PRETTY_PRINT);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }



function getAccessToken($serviceAccountFile)
{
    $serviceAccount = json_decode($serviceAccountFile, true);

    $now = time();
    $jwtPayload = [
        'iss' => $serviceAccount['client_email'],
        'sub' => $serviceAccount['client_email'],
        'aud' => 'https://oauth2.googleapis.com/token',
        'iat' => $now,
        'exp' => $now + 3600,
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
    ];

    // Crear JWT
    $jwt = JWT::encode($jwtPayload, $serviceAccount['private_key'], 'RS256');

    // Intercambiar JWT por un Access Token
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt,
    ]);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        throw new Exception('cURL error: ' . curl_error($ch));
    }
    curl_close($ch);

    $json = json_decode($response, true);
    if (isset($json['access_token'])) {
        return $json['access_token'];
    } else {
        throw new Exception("Error al obtener token: " . $response);
    }
}






function sendNotification($title, $body, $deviceToken, $serviceAccountFile, $projectId)
{
    $accessToken = getAccessToken($serviceAccountFile);

    $message = [
        "message" => [
            "token" => $deviceToken,
            "notification" => [
                "title" => $title,
                "body"  => $body,
            ],
            "android" => [
                "notification" => [
                    "icon" => "ic_launcher" // Asegúrate que exista en tu app React
                ]
            ]
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://fcm.googleapis.com/v1/projects/$projectId/messages:send");
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $accessToken",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        return ['error' => curl_error($ch)];
    }
    curl_close($ch);

    return json_decode($response, true);
}

// ========================
// Endpoint
// ========================
 









