<?php
/**
 * PHP Kuriyar API: Steadfast create_order + Firebase PATCH (REST ?auth=idToken).
 * No service account / bootstrap.local.php required.
 */
header('Content-Type: application/json; charset=UTF-8');

require_once __DIR__ . '/api/kuriyar-firebase-client.php';
require_once __DIR__ . '/api/steadfast-keys-resolve.php';
require_once __DIR__ . '/api/steadfast-create-order-lib.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, '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(['success' => false, 'message' => 'Invalid JSON'], JSON_UNESCAPED_UNICODE);
    exit;
}

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

if ($clientId === '' || $idToken === '' || $firebaseOrderKey === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'clientId, idToken, and firebase_order_key are required.'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!preg_match('/^[-a-zA-Z0-9_]{1,128}$/', $firebaseOrderKey)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid firebase_order_key.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$chk = kuriyar_verify_store_admin($clientId, $idToken);
if (isset($chk['error'])) {
    $code = isset($chk['http']) ? (int) $chk['http'] : 403;
    if ($code < 400 || $code > 599) {
        $code = 403;
    }
    http_response_code($code);
    echo json_encode(['success' => false, 'message' => $chk['error']], JSON_UNESCAPED_UNICODE);
    exit;
}

$creds = steadfast_load_local_config();
if ($creds === null) {
    $cfgSnap = kuriyar_rtdb_get('clients/' . $clientId . '/siteSettings/steadfastConfig', $idToken);
    if (isset($cfgSnap['error'])) {
        http_response_code(503);
        echo json_encode(['success' => false, 'message' => 'Could not read Steadfast settings: ' . $cfgSnap['error']], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $cfg = $cfgSnap['data'] ?? null;
    if (!is_array($cfg)) {
        http_response_code(503);
        echo json_encode(['success' => false, 'message' => 'Save Steadfast API Key and Secret in Dashboard → Settings, or add api/steadfast-config.local.php on the server.'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $apiKey = isset($cfg['apiKey']) ? trim((string) $cfg['apiKey']) : '';
    $secretKey = isset($cfg['secretKey']) ? trim((string) $cfg['secretKey']) : '';
    if ($apiKey === '' || $secretKey === '') {
        http_response_code(503);
        echo json_encode(['success' => false, 'message' => 'Steadfast apiKey/secretKey missing in siteSettings/steadfastConfig.'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $baseUrl = 'https://portal.packzy.com/api/v1';
    if (!empty($cfg['baseUrl']) && is_string($cfg['baseUrl'])) {
        $t = rtrim(trim((string) $cfg['baseUrl']), '/');
        if ($t !== '') {
            $baseUrl = $t;
        }
    }
    $creds = ['api_key' => $apiKey, 'secret_key' => $secretKey, 'base_url' => $baseUrl];
}

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

$res = steadfast_create_order_http_post($creds['api_key'], $creds['secret_key'], $creds['base_url'], $parsed['forward']);

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

$data = $res['data'];

if (steadfast_packzy_create_succeeded($data)) {
    $consignment = $data['consignment'];
    $consignmentId = (string) ($consignment['consignment_id'] ?? '');
    $trackingCode = (string) ($consignment['tracking_code'] ?? '');
    $statusText = (string) ($consignment['status'] ?? 'Created');

    $patch = [
        'status' => 'Shipped',
        'courierInfo' => [
            'provider' => 'steadfast',
            'consignmentId' => $consignmentId,
            'trackingCode' => $trackingCode,
            'status' => $statusText !== '' ? $statusText : 'Created',
            'rawRef' => $consignmentId,
            'createdAt' => (int) round(microtime(true) * 1000),
        ],
    ];

    $orderPath = 'clients/' . $clientId . '/orders/' . $firebaseOrderKey;
    $patchRes = kuriyar_rtdb_patch($orderPath, $idToken, $patch);
    if (isset($patchRes['error'])) {
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'message' => 'Courier booked but Firebase update failed: ' . $patchRes['error'],
            'tracking_code' => $trackingCode,
            'consignment_id' => $consignmentId,
            'firebase_patch_error' => $patchRes['error'],
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    echo json_encode([
        'success' => true,
        'message' => 'Order sent to Steadfast and Firebase updated.',
        'tracking_code' => $trackingCode,
        'consignment_id' => $consignmentId,
        'status_text' => $statusText,
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$msg = 'Courier API did not return a valid consignment.';
if (is_array($data)) {
    if (!empty($data['message'])) {
        $msg = (string) $data['message'];
    } elseif (!empty($data['error'])) {
        $msg = is_string($data['error']) ? $data['error'] : json_encode($data['error'], JSON_UNESCAPED_UNICODE);
    }
}

http_response_code($res['http'] >= 400 ? $res['http'] : 400);
echo json_encode([
    'success' => false,
    'message' => $msg,
    'http_code' => $res['http'],
    'raw' => $res['raw'],
], JSON_UNESCAPED_UNICODE);
