Create rewrite rule for subpage

I do something similar. I have a page (country_tc) that uses a custom page template that either dynamically generates info for requested country, or a series of sub-pages for the country e.g.

/country/Egypt (index.php?pagename=country&countrytc=egypt)

/country/egypt/safety (index.php?pagename=country&countrytc=egypt/safety)

I use page_rewrite_rules for the re-write. I’ve not had time to vet your code, so this is how I’d do it:

In a site functions plugin:

//  allow WP to store querystring attribs for use in our pages
function tc_query_vars_filter($vars) {
  $vars[] = 'department-team';
  $vars[] .= 'another-var';
  return $vars;
}
add_filter( 'query_vars', 'tc_query_vars_filter' );

function tc_rewrite_rules($rules) {
   global $wp_rewrite;
   $tc_rule = array(
     // working example from my site
     'country/(.+)/?' => 'index.php?pagename=" . "country' . '&countrytc=$matches[1]',
     // YOUR rule (not tested)
     '/([^/]*)/team', 'index.php?pagename=YOURPAGENAME&department-team=$matches[1]'
   );
   return array_merge($tc_rule, $rules);
}
add_filter('page_rewrite_rules', 'tc_rewrite_rules');

AFTER ACTIVATING PLUGIN YOU NEED TO RE-SAVE PERMALINKS ON DASHBOARD – THIS WILL FLUSH/UPDATE YOUR REWRITE RULES

Do the rest of your code in your custom page using:

get_query_var('department-team') – sanitize, validate do your includes as required.