<?php
require 'vendor/autoload.php';

use Firebase\JWT\JWT;

// ==== CONFIGURACIÓN ====
// Ruta al archivo JSON de tu cuenta de servicio de Firebase
$serviceAccountPath = '/home/gbcoha2h/public_html/opfhub/ApiV1/gbco-wms-firebase-adminsdk-fbsvc-d6c53873d7.json';  //  AJUSTA ESTA RUTA

// ==== ACTIVAR ERRORES ====
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ==== VALIDAR DATOS DE ENTRADA ====
$title = $_POST['title'];
$body = $_POST['body'];
$deviceToken = $_POST['token'];
error_log("LLEGA titulo: ".$title." body: ".$body. " token: ".$token."\n", 3, "php.log");

if (!$title || !$body || !$deviceToken) {
    http_response_code(400);
    echo json_encode(["error" => "Faltan parámetros (title, body, token)"]);
    exit;
}

// ==== CARGAR CUENTA DE SERVICIO ====
$serviceAccount = json_decode(file_get_contents($serviceAccountPath), true);
$privateKey = str_replace("\\n", "\n", $serviceAccount['private_key']);
$clientEmail = $serviceAccount['client_email'];
$projectId = $serviceAccount['project_id'];

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

$jwt = JWT::encode($jwtPayload, $privateKey, 'RS256');

// ==== SOLICITAR ACCESS TOKEN ====
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' => $jwt
]));

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

$tokenData = json_decode($tokenResponse, true);
$accessToken = $tokenData['access_token'] ?? null;

if (!$accessToken) {
    http_response_code(500);
    echo json_encode(["error" => "No se pudo obtener el token de acceso"]);
    exit;
}

// ==== ENVIAR MENSAJE ====
$fcmUrl = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";

$payload = [
    'message' => [
        'token' => $deviceToken,
        'notification' => [
            'title' => $title,
            'body' => $body,
            'image' => 'https://opfhub.globalb.co/ApiV1/verde.png'
        ],
        'android' => [
        'priority' => 'HIGH',
        'notification' => [
            'icon' => 'ic_notification',
            'color' => '#2196F3'
        ]
        ],
        'data' => [
            'click_action' => 'FLUTTER_NOTIFICATION_CLICK'
        ]
    ]
];

/*$payload = [
    'message' => [
    'token' => $deviceToken,
    'notification' => [
        'title' => '📦 Nuevo inventario disponible',
        'body'  => 'Hay productos sin escanear en el Slot 3B. ¡Revísalos ahora!',
        'image' => 'https://tuservidor.com/img/slot3B.jpg'
    ],
    'android' => [
        'priority' => 'HIGH',
        'notification' => [
            'channel_id' => 'notificaciones_wms',
            'color' => '#2196F3',
            'icon' => 'ic_notification'
        ]
    ],
    'data' => [
        'accion' => 'abrir_slot',
        'slot_id' => '3B',
        'nivel_alerta' => 'alta'
    ]
]
];*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $accessToken",
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// ==== RESPUESTA ====
header('Content-Type: application/json');
echo json_encode([
    "http_code" => $httpCode,
    "response" => json_decode($response, true)
]);







/*
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'vendor/autoload.php';

use Firebase\JWT\JWT;

// === CONFIGURACIÓN ===
$serviceAccountPath = '/home/gbcodesa/public_html/opfhub/ApiV1/gbco-wms-f1c1b9a5d3d2.json'; 
$deviceToken = 'ejBoRdUOTlWZDoFfpQd0fU:APA91bFbnaXLoksltvoXREYdqkmPnI3BfHKBUfV9NV2bDS4kUs77KiPyuWqt7aauicz_es62U4DPiY9kcUI78uq3T-3tN2Z5M6ybprrBtdxF2LrMsR_z2lk'; 

// === CARGAR CUENTA DE SERVICIO ===
$serviceAccount = json_decode(file_get_contents($serviceAccountPath), true);
$privateKey = $serviceAccount['private_key'];
$clientEmail = $serviceAccount['client_email'];
$projectId = $serviceAccount['project_id'];

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

$jwt = JWT::encode($jwtPayload, $privateKey, 'RS256');

// === SOLICITAR ACCESS TOKEN ===
$tokenRequestData = [
    '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_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($tokenRequestData));

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

if (!$tokenResponse) {
    exit("Error al obtener el token de acceso.\n");
}

$tokenData = json_decode($tokenResponse, true);
$accessToken = $tokenData['access_token'];

if (!$accessToken) {
    exit("No se pudo obtener el access token.\n");
}

// === ENVIAR MENSAJE A FCM ===
$fcmUrl = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";

$notification = [
    'message' => [
        'token' => $deviceToken,
        'notification' => [
            'title' => ' Notificación desde WMS',
            'body'  => 'Tienes nuevos productos pendientes por escanear.'
        ],
        'data' => [
            'click_action' => 'FLUTTER_NOTIFICATION_CLICK'
        ]
    ]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $fcmUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $accessToken",
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($notification));

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo " Código HTTP: $httpCode\n";
echo " Respuesta:\n$response\n";

