<?php
// /elms/includes/capabilities.php — DB-backed role capabilities with safe fallbacks

if (!function_exists('ec_current_user')) {
  function ec_current_user() { return $_SESSION['user'] ?? null; }
}
if (!function_exists('ec_is_logged_in')) {
  function ec_is_logged_in() { return !empty($_SESSION['user']); }
}
if (!function_exists('ec_require_login')) {
  function ec_require_login() {
    if (!ec_is_logged_in()) { header('Location: /elms/login.php'); exit; }
  }
}

if (!function_exists('cap__db')) {
  function cap__db() {
    global $mysqli, $conn;
    $db = ($conn ?? null) instanceof mysqli ? $conn
        : (($mysqli ?? null) instanceof mysqli ? $mysqli : null);
    if ($db) { @$db->set_charset('utf8mb4'); }
    return $db;
  }
}

if (!function_exists('cap__role_slug')) {
  function cap__role_slug() {
    $u = ec_current_user();
    if (is_array($u) && !empty($u['role_slug'])) return (string)$u['role_slug'];
    if (!empty($_SESSION['role_slug'])) return (string)$_SESSION['role_slug'];
    return '';
  }
}
if (!function_exists('cap__is_super_admin')) {
  function cap__is_super_admin() { return cap__role_slug()==='super_admin'; }
}

$GLOBALS['__cap_cache'] = $GLOBALS['__cap_cache'] ?? [];

if (!function_exists('can')) {
  function can($cap_code) {
    if (cap__is_super_admin()) return true; // bypass all
    $cap_code = (string)$cap_code;
    $role = cap__role_slug();
    if ($role === '') return false;

    $key = $role.'|'.$cap_code;
    if (isset($GLOBALS['__cap_cache'][$key])) return $GLOBALS['__cap_cache'][$key];

    $db = cap__db(); if (!$db) return false;

    $caps = @$db->query("SHOW TABLES LIKE 'elms_capabilities'");
    $rc   = @$db->query("SHOW TABLES LIKE 'elms_role_caps'");
    if (!$caps || !$caps->num_rows || !$rc || !$rc->num_rows) return false;

    $role_es = $db->real_escape_string($role);
    $cap_es  = $db->real_escape_string($cap_code);
    $sql = "SELECT 1 FROM elms_role_caps WHERE role_slug='$role_es' AND cap_code='$cap_es' LIMIT 1";
    $res = @$db->query($sql);
    $ok = ($res && $res->num_rows>0);
    $GLOBALS['__cap_cache'][$key] = $ok;
    return $ok;
  }
}
if (!function_exists('can_any')) {
  function can_any($caps) { foreach ((array)$caps as $c) if (can($c)) return true; return false; }
}
if (!function_exists('require_cap')) {
  function require_cap($cap_code) { if (!can($cap_code)) { http_response_code(403); exit('Forbidden'); } }
}
