<?php
require_once __DIR__ . '/vendor/autoload.php';
$page_title = 'Management Menu';
require_once('includes/load.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_group'])) {
  $groupId = $_POST['user_group'];
  $menuItems = $_POST['menu_items'] ?? [];

  // Clear existing permissions for the group
  $db->query("DELETE FROM role_menu_permissions WHERE user_groups_id = $groupId");

  // Insert new permissions
  foreach ($menuItems as $menuItemId) {
    $db->query("INSERT INTO role_menu_permissions (user_groups_id, menu_item_id) VALUES ($groupId, $menuItemId)");
  }

  echo "<div class='alert alert-success'>Permissions updated successfully!</div>";
}

// Fetch user groups
$groupsResult = $db->query("SELECT * FROM user_groups");
$groups = [];
while ($row = $groupsResult->fetch_assoc()) {
  $groups[] = $row;
}

// Fetch menu items
$menuResult = $db->query("SELECT * FROM menu_items WHERE visible = 1");
$menuItems = [];
while ($row = $menuResult->fetch_assoc()) {
  $menuItems[] = $row;
}

// Fetch existing permissions for the first group (for example)
$selectedGroupId = $groups[0]['id'] ?? null;
$permissionsResult = $db->query("SELECT menu_item_id FROM role_menu_permissions WHERE user_groups_id = $selectedGroupId");
$existingPermissions = [];
while ($row = $permissionsResult->fetch_assoc()) {
  $existingPermissions[] = $row['menu_item_id'];
}

$permissionsResult = $db->query("
    SELECT ug.group_name, mi.name AS menu_item, 
           CASE WHEN rmp.user_groups_id IS NOT NULL THEN 'Yes' ELSE 'No' END AS has_permission
    FROM user_groups ug
    LEFT JOIN role_menu_permissions rmp ON ug.id = rmp.user_groups_id
    LEFT JOIN menu_items mi ON rmp.menu_item_id = mi.id
");
$permissions = [];
while ($row = $permissionsResult->fetch_assoc()) {
  $permissions[] = $row;
}

?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
  <div class="col-md-12">
    <?php echo display_msg($msg); ?>
  </div>
</div>
<div class="row">
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading clearfix">
        <strong>
          <span class="glyphicon glyphicon-th"></span>
          <span>Form Add / Edit</span>
        </strong>
      </div>
      <div class="panel-body">
        <form method="POST" action="">
          <div class="form-group">
            <label for="user_group">Select User Group:</label>
            <select name="user_group" id="user_group" class="form-control" onchange="this.form.submit()">
              <?php foreach ($groups as $group): ?>
                <option value="<?php echo $group['id']; ?>"
                  <?php echo ($group['id'] == $selectedGroupId) ? 'selected' : ''; ?>>
                  <?php echo $group['group_name']; ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>

          <h3>Menu Permissions</h3>
          <?php foreach ($menuItems as $item): ?>
            <div class="checkbox">
              <label>
                <input type="checkbox" name="menu_items[]" value="<?php echo $item['id']; ?>"
                  <?php echo in_array($item['id'], $existingPermissions) ? 'checked' : ''; ?>>
                <?php echo $item['name']; ?>
              </label>
            </div>
          <?php endforeach; ?>

          <button type="submit" class="btn btn-primary">Update Permissions</button>
        </form>
      </div>
    </div>
  </div>
  <div class="col-md-12">
    <div class="panel panel-default">
      <div class="panel-heading clearfix">
        <strong>
          <span class="glyphicon glyphicon-th"></span>
          <span>Data Role</span>
        </strong>
      </div>
      <div class="panel-body">
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>Role Name</th>
              <th>Menu Item</th>
              <th>Has Permission</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($permissions)): ?>
              <tr>
                <td colspan="3" class="text-center">No permissions found.</td>
              </tr>
            <?php else: ?>
              <?php foreach ($permissions as $permission): ?>
                <tr>
                  <td><?php echo $permission['group_name']; ?></td>
                  <td><?php echo $permission['menu_item']; ?></td>
                  <td><?php echo $permission['has_permission']; ?></td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include_once('layouts/footer.php'); ?>