<?php
// /elms/admin/dashboard_manager.php
if (session_status() === PHP_SESSION_NONE) session_start();
define('APP_ROOT', dirname(__DIR__));

require_once APP_ROOT . '/includes/auth.php';
require_role(['super_admin','admin']); // who may configure

require_once APP_ROOT . '/includes/db.php';

/* --- DB bootstrap: normalize handle to $mysqli and expose globally --- */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = $conn ?? ($mysqli ?? null);
if (!$mysqli instanceof mysqli) { http_response_code(500); exit('DB not connected'); }
$mysqli->set_charset('utf8mb4');
$GLOBALS['mysqli'] = $mysqli;

require_once APP_ROOT . '/includes/capabilities.php'; // provides require_cap, can, etc.
require_cap('manage_dashboard'); // only roles with this cap can use this page

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }

// load roles from your users table (exclude 'student')
$roles = [];
$res = $mysqli->query("SELECT DISTINCT role_slug FROM elms_users WHERE role_slug IS NOT NULL AND role_slug<>'student' ORDER BY role_slug");
while ($r = $res->fetch_row()) $roles[] = $r[0];

// load capability catalog
$capRows = [];
$res = $mysqli->query("SELECT code,label,kind FROM elms_capabilities ORDER BY FIELD(kind,'menu','widget','action'), code");
while ($r = $res->fetch_assoc()) $capRows[] = $r;

// handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save']) && hash_equals($_POST['csrf'] ?? '', $_SESSION['csrf'] ?? '')) {
    $mysqli->begin_transaction();
    try {
        $del = $mysqli->prepare("DELETE FROM elms_role_caps WHERE role_slug=?");
        $ins = $mysqli->prepare("INSERT IGNORE INTO elms_role_caps (role_slug,cap_code) VALUES (?,?)");
        foreach ($roles as $role) {
            $del->bind_param('s', $role);
            $del->execute();
            $vals = $_POST['cap'][$role] ?? [];
            foreach ($vals as $capCode => $on) {
                $capCode = (string)$capCode;
                $ins->bind_param('ss', $role, $capCode);
                $ins->execute();
            }
        }
        $mysqli->commit();
        $msg = 'Saved.';
    } catch (Throwable $e) {
        $mysqli->rollback();
        $msg = 'Error saving: '.$e->getMessage();
    }
}

// load current selections
$matrix = [];
$sel = $mysqli->query("SELECT role_slug, cap_code FROM elms_role_caps");
while ($r = $sel->fetch_assoc()) $matrix[$r['role_slug']][$r['cap_code']] = true;

// csrf
$_SESSION['csrf'] = bin2hex(random_bytes(16));

$PAGE_TITLE='Dashboard Manager';
$ACTIVE_MENU='dashboard_manager';
require APP_ROOT . '/includes/admin_layout_top.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h5 m-0">Dashboard Manager</h1>
  <?php if(!empty($msg)): ?><span class="text-muted"><?= esc($msg) ?></span><?php endif; ?>
</div>

<form method="post" class="card">
  <input type="hidden" name="csrf" value="<?= esc($_SESSION['csrf']) ?>">
  <div class="card-body">
    <p class="text-muted mb-3">Tick capabilities per role. This controls which <em>menus</em>, <em>widgets/tiles</em>, and <em>actions</em> are visible on the shared admin dashboard.</p>

    <?php
      $groups = [
        'menu'   => 'Menus',
        'widget' => 'Dashboard Widgets / Panels',
        'action' => 'Actions'
      ];
      foreach ($groups as $kind => $title):
        $items = array_values(array_filter($capRows, fn($c)=>$c['kind']===$kind));
        if (!$items) continue;
    ?>
      <div class="mb-4">
        <h2 class="h6 mb-2"><?= esc($title) ?></h2>
        <div class="table-responsive">
          <table class="table table-sm align-middle">
            <thead class="table-light">
              <tr>
                <th style="min-width:240px">Capability</th>
                <?php foreach ($roles as $role): ?>
                  <th class="text-center"><?= esc($role) ?></th>
                <?php endforeach; ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($items as $cap): ?>
                <tr>
                  <td><strong><?= esc($cap['label']) ?></strong><div class="small text-muted"><?= esc($cap['code']) ?></div></td>
                  <?php foreach ($roles as $role): $checked = !empty($matrix[$role][$cap['code']]); ?>
                    <td class="text-center">
                      <input type="checkbox" class="form-check-input" name="cap[<?= esc($role) ?>][<?= esc($cap['code']) ?>]" <?= $checked?'checked':'' ?>>
                    </td>
                  <?php endforeach; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
  <div class="card-footer d-flex justify-content-end">
    <button class="btn btn-primary" name="save" value="1">Save</button>
  </div>
</form>

<?php require APP_ROOT . '/includes/admin_layout_bottom.php';
