<?php
ob_start();
header('Content-Type: application/json; charset=utf-8');

// Verification may refresh an expired token and make multiple MRA requests.
@set_time_limit(190);

$responseSent = false;
function sendJsonResponse(array $payload, $status = 200) {
    global $responseSent;
    $responseSent = true;
    http_response_code((int)$status);
    if (ob_get_level() > 0) {
        ob_clean();
    }
    echo json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
}

register_shutdown_function(static function () {
    global $responseSent;
    if ($responseSent) {
        return;
    }
    $error = error_get_last();
    $fatalTypes = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
    if ($error && in_array($error['type'], $fatalTypes, true)) {
        error_log('MRA transfer receipt verification fatal error: ' . $error['message']);
        $message = stripos($error['message'], 'maximum execution time') !== false
            ? 'MRA verification timed out. Please check the MRA connection and retry.'
            : 'The server could not complete MRA verification. Check the server log for details.';
        sendJsonResponse(['success' => false, 'message' => $message], 500);
    }
});

try {
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/MraEisCompliance.php';

if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', ['admin', 'warehouse'], true)) {
    sendJsonResponse(['success' => false, 'message' => 'Unauthorized'], 403);
    exit;
}

$shipmentId = filter_input(INPUT_POST, 'shipment_id', FILTER_VALIDATE_INT);
if (!$shipmentId) {
    sendJsonResponse(['success' => false, 'message' => 'Invalid shipment ID.'], 422);
    exit;
}
$action = trim((string)($_POST['action'] ?? 'verify'));
if (!in_array($action, ['verify', 'calibrate'], true)) {
    sendJsonResponse(['success' => false, 'message' => 'Invalid verification action.'], 422);
    exit;
}

$database = new Database();
$conn = $database->getConnection();
if (!$conn instanceof PDO) {
    throw new RuntimeException('Database connection is unavailable. Please try again shortly.');
}

    $compliance = new MraEisCompliance($conn);
    $result = $action === 'calibrate'
        ? $compliance->calibrateTransferReceipt($shipmentId, $_SESSION['user_id'])
        : $compliance->confirmTransferReceipt($shipmentId, $_SESSION['user_id']);
    sendJsonResponse(['success' => true, 'action' => $action] + $result);
} catch (Throwable $e) {
    error_log('MRA transfer receipt verification failed: ' . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
