<?php
// Session and role handling helpers for RBE Utilities
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

require_once __DIR__ . '/db_connect.php';

function current_user_id(): ?int {
  return isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null;
}

function current_user_role(?PDO $conn = null): ?string {
  $uid = current_user_id();
  if (!$uid) return null;
  if (!$conn) {
    global $conn_rbe;
    $conn = $conn_rbe ?? null;
  }
  if (!$conn) return null;
  $stmt = $conn->prepare('SELECT role FROM rbe_roles WHERE user_id=? LIMIT 1');
  $stmt->execute([$uid]);
  $role = $stmt->fetchColumn();
  return $role ?: null;
}

function require_login(): void {
  if (!current_user_id()) {
    header('Location: /login.php');
    exit();
  }
}

function require_role($allowed): void {
  $allowed_list = is_array($allowed) ? $allowed : [$allowed];
  $role = current_user_role();
  if (!$role || !in_array($role, $allowed_list, true)) {
    http_response_code(403);
    exit('Access denied');
  }
}

function landlord_scope_id(): ?int {
  // Admin may pass landlord_id via query; others default to self
  $role = current_user_role();
  $uid = current_user_id();
  if (!$uid) return null;
  if ($role === 'admin' && isset($_GET['landlord_id']) && $_GET['landlord_id'] !== '') {
    return (int)$_GET['landlord_id'];
  }
  return $uid;
}

function is_admin(): bool { return current_user_role() === 'admin'; }
function is_landlord(): bool { return current_user_role() === 'landlord'; }
function is_tenant(): bool { return current_user_role() === 'tenant'; }

?>
