<?php
// pages/feature_toggles.php — ON/OFF features (permissions) by role in a matrix
require_once __DIR__ . '/../includes/auth.php';
ec_require_min_role('super_admin'); // Only Super Admin can change toggles

$db = ec_db(); if (!$db) die('DB error');
$db->set_charset('utf8mb4');

function db_has(mysqli $db, string $tbl): bool {
  $tbl = $db->real_escape_string($tbl);
  $res = $db->query("SHOW TABLES LIKE '{$tbl}'");
  return $res && $res->num_rows > 0;
}
if (!db_has($db,'roles') || !db_has($db,'permissions') || !db_has($db,'role_permissions')) {
  die('Missing tables: roles / permissions / role_permissions');
}

/* Canonical features = permissions */
$CANON = [
  'batches.view'     => 'Batches — View',
  'batches.manage'   => 'Batches — Manage',
  'students.manage'  => 'Students — Manage',
  'courses.manage'   => 'Courses — Manage',
  'payments.manage'  => 'Payments — Manage',
  'reports.view'     => 'Reports — View',
  'users.manage'     => 'Users — Manage',
  'roles.manage'     => 'Roles — Manage',
  'settings.manage'  => 'Settings — Manage',
  'marks.add'        => 'Marks — Add',
  'marks.verify'     => 'Marks — Verify',
];

/* Ensure permissions table contains all canonical features */
$have = [];
$r = $db->query("SELECT slug FROM permissions");
while ($row = $r->fetch_assoc()) $have[$row['slug']] = true;
$ins = [];
foreach ($CANON as $slug=>$name) {
  if (!isset($have[$slug])) $ins[] = "('".$db->real_escape_string($name)."','".$db->real_escape_string($slug)."')";
}
if ($ins) $db->query("INSERT INTO permissions (name,slug) VALUES ".implode(',',$ins));

/* Load all roles & perms */
$roles = [];
$qr = $db->query("SELECT id,name,slug FROM roles ORDER BY FIELD(slug,'super_admin','admin','manager','staff'), name");
while ($row=$qr->fetch_assoc()) $roles[] = $row;

$perms = [];
$qp = $db->query("SELECT id,name,slug FROM permissions ORDER BY name");
while ($row=$qp->fetch_assoc()) $perms[] = $row;

/* Current mappings */
$map = []; // [perm_slug][role_id] = 1
$qq = $db->query("SELECT rp.role_id, p.slug FROM role_permissions rp JOIN permissions p ON p.id=rp.perm_id");
while ($row=$qq->fetch_assoc()) $map[$row['slug']][(int)$row['role_id']] = 1;

/* Save all toggles */
$msg = '';
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && isset($_POST['m'])) {
  $m = $_POST['m']; // m[perm_slug][role_id] = 'on'
  $db->begin_transaction();
  try {
    $db->query("DELETE rp FROM role_permissions rp JOIN permissions p ON p.id=rp.perm_id WHERE 1"); // clear all

    // prepare insert
    $ins = $db->prepare("INSERT INTO role_permissions (role_id, perm_id) SELECT ?, p.id FROM permissions p WHERE p.slug=?");
    foreach ($m as $slug => $rolesChecked) {
      foreach ($rolesChecked as $rid => $on) {
        $rid = (int)$rid;
        if ($rid <= 0) continue;
        $slug = (string)$slug;
        $ins->bind_param('is', $rid, $slug);
        $ins->execute();
      }
    }
    $ins->close();

    $db->commit();
    $msg = 'Saved feature toggles.';
    // reload map
    $map = [];
    $qq = $db->query("SELECT rp.role_id, p.slug FROM role_permissions rp JOIN permissions p ON p.id=rp.perm_id");
    while ($row=$qq->fetch_assoc()) $map[$row['slug']][(int)$row['role_id']] = 1;
  } catch (Throwable $e) {
    $db->rollback();
    $msg = 'Save failed: '.$e->getMessage();
  }
}

?>
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Feature Toggles — Eden RMS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
  body { background:#f5f7fb; }
  table.sticky thead th { position: sticky; top: 0; background: #fff; z-index: 5; }
  .perm-name { white-space: nowrap; }
</style>
</head>
<body>
    <?php
require_once __DIR__ . '/../includes/auth.php';
ec_require_login();
$ACTIVE = 'course'; // <-- set this to highlight the current menu item
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="container py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">Feature Toggles (by Role)</h4>
    <span class="text-muted small">Only Super Admin can edit</span>
  </div>

  <?php if ($msg): ?><div class="alert alert-info py-2"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

  <form method="post" class="card shadow-sm">
    <div class="table-responsive">
      <table class="table table-sm align-middle mb-0 sticky">
        <thead>
          <tr>
            <th style="min-width:260px">Feature</th>
            <?php foreach ($roles as $r): ?>
              <th class="text-center"><?= htmlspecialchars($r['name']) ?><div class="small text-muted"><?= htmlspecialchars($r['slug']) ?></div></th>
            <?php endforeach; ?>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($perms as $p): ?>
            <tr>
              <td class="perm-name"><?= htmlspecialchars($p['name']) ?><div class="small text-muted"><?= htmlspecialchars($p['slug']) ?></div></td>
              <?php foreach ($roles as $r): ?>
                <td class="text-center">
                  <input type="checkbox"
                         name="m[<?= htmlspecialchars($p['slug']) ?>][<?= (int)$r['id'] ?>]"
                         <?= isset($map[$p['slug']][(int)$r['id']]) ? 'checked' : '' ?>>
                </td>
              <?php endforeach; ?>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <div class="card-body text-end">
      <button class="btn btn-primary">Save</button>
    </div>
  </form>

  <div class="mt-3 small text-muted">
    Tip: the sidebar and pages already use <code>ec_can('...')</code>. Toggling here instantly hides/shows features by role.
  </div>
</div>
</body></html>
<?php include __DIR__ . '/../includes/footer.php'; ?>