<?php
/**
 * Same-origin proxy: forwards create_order to Steadfast (Packzy) API.
 * Keys from (1) api/steadfast-config.local.php if valid, else (2) RTDB clients/{clientId}/siteSettings/steadfastConfig
 * after verifying Firebase idToken + admin record (REST ?auth=idToken; see kuriyar-firebase-client.php).
 *
 * @see https://docs.google.com/document/d/e/2PACX-1vTi0sTyR353xu1AK0nR8E_WKe5onCkUXGEf8ch8uoJy9qxGfgGnboSIkNosjQ0OOdXkJhgGuAsWxnIh/pub
 */
header('Content-Type: application/json; charset=UTF-8');

require_once __DIR__ . '/steadfast-keys-resolve.php';
require_once __DIR__ . '/steadfast-create-order-lib.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed'], JSON_UNESCAPED_UNICODE);
    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'], JSON_UNESCAPED_UNICODE);
    exit;
}

$clientId = isset($body['clientId']) ? trim((string) $body['clientId']) : '';
$idToken = isset($body['idToken']) ? trim((string) $body['idToken']) : '';

$creds = steadfast_load_local_config();
if ($creds === null) {
    $fb = steadfast_resolve_keys_from_firebase($clientId, $idToken);
    if (isset($fb['error'])) {
        $code = isset($fb['http']) ? (int) $fb['http'] : 503;
        if ($code < 400 || $code > 599) {
            $code = 503;
        }
        http_response_code($code);
        echo json_encode(['status' => 'error', 'message' => $fb['error']], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $creds = $fb;
}

$apiKey = $creds['api_key'];
$secretKey = $creds['secret_key'];
$baseUrl = $creds['base_url'];

$parsed = steadfast_parse_create_order_body($body);
if (isset($parsed['error'])) {
    http_response_code($parsed['error']['http']);
    echo json_encode([
        'status' => 'error',
        'message' => $parsed['error']['message'],
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$res = steadfast_create_order_http_post($apiKey, $secretKey, $baseUrl, $parsed['forward']);

if ($res['http'] === 502 && $res['raw'] === '') {
    http_response_code(502);
    echo json_encode([
        'status' => 'error',
        'message' => 'Could not reach Steadfast API. Check server network or PHP curl.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($res['http'] >= 100) {
    http_response_code($res['http']);
}
echo $res['raw'];
