<?php
include 'db.php';
include 'layout.php';
?>

<div class="page-wrapper">
  <div class="content container-fluid">

    <div class="page-header">
      <div class="row align-items-center">
        <div class="col">
          <h4 class="page-title">User Rights Management</h4>
        </div>
        <div class="col-auto float-end ms-auto">
          <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRightModal">
            <i class="fa fa-plus"></i> Add Right
          </button>
          <button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#assignRightsModal">
            <i class="fa fa-key"></i> Assign Rights
          </button>
        </div>
      </div>
    </div>

    <!-- Rights Table -->
    <div class="row">
      <div class="col-md-12">
        <div class="card card-table">
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-hover table-center mb-0 datatable">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Role</th>
                    <th>Assigned Rights</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $roles = $conn->query("SELECT * FROM roles");
                  $i = 1;
                  while ($role = $roles->fetch_assoc()):
                    $role_id = $role['id'];
                    $rights_q = $conn->query("
                      SELECT rights.name FROM role_rights
                      JOIN rights ON role_rights.right_id = rights.id
                      WHERE role_rights.role_id = $role_id
                    ");
                    $rights = [];
                    while ($r = $rights_q->fetch_assoc()) {
                      $rights[] = $r['name'];
                    }
                    $rights_list = $rights ? implode(', ', $rights) : 'No rights assigned';
                  ?>
                  <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlspecialchars($role['name']) ?></td>
                    <td><?= $rights_list ?></td>
                  </tr>
                  <?php endwhile; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>

  <!-- Include Modals -->
  <?php
    include 'modals/add_right_modal.php';
    include 'modals/assign_rights_modal.php';
  ?>
</div>
