<?php
// ── Chupito — FCM push sender (HTTP v1 API) ────────────────────────────────
// Použitie:
//   require 'fcm_send.php';
//   fcmSendToTopic('restaurant_mp', 'Nová rezervácia', 'Ján Novák · 2 os. · 19:00');
//
// Vyžaduje service account JSON z Firebase:
//   Firebase console -> Project settings -> Service accounts -> Generate new private key
//   Uložiť ako /var/www/keys/chupito-firebase-sa.json (mimo web rootu!)

define('FCM_SA_PATH', '/var/www/keys/chupito-firebase-sa.json');

function fcmGetAccessToken(): ?string {
    if (!file_exists(FCM_SA_PATH)) {
        error_log('FCM: service account JSON nenájdený: ' . FCM_SA_PATH);
        return null;
    }
    $sa = json_decode(file_get_contents(FCM_SA_PATH), true);
    if (!$sa) return null;

    // Cache tokenu (platí 1h) v /tmp
    $cacheFile = '/tmp/fcm_token_cache.json';
    if (file_exists($cacheFile)) {
        $cache = json_decode(file_get_contents($cacheFile), true);
        if ($cache && $cache['expires'] > time() + 60) {
            return $cache['token'];
        }
    }

    // JWT pre OAuth2
    $now = time();
    $header = rtrim(strtr(base64_encode(json_encode(['alg' => 'RS256', 'typ' => 'JWT'])), '+/', '-_'), '=');
    $claims = rtrim(strtr(base64_encode(json_encode([
        'iss' => $sa['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'iat' => $now,
        'exp' => $now + 3600,
    ])), '+/', '-_'), '=');

    $signInput = $header . '.' . $claims;
    openssl_sign($signInput, $signature, $sa['private_key'], 'sha256WithRSAEncryption');
    $jwt = $signInput . '.' . rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');

    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
            'assertion' => $jwt,
        ]),
    ]);
    $resp = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (!isset($resp['access_token'])) {
        error_log('FCM: OAuth token error: ' . json_encode($resp));
        return null;
    }

    file_put_contents($cacheFile, json_encode([
        'token' => $resp['access_token'],
        'expires' => time() + (int)($resp['expires_in'] ?? 3600),
    ]));
    return $resp['access_token'];
}

function fcmSendToTopic(string $topic, string $title, string $body, array $data = []): bool {
    $sa = json_decode(@file_get_contents(FCM_SA_PATH), true);
    if (!$sa || empty($sa['project_id'])) return false;

    $accessToken = fcmGetAccessToken();
    if (!$accessToken) return false;

    $message = [
        'message' => [
            'topic' => $topic,
            'notification' => [
                'title' => $title,
                'body' => $body,
            ],
            'android' => [
                'priority' => 'HIGH',
                'notification' => [
                    'channel_id' => 'reservations',
                    'sound' => 'default',
                    'default_vibrate_timings' => true,
                ],
            ],
            'data' => empty($data) ? (object)[] : array_map('strval', $data),
        ],
    ];

    $url = 'https://fcm.googleapis.com/v1/projects/' . $sa['project_id'] . '/messages:send';
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode($message),
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code !== 200) {
        error_log("FCM send failed ($code): $resp");
        return false;
    }
    return true;
}

// Prihlásenie FCM tokenu zariadenia na topic (volané z api.php register_fcm_token)
function fcmSubscribeTokenToTopic(string $fcmToken, string $topic): bool {
    $accessToken = fcmGetAccessToken();
    if (!$accessToken) return false;

    $ch = curl_init("https://iid.googleapis.com/iid/v1/$fcmToken/rel/topics/$topic");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $accessToken,
            'access_token_auth: true',
            'Content-Length: 0',
        ],
    ]);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $code === 200;
}
