<?php
/**
 * PHP Kuriyar: Firebase RTDB via REST with user idToken (?auth=) — no service account file.
 * Public values must match storefront Firebase config (e.g. shop-core.js).
 */
require_once __DIR__ . '/firebase-rtdb-admin.php';

/**
 * @return array{database_url: string, web_api_key: string}
 */
function kuriyar_firebase_config() {
    $local = __DIR__ . '/kuriyar-firebase-config.local.php';
    if (is_readable($local)) {
        $c = include $local;
        if (is_array($c) && !empty($c['database_url']) && !empty($c['web_api_key'])) {
            return [
                'database_url' => rtrim((string) $c['database_url'], '/'),
                'web_api_key' => trim((string) $c['web_api_key']),
            ];
        }
    }
    return [
        'database_url' => 'https://arafstore-14938-default-rtdb.firebaseio.com',
        'web_api_key' => 'AIzaSyCqfdaLceRPWxi7PQ6QJyrqbSLudoMUywI',
    ];
}

function kuriyar_rtdb_build_url($path, $idToken) {
    $cfg = kuriyar_firebase_config();
    $databaseUrl = $cfg['database_url'];
    $segs = explode('/', trim((string) $path, '/'));
    $enc = array_map('rawurlencode', $segs);
    return $databaseUrl . '/' . implode('/', $enc) . '.json?auth=' . rawurlencode($idToken);
}

/**
 * @return array{data?: mixed, error?: string, http?: int}
 */
function kuriyar_rtdb_get($path, $idToken) {
    if (!function_exists('curl_init')) {
        return ['error' => 'PHP curl extension required for Firebase REST.', 'http' => 500];
    }
    $url = kuriyar_rtdb_build_url($path, $idToken);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 45,
    ]);
    $res = curl_exec($ch);
    $http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($res === false) {
        return ['error' => 'RTDB GET request failed.', 'http' => $http];
    }
    if ($http === 401 || $http === 403) {
        return ['error' => 'Permission denied. Re-open PHP Kuriyar from the dashboard (fresh token) or check Realtime Database rules for admins.', 'http' => $http];
    }
    if ($http >= 400) {
        return ['error' => 'RTDB HTTP ' . $http, 'http' => $http];
    }
    if ($res === 'null' || trim((string) $res) === '') {
        return ['data' => null, 'http' => $http];
    }
    $decoded = json_decode((string) $res, true);
    return ['data' => $decoded, 'http' => $http];
}

/**
 * @param array<string,mixed> $payload
 * @return array{data?: mixed, error?: string, http?: int}
 */
function kuriyar_rtdb_patch($path, $idToken, array $payload) {
    if (!function_exists('curl_init')) {
        return ['error' => 'PHP curl extension required for Firebase REST.', 'http' => 500];
    }
    $url = kuriyar_rtdb_build_url($path, $idToken);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => 'PATCH',
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 45,
    ]);
    $res = curl_exec($ch);
    $http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($res === false) {
        return ['error' => 'RTDB PATCH request failed.', 'http' => $http];
    }
    if ($http === 401 || $http === 403) {
        return ['error' => 'Permission denied on PATCH. Check Firebase rules.', 'http' => $http];
    }
    if ($http >= 400) {
        return ['error' => 'RTDB PATCH HTTP ' . $http . ($res !== '' ? (': ' . substr((string) $res, 0, 200)) : ''), 'http' => $http];
    }
    return ['data' => json_decode((string) $res, true), 'http' => $http];
}

/**
 * Verify idToken and that user is admin for clients/{clientId}.
 *
 * @return array{uid: string}|array{error: string, http?: int}
 */
function kuriyar_verify_store_admin($clientId, $idToken) {
    if ($clientId === '' || !preg_match('/^[-A-Za-z0-9_]{1,128}$/', $clientId)) {
        return ['error' => 'Valid clientId is required.', 'http' => 400];
    }
    if ($idToken === '') {
        return ['error' => 'Firebase idToken is required.', 'http' => 401];
    }
    $cfg = kuriyar_firebase_config();
    $verify = firebase_verify_id_token($idToken, $cfg['web_api_key']);
    if (isset($verify['error'])) {
        return ['error' => $verify['error'], 'http' => 401];
    }
    $uid = $verify['uid'];

    $snap = kuriyar_rtdb_get('clients/' . $clientId . '/admins/' . $uid, $idToken);
    if (isset($snap['error'])) {
        return ['error' => $snap['error'], 'http' => $snap['http'] ?? 403];
    }
    if (!firebase_rtdb_is_truthy_admin($snap['data'] ?? null)) {
        return ['error' => 'Forbidden: this account is not an admin for this store.', 'http' => 403];
    }
    return ['uid' => $uid];
}
