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

try {
    if (session_status() === PHP_SESSION_NONE) session_start();
    require_once __DIR__ . '/../../classes/Database.php';
    require_once __DIR__ . '/../../includes/auth.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'])) {
        if (ob_get_level() > 0) ob_clean();
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Your session has expired. Please sign in again.']);
        exit;
    }
    $branchId = (int)$auth->getUserBranch($_SESSION['user_id']);
    $groupKey = trim((string)($_GET['group_key'] ?? ''));
    if ($branchId <= 0 || $groupKey === '' || strlen($groupKey) > 500) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid stock group.']);
        exit;
    }

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

    if (ob_get_level() > 0) ob_clean();
    echo json_encode(['success' => true, 'codes' => $codes], JSON_INVALID_UTF8_SUBSTITUTE);
} catch (Throwable $e) {
    error_log('Unable to load branch stock group 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.']);
}
