<?php
require_once __DIR__ . '/../config/database.php';
requireLogin();
requireAnyRole(['admin','super_admin']);
$db = Database::getInstance();

$id = (int)($_GET['id'] ?? 0);
$role = null;
$availablePermissions = ['can_create_courses','can_create_assessments','can_view_reports','can_view_analytics','can_manage_users','manage_region','can_manage_roles','can_create_certificates'];

if ($id) {
    $role = $db->get('SELECT * FROM roles WHERE id = ?', [$id]);
    if (!$role) redirect('roles.php');
}

$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rname = trim($_POST['role'] ?? '');
    if ($rname === '') $errors[] = 'Role name is required.';

    $permArray = [];
    if (!empty($_POST['permissions']) && is_array($_POST['permissions'])) {
        foreach ($_POST['permissions'] as $p) $permArray[$p] = true;
    }

    if (empty($errors)) {
        if ($id) {
            $db->update('roles', ['role' => $rname, 'permissions' => json_encode($permArray)], 'id = ?', [$id]);
            setFlashMessage('success', 'Role updated.');
        } else {
            $db->insert('roles', ['role' => $rname, 'permissions' => json_encode($permArray)]);
            setFlashMessage('success', 'Role created.');
        }
        header('Location: roles.php'); exit;
    }
}

$pageTitle = $id ? 'Edit Role' : 'New Role';
include __DIR__ . '/includes/header.php';
$selectedPerms = [];
if ($role && !empty($role['permissions'])) {
    $decoded = is_string($role['permissions']) ? json_decode($role['permissions'], true) : $role['permissions'];
    if (is_array($decoded)) $selectedPerms = array_keys(array_filter($decoded));
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0"><?php echo htmlspecialchars($pageTitle); ?></h1>
    <p class="text-muted mb-0">Manage the role's default permissions</p>
  </div>
  <div>
    <a href="roles.php" class="btn btn-outline-secondary">Back</a>
  </div>
</div>

<?php if (!empty($errors)): ?>
  <div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e): ?><li><?php echo htmlspecialchars($e); ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>

<div class="card">
  <div class="card-body">
    <form method="post">
      <div class="mb-3">
        <label class="form-label">Role key</label>
        <input type="text" name="role" class="form-control" value="<?php echo htmlspecialchars($_POST['role'] ?? ($role['role'] ?? '')); ?>" required>
      </div>

      <div class="mb-3">
        <label class="form-label">Permissions</label>
        <div class="d-flex flex-wrap gap-2">
          <?php foreach ($availablePermissions as $perm): ?>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" name="permissions[]" value="<?php echo $perm; ?>" id="perm_<?php echo $perm; ?>" <?php echo in_array($perm, ($_POST['permissions'] ?? $selectedPerms)) ? 'checked' : ''; ?> >
              <label class="form-check-label small" for="perm_<?php echo $perm; ?>"><?php echo $perm; ?></label>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="d-flex justify-content-end gap-2">
        <a href="roles.php" class="btn btn-outline-secondary">Cancel</a>
        <button class="btn btn-primary">Save</button>
      </div>
    </form>
  </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>