<?php
function require_admin_auth(array $cfg): void {
  if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
  }
  // ✅ accept id=0
  if (!empty($_SESSION['user']) && isset($_SESSION['user']['id'])) {
    return;
}
  // Back-compat: accept HTTP Basic if provided and matches config; mint a session
  if (!empty($cfg['admin_auth'])) {
    $u = $_SERVER['PHP_AUTH_USER'] ?? null;
    $p = $_SERVER['PHP_AUTH_PW'] ?? null;
    if ($u === ($cfg['admin_auth']['user'] ?? null) && $p === ($cfg['admin_auth']['pass'] ?? null)) {
      $_SESSION['user'] = [
        'id'       => 0,
        'email'    => $u . '@local',
        'name'     => 'Admin',
        'role'     => 'admin',
        'provider' => 'local',
      ];
      return;
    }
  }

  // Not signed in -> send to login page (supports SSO), preserve return-to
  $base   = rtrim($cfg['base_url'] ?? '', '/');
  $login  = $base . '/admin/login.php';
  $return = current_url();
  header('Location: ' . $login . '?r=' . urlencode($return));
  exit;
}

function current_url(): string {
  $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
           || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
  $scheme = $https ? 'https' : 'http';
  $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
  $uri    = $_SERVER['REQUEST_URI'] ?? '/';
  return $scheme . '://' . $host . $uri;
}

function uuidv4(): string {
  $data = random_bytes(16);
  $data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
  $data[8] = chr((ord($data[8]) & 0x3f) | 0x80);
  return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

function esc($v): string {
  return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function sanitize_filename(string $name): string {
  $name = preg_replace('/[^\w.\-]/', '_', $name);
  return trim($name, '._');
}

function is_request_expired(?string $expires_at): bool {
  if (!$expires_at) return false;
  return (new DateTime($expires_at)) < new DateTime('now');
}

function ensure_dir(string $dir): void {
  if (!is_dir($dir)) {
    if (!mkdir($dir, 0775, true) && !is_dir($dir)) {
      throw new RuntimeException("Failed to create directory: $dir");
    }
  }
}
