<?php
// firebase_helper.php
// Helper to verify Invite Codes via Firestore REST API

function getServiceAccount() {
    // Credentials copied from api.php
    return [
       'email' => 'firebase-adminsdk-fbsvc@guess-63e3d.iam.gserviceaccount.com',
       // The Private Key (PEM format)
       'key' => "-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCpNSreOf0nMZ0i
DdraEEXF9I+umjMIUsYEjFuGykrVldCdkOMHgVGkD0cOP7ccLcppaohLOaAwzDV+
Ibv/XqWkVyFr9aTcZGJgjMENVz7ny4kRN5JLCJ5FqxcefIGFPhAnKEk0BiLmbPA4
fmUOj4xeGnqAE+kdLlwfLqlIsFckMfOElt2K9qQ1D5dRn++Dt1m/IFahKRU5HZmH
NQeu8nZXU7HNZQT5vX3IwsfXQqXZIfcIQJGxCE2aMQ+GvctPWdWZitLG5HlAXglu
xc4bA6SiNlYfgDUo0jgbOAJmzZbwyzYQSZqWPAnOTkL/UPgZRB8bIRY2hkxDQ63H
0Vbm0jXRAgMBAAECggEAAQLNMsQImIA9mzUligjhhWTPVS0OrI2ct3sg+cBMi/Bb
bWPLU+UKWEZdUInQBrOEq2gfF3P3WmGBg94SZXkVg2D1cbc8qrKl89Iqk1Twx0Yz
JasvxedvuN2A0duWWoQb90N7PkL+rfDe53BkjNd/mzIaowomFJ/iullpBRFFF5HQ
kQEUVPB8yG3BmxDmSiQYKsIQbjyhRVvpsaATutqCUCuDF7CR3DSqg2EddTLmrOMe
YF6zdmpmlSIVXIeTni0gUfjSVGAmI+Wq/gruIsf+PnLQ8cjix54z+z4hCe2+481h
9pNXJa/63VbpZVJGgonj0SQBmafb8W/GB9tpUSLtEQKBgQDTm/zs592T+JQIU7nI
pPZGxrqxZ0Dz9nfB+kTk/mQ5OUuJZXc2kKyU/pKj/iTyxSXzABfF/8llsxtKCP1v
DgqszJTAfz5pnz+zoJaJMTWqofM5QvwHKz3XJ/XDBJ0QOK06Q842RdpXP1jszfpQ
HxiRnNN/3vHSt3DOnqKjufyAnwKBgQDMtBfCRweqOakC+e+58v0q94T6K0P77Zsg
7t4a9kib1oS3miEY32xoUwDPOs50KS+jmnzh6wPYzogU2rRZp/pr7ssovlPtBTP7
n+NPtUVQvZuOFbnbt8d970OENoaVZf7mUr+2v19NcjEmrQyrOPbe6Hreez0gp1LI
vLmzZeuDjwKBgQCI1RNF9eDX8CN5BvrZfaIqvhK26HedycBC1Jx8Huub/SqVG+Fs
jTyr07nrBUnLGiSh72twAyit9JUu2IVYrJHGjzuZBi7LichdVPhCmmmDftmSK3hh
AlsRJ5RJmNAfTybkyDet7Jl1VWchKUg1SwZOEkTJKNbiVPBDC11L1dYrLQKBgQCl
W2VF3rLmYyWP7e4ku5CewMt+eqy0OT/y3oI0LXaBzEvxNGQ//1tG+qXQwKQ9WXfO
JOF0ba/x1wQ+NF0zf2ne/krGYtjQwj83p/SrUrbnfgLGR+6W+mH/7OMRTipxTK8X
xwhuyzBlEzV5FJkDR0TE0+9NAShj1EYfObSYomAZKQKBgQCWl9/7vjoit7oQi9sQ
rQCv3LH7LzJV8eMSho8A0N7nLGVQJwCnimehdtXBQkd9/UHJr2EjjY5QTuG1ECvb
RMYKUI/IclTUIWA2KMnDoYB0P742oNULTZWO7gsKfG2d1QyD24cp14hEzNexZR/U
QJp9eQ/SV+qVFg/PTX3wq6WRcw==
-----END PRIVATE KEY-----"
    ];
}

function getGoogleAccessToken() {
    $creds = getServiceAccount();
    $now = time();
    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT']);
    // Scope for Firestore/Datastore
    $payload = json_encode([
        'iss' => $creds['email'],
        'sub' => $creds['email'],
        'aud' => 'https://www.googleapis.com/oauth2/v4/token',
        'iat' => $now,
        'exp' => $now + 3600,
        'scope' => 'https://www.googleapis.com/auth/datastore'
    ]);
    
    // Base64Url Encode
    $b64Header = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
    $b64Payload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
    $signatureInput = $b64Header . '.' . $b64Payload;
    
    $signature = '';
    $key = $creds['key'];
    // Sign using RSA256
    if (!openssl_sign($signatureInput, $signature, $key, OPENSSL_ALGO_SHA256)) {
        return null; // Key error
    }
    $b64Signature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
    $jwt = $signatureInput . '.' . $b64Signature;
    
    // Exchange JWT for Access Token
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v4/token');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Silent errors
    $response = curl_exec($ch);
    curl_close($ch);
    
    $data = json_decode($response, true);
    return $data['access_token'] ?? null;
}

function checkFirestoreInvite($code, $debug = false) {
    if (empty($code)) return false;
    
    // 1. Admin Overrides
    $local = ['vyomotive', 'bypass_update', 'vyo_client_verified'];
    if (in_array(strtolower($code), $local)) return true;

    // 2. Get Access Token
    $token = getGoogleAccessToken();
    if (!$token) {
        if ($debug) echo "Failed to get access token.<br>";
        return false;
    }
    
    $projectId = 'guess-63e3d';
    
    // 3. Check Collections
    if (runInviteQuery($projectId, $token, 'tenants', $code, $debug)) return true;
    if (runInviteQuery($projectId, $token, 'stores', $code, $debug)) return true;
    if (runInviteQuery($projectId, $token, 'organizations', $code, $debug)) return true;
    
    return false;
}

function runInviteQuery($projectId, $token, $collection, $code, $debug = false) {
    $url = "https://firestore.googleapis.com/v1/projects/$projectId/databases/(default)/documents:runQuery";
    
    if ($debug) echo "Querying $collection for code '$code'...<br>";

    $query = [
        'structuredQuery' => [
            'from' => [['collectionId' => $collection]],
            'where' => [
                'fieldFilter' => [
                    'field' => ['fieldPath' => 'invite_code'],
                    'op' => 'EQUAL',
                    'value' => ['stringValue' => $code]
                ]
            ],
            'limit' => 1
        ]
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($query));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $token",
        "Content-Type: application/json"
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    
    if ($debug) {
        echo "Response Code: " . $info['http_code'] . "<br>";
        echo "Response Body: " . htmlspecialchars(substr($res, 0, 500)) . "...<br>";
    }

    $data = json_decode($res, true);
    
    // Check if any document was returned
    if (is_array($data) && !empty($data)) {
        foreach ($data as $item) {
            if (isset($item['document'])) {
                if ($debug) echo "MATCH FOUND in $collection!<br>";
                return true;
            }
        }
    }
    
    if ($debug) {
        echo "No match in $collection. Dumping first 3 docs to verify schema:<br>";
        debugDump($projectId, $token, $collection);
    }
    
    return false;
}

function debugDump($projectId, $token, $collection) {
    if ($collection === 'organizations') return; // Skip unnecessary dump
    
    $url = "https://firestore.googleapis.com/v1/projects/$projectId/databases/(default)/documents/$collection?pageSize=3";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $token"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $res = curl_exec($ch);
    curl_close($ch);
    
    $data = json_decode($res, true);
    if (isset($data['documents'])) {
        foreach ($data['documents'] as $doc) {
            $fields = $doc['fields'] ?? [];
            if (isset($fields['invite_code'])) {
                echo "Found Doc ID: " . basename($doc['name']) . " | invite_code: " . ($fields['invite_code']['stringValue'] ?? 'N/A') . "<br>";
            } else {
                echo "Found Doc ID: " . basename($doc['name']) . " | [No invite_code field]<br>";
                // print_r($fields); // Uncomment for full dump
            }
        }
    } else {
        echo "No documents found or permission denied.<br>";
        echo "Raw: " . htmlspecialchars(substr($res, 0, 200)) . "<br>";
    }
}
?>
