<?php
require_once __DIR__ . '/../helpers/functions.php';

/* ===============================
   CURRENT USER (CUSTOMER SAFE)
   - Supports BOTH old and new keys
================================ */
function current_user(): ?array {
  session_boot();

  // Priority: customer (new) → user (legacy)
  if (!empty($_SESSION['customer'])) {
    return $_SESSION['customer'];
  }

  return $_SESSION['user'] ?? null;
}

/* ===============================
   AUTH CHECK
================================ */
function is_logged_in(): bool {
  return (bool) current_user();
}

/* ===============================
   REQUIRE CUSTOMER LOGIN
================================ */
function require_login(): void {
  if (!is_logged_in()) {
    redirect('/customer/login.php');
  }
}

/* ===============================
   ROLE CHECK (ADMIN SAFE)
================================ */
function user_has_role(mysqli $conn, int $userId, array $roles): bool {
  if (!$roles) return false;

  $placeholders = implode(',', array_fill(0, count($roles), '?'));

  $sql = "
    SELECT COUNT(*) AS c
    FROM user_roles ur
    JOIN roles r ON r.id = ur.role_id
    WHERE ur.user_id = ?
      AND r.name IN ($placeholders)
  ";

  $stmt = $conn->prepare($sql);

  $types = 'i' . str_repeat('s', count($roles));
  $params = array_merge([$userId], $roles);

  $stmt->bind_param($types, ...$params);
  $stmt->execute();

  $res = $stmt->get_result()->fetch_assoc();
  return (int)($res['c'] ?? 0) > 0;
}

/* ===============================
   REQUIRE ADMIN (UNTOUCHED LOGIC)
================================ */
function require_admin(mysqli $conn): void {
  $u = current_user();
  if (!$u) redirect('/admin/login.php');

  if (!user_has_role(
        $conn,
        (int)$u['id'],
        ['super_admin','ops','compliance','support']
      )) {
    http_response_code(403);
    die('Forbidden');
  }
}
