<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/rbac.php";
require_once "../includes/lang.php";
require_once "../includes/csrf.php";

requirePageAuth();
if (!hasPermission("manage_users") && (int)($_SESSION["user"]["role_id"] ?? 0) !== 5) {
    http_response_code(403);
    exit("Forbidden");
}

$user = getAuthUser();
$csrf = csrfToken();
?>
<!DOCTYPE HTML>
<html lang="<?= htmlspecialchars(currentLang()) ?>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars(t("manage_permissions")) ?> - Konzona Hub</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="assets/css/style.css" type="text/css">
<link rel="stylesheet" href="assets/css/dashboard.css" type="text/css">
<link href="assets/css/font-awesome.min.css" rel="stylesheet">
<style>
.permissions-card { border-radius: 14px; box-shadow: 0 8px 24px rgba(0,0,0,.08); }
.permissions-table th, .permissions-table td { vertical-align: top; }
.perm-pill { display:inline-flex; align-items:center; gap:6px; margin:4px 10px 4px 0; padding:4px 8px; border:1px solid #e5e5e5; border-radius:999px; background:#fff; }
.perm-pill input { margin:0; }
@media (max-width: 991px){
  .dashboard_container .navbar-header { position: relative; z-index: 30; }
  #dashboard-nav { z-index: 20; }
  .dashboard-nav-active #dashboard-nav { margin-top: 10px; }
}
</style>
</head>
<body>
<div class="dashboard_container">
<header id="header">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<div class="logo"><a href="admin.php"><img src="assets/images/logo.png" alt="logo"/></a></div>
<div id="dashboard-responsive-nav-trigger"><i class="fa fa-reorder"></i></div>
</div>
</div>
</nav>
</header>

<div id="dashboard">
<div id="dashboard-nav" class="dashboard-nav">
<ul>
<li><a href="admin.php"><i class="fa fa-cogs"></i> <?= htmlspecialchars(t("dashboard")) ?></a></li>
<li><a href="dashboard.php"><i class="fa fa-th-list"></i> <?= htmlspecialchars(t("requests")) ?></a></li>
<li><a href="match_history.php"><i class="fa fa-link"></i> Matched Workers</a></li>
<li><a href="agency_documents.php"><i class="fa fa-file-text-o"></i> Worker Documentation</a></li>
<li><a href="worker_documents_review.php"><i class="fa fa-folder-open-o"></i> Documentation Review</a></li>
<li>
  <a href="#adminActionsMenu" data-toggle="collapse" aria-expanded="true">
    <i class="fa fa-plus-circle"></i> Admin Actions <span class="caret"></span>
  </a>
  <ul id="adminActionsMenu" class="collapse in list-unstyled" style="padding-left:15px;">
    <li><a href="nalog.php"><i class="fa fa-user-plus"></i> <?= htmlspecialchars(t("add_user")) ?></a></li>
    <li><a href="add_skills.php"><i class="fa fa-tags"></i> <?= htmlspecialchars(t("add_skill")) ?></a></li>
    <li><a href="add_positions.php"><i class="fa fa-briefcase"></i> Positions</a></li>
    <li class="active"><a href="manage_permissions.php"><i class="fa fa-lock"></i> <?= htmlspecialchars(t("manage_permissions")) ?></a></li>
    <li><a href="admin_profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("admin_profile")) ?></a></li>
  </ul>
</li>
<li><a href="chat.php"><i class="fa fa-comments"></i> <?= htmlspecialchars(t("support")) ?></a></li>
<li><a href="profile.php"><i class="fa fa-user-o"></i> <?= htmlspecialchars(t("my_profile")) ?></a></li>
<li><a href="terms.php"><i class="fa fa-file-text-o"></i> <?= htmlspecialchars(t("terms_of_use")) ?></a></li>
<li><a href="logout.php"><i class="fa fa-power-off"></i> <?= htmlspecialchars(t("logout")) ?></a></li>
</ul>
</div>

<div class="dashboard-content">
<div id="titlebar"><div class="row"><div class="col-md-12"><h2><?= htmlspecialchars(t("manage_permissions")) ?></h2></div></div></div>

<div class="dashboard-list-box permissions-card">
<h4><?= htmlspecialchars(t("manage_permissions")) ?></h4>
<div class="padding-20">
<div class="table-responsive">
<table class="table table-striped permissions-table">
<thead>
<tr>
<th>User</th>
<th>Role</th>
<th>Permissions</th>
</tr>
</thead>
<tbody id="permissionsTableBody"></tbody>
</table>
</div>
</div>
</div>

</div>
</div>
</div>

<script>
window.APP = { csrf: "<?= htmlspecialchars($csrf) ?>" };

function createPermCheckbox(user, perm, checked, disabled) {
  const roleId = parseInt(user.role_id, 10);
  const permId = parseInt(perm.id, 10);
  return '<label class="perm-pill">' +
    '<input type="checkbox" ' + (checked ? 'checked ' : '') + (disabled ? 'disabled ' : '') +
    'onchange="updateRolePermission(' + roleId + ',' + permId + ', this.checked)">' +
    '<span>' + String(perm.name || '') + '</span>' +
    '</label>';
}

async function safeJson(res) {
  const text = await res.text();
  try { return JSON.parse(text); } catch (e) {
    return { success: false, error: "invalid_json", raw: text };
  }
}

async function loadPermissionsPage() {
  const [usersRes, permsRes, rolePermRes] = await Promise.all([
    fetch("../api/users.php", { credentials: "same-origin" }),
    fetch("../api/permissions.php", { credentials: "same-origin" }),
    fetch("../api/permissions_matrix.php", { credentials: "same-origin" })
  ]);

  const usersJ = await safeJson(usersRes);
  const permsJ = await safeJson(permsRes);
  const rolePermJ = await safeJson(rolePermRes);

  const tbody = document.getElementById("permissionsTableBody");
  tbody.innerHTML = "";

  if (!usersJ.success || !permsJ.success || !rolePermJ.success) {
    console.error("permissions load error", { usersJ, permsJ, rolePermJ });
    tbody.innerHTML = '<tr><td colspan="3">Failed to load permissions data.</td></tr>';
    return;
  }

  usersJ.data.forEach(u => {
    const tr = document.createElement("tr");
    const roleId = parseInt(u.role_id, 10);
    const isModerator = roleId === 5;

    let permsHtml = "";
    permsJ.data.forEach(p => {
      const checked = !!(rolePermJ.data[String(roleId)] || []).includes(parseInt(p.id, 10));
      const disabled = isModerator && p.name === "manage_users";
      permsHtml += createPermCheckbox(u, p, checked, disabled);
    });

    tr.innerHTML = `
      <td>${u.email || ("User #" + u.id)}</td>
      <td>${u.role_name || ("Role " + roleId)}</td>
      <td>${permsHtml}</td>
    `;
    tbody.appendChild(tr);
  });
}

async function updateRolePermission(roleId, permissionId, grant) {
  const r = await fetch("../api/permissions_matrix.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "same-origin",
    body: JSON.stringify({
      csrf: window.APP.csrf,
      role_id: roleId,
      permission_id: permissionId,
      grant: !!grant
    })
  });

  const j = await r.json().catch(() => ({ success: false, error: "invalid_response" }));
  if (!j.success) {
    alert(j.error || "update_failed");
    await loadPermissionsPage();
  }
}

loadPermissionsPage();
</script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
</body>
</html>
