<?php
// /lib/tenant.php
function current_host(): string {
  return $_SERVER['HTTP_HOST'] ?? '';
}

/**
 * Resolve org by subdomain or ?org=slug, or fallback to a configured default.
 * Returns assoc ['id'=>int,'name'=>string,'slug'=>string] or exits 404.
 */
function resolve_org(PDO $pdo, array $config): array {
  $host = current_host();
  $slug = null;

  // 1) Allow explicit ?org=... (useful on dev or single-domain setups)
  if (!empty($_GET['org'])) {
    $slug = preg_replace('~[^a-z0-9-]~i', '', $_GET['org']);
  }

  // 2) If not provided, derive from subdomain: <slug>.client.towlens.net
  if ($slug === null && strpos($host, '.') !== false) {
    // grab the left-most label
    $parts = explode('.', $host);
    $candidate = strtolower($parts[0]);
    // ignore generic prefixes like "www"
    if ($candidate !== 'www') $slug = preg_replace('~[^a-z0-9-]~', '', $candidate);
  }

  // 3) Optional default (for legacy routes)
  if ($slug === null) {
    $slug = $config['default_org_slug'] ?? null;
  }

  if (!$slug) {
    http_response_code(404); echo "Organisation not found (no slug)."; exit;
  }

  $stmt = $pdo->prepare("SELECT id, name, slug FROM organisations WHERE slug=? AND status='active' LIMIT 1");
  $stmt->execute([$slug]);
  $org = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$org) {
    http_response_code(404); echo "Organisation not found: " . htmlspecialchars($slug); exit;
  }
  return $org;
}
