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

try {
    if (session_status() === PHP_SESSION_NONE) session_start();
    require_once __DIR__ . '/../../includes/auth.php';
    require_once __DIR__ . '/../../classes/Database.php';
    require_once __DIR__ . '/../../classes/Inventory.php';
    $database = new Database();
    $conn = $database->getConnection();
    if (!$conn instanceof PDO) {
        throw new RuntimeException('Database connection is unavailable.');
    }

    $auth = new Auth($conn);
    if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'] ?? '', ['admin', 'warehouse'], true)) {
        if (ob_get_level() > 0) ob_clean();
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Unauthorized.']);
        exit;
    }

    $branchRaw = filter_input(INPUT_GET, 'branch_id', FILTER_VALIDATE_INT);
    $branchId = (!$branchRaw || $branchRaw === 0) ? null : (int)$branchRaw;
    $groupKey = trim((string)($_GET['group_key'] ?? ''));
    if ($groupKey === '' || strlen($groupKey) > 500) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid inventory group.']);
        exit;
    }

    $rows = (new Inventory($conn))->getDetailedItemGroupCodes($branchId, $groupKey);
    $items = array_map(static function (array $row): array {
        return [
            'item_id' => (int)$row['item_id'],
            'unique_code' => (string)($row['unique_code'] ?? ''),
            'item_details' => (string)($row['item_details'] ?? ''),
            'serial_number' => (string)($row['serial_number'] ?? ''),
            'branch_name' => (string)($row['branch_name'] ?? ''),
        ];
    }, $rows);

    if (ob_get_level() > 0) ob_clean();
    echo json_encode([
        'success' => true,
        'items' => $items,
        'can_delete' => ($_SESSION['role'] ?? '') === 'admin',
    ], JSON_INVALID_UTF8_SUBSTITUTE);
} catch (Throwable $e) {
    error_log('Unable to load grouped branch inventory codes: ' . $e->getMessage());
    if (ob_get_level() > 0) ob_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Unable to load unique codes.']);
}
