<?php
// Function to send FCM notification using HTTP v1 API
function sendPushNotification($to, $title, $body, $data = []) {
    $serviceAccountPath = __DIR__ . '/firebase_service_account.json';
    
    if (!file_exists($serviceAccountPath)) {
        error_log("FCM Error: Service account file missing at $serviceAccountPath");
        return false;
    }

    $serviceAccount = json_decode(file_get_contents($serviceAccountPath), true);
    $projectId = $serviceAccount['project_id'];

    // 1. Get Access Token (Self-signed JWT for Google OAuth2)
    $accessToken = getGoogleAccessToken($serviceAccount);
    
    if (!$accessToken) {
        error_log("FCM Error: Could not generate access token");
        return false;
    }

    $url = "https://fcm.googleapis.com/v1/projects/$projectId/messages:send";
    
    // Including title/body in 'data' specifically for B4A's GetData to pick up
    $data['title'] = $title;
    $data['body'] = $body;

    // v1 Structure is slightly different (nested under 'message')
    $payload = [
        'message' => [
            'token' => $to,
            'notification' => [
                'title' => $title,
                'body' => $body
            ],
            'data' => array_map('strval', $data), // Data must be strings
            'android' => [
                'priority' => 'high',
                'notification' => [
                    'sound' => 'default',
                    'click_action' => 'OPEN_MAIN_ACTIVITY'
                ]
            ]
        ]
    ];

    $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_SSL_VERIFYPEER, false); // For local XAMPP issues
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        error_log("FCM Error Response ($httpCode): " . $result);
        
        // Check if token is invalid/expired
        $resultData = json_decode($result, true);
        if (isset($resultData['error'])) {
            $errorCode = $resultData['error']['status'] ?? '';
            
            // Token is invalid, expired, or unregistered
            if (in_array($errorCode, ['INVALID_ARGUMENT', 'NOT_FOUND', 'UNREGISTERED'])) {
                error_log("FCM: Token is invalid/expired: $to");
                markTokenAsInvalid($to);
            }
        }
    }
    
    return $result;
}

// Mark token as invalid in database
function markTokenAsInvalid($token) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("UPDATE fcm_tokens SET is_valid = 0, updated_at = NOW() WHERE token = ?");
        $stmt->execute([$token]);
        error_log("FCM: Marked token as invalid in database");
    } catch (PDOException $e) {
        error_log("FCM: Could not mark token as invalid: " . $e->getMessage());
    }
}

// Helper to generate Google Access Token without using heavy libraries
function getGoogleAccessToken($sa) {
    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    $now = time();
    $payload = json_encode([
        'iss' => $sa['client_email'],
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'exp' => $now + 3600,
        'iat' => $now
    ]);

    $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
    
    $signatureInput = $base64UrlHeader . "." . $base64UrlPayload;
    openssl_sign($signatureInput, $signature, $sa['private_key'], 'SHA256');
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    
    $jwt = $signatureInput . "." . $base64UrlSignature;

    $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_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));
    
    $res = json_decode(curl_exec($ch), true);
    curl_close($ch);
    
    return $res['access_token'] ?? null;
}
?>
