<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/MraEisOnboarding.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Login required.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    $auth = new Auth($conn);
    if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized.']);
        exit;
    }

    $stockId = (int)($_GET['stock_id'] ?? 0);
    if ($stockId <= 0) {
        echo json_encode(['success' => false, 'error' => 'Invalid stock id.']);
        exit;
    }
    $branchId = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;

    $eis = new MraEisOnboarding($conn);
    $items = $eis->linkedWarehouseItems($stockId, $branchId);

    echo json_encode(['success' => true, 'items' => $items]);
} catch (Throwable $e) {
    error_log('MRA EIS linked items lookup failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Unable to load linked items.']);
}
