<?php
header('Content-Type: application/json; charset=UTF-8');
require_once __DIR__ . '/firebase-rtdb-admin.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
    exit;
}

$raw = file_get_contents('php://input');
$body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
if (!is_array($body)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON']);
    exit;
}

$idToken = isset($body['idToken']) ? trim((string) $body['idToken']) : '';
if ($idToken === '') {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'idToken is required.']);
    exit;
}

$bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (!is_readable($bootPath)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Server not configured: firebase-admin-bootstrap.local.php missing.']);
    exit;
}
$boot = include $bootPath;
if (!is_array($boot)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Invalid firebase-admin-bootstrap.local.php.']);
    exit;
}
$webKey = isset($boot['firebase_web_api_key']) ? trim((string) $boot['firebase_web_api_key']) : '';
if ($webKey === '' || $webKey === 'PASTE_FIREBASE_WEB_API_KEY_HERE') {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Bootstrap config incomplete.']);
    exit;
}

$creatorCfgPath = __DIR__ . '/creator-access.local.php';
if (!is_readable($creatorCfgPath)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Creator access config missing.']);
    exit;
}
$creatorCfg = include $creatorCfgPath;
if (!is_array($creatorCfg)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Invalid creator access config.']);
    exit;
}
$allowedEmails = array_map(static fn($v) => strtolower(trim((string) $v)), (array)($creatorCfg['allowed_emails'] ?? []));
$allowedUids = array_map(static fn($v) => trim((string) $v), (array)($creatorCfg['allowed_uids'] ?? []));

$verify = firebase_verify_id_token($idToken, $webKey);
if (isset($verify['error'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => $verify['error']]);
    exit;
}
$uid = (string)$verify['uid'];

$lookupUrl = 'https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=' . rawurlencode($webKey);
$ch = curl_init($lookupUrl);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode(['idToken' => $idToken]),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 20,
]);
$lookupRes = curl_exec($ch);
curl_close($ch);
$lookupData = json_decode((string)$lookupRes, true);
$email = '';
if (!empty($lookupData['users'][0]['email'])) {
    $email = strtolower(trim((string)$lookupData['users'][0]['email']));
}

$allowed = in_array($uid, $allowedUids, true) || ($email !== '' && in_array($email, $allowedEmails, true));
echo json_encode([
    'status' => 'success',
    'allowed' => $allowed,
    'uid' => $uid,
    'email' => $email
], JSON_UNESCAPED_UNICODE);
