# Permission Hierarchy System - Integration Guide for Developers

## Quick Start

The permission hierarchy system is now live. Here's how to use it in your sub-admin pages.

## Overview

**Three Permission Levels:**
- `'none'` - No access
- `'viewer'` - Read-only
- `'editor'` - Can view, create, edit (NOT delete)
- `'administrator'` - Full access

## Integration Examples

### Example 1: Protecting a DELETE Action

```php
<?php
// In your API handler (e.g., api_delete_product.php)
session_start();
require_once __DIR__ . '/helpers/subadmin_actions.php';

// Verify sub-admin has permission to delete products
SubAdminActions::enforceSilent('manage_products', 'delete', $_SESSION['subadmin_permissions']);

// If we reach here, delete is authorized - proceed safely
$id = (int)$_POST['id'];
// ... delete logic ...
echo json_encode(['success' => true, 'message' => 'Deleted']);
exit;
?>
```

### Example 2: Hiding UI Elements Based on Permissions

```php
<?php
// In your admin page (e.g., admin_products.php)
require_once __DIR__ . '/helpers/subadmin_actions.php';

// Get capabilities for current permission level
$caps = SubAdminActions::getCapabilities('manage_products', $_SESSION['subadmin_permissions']);
?>

<!-- Show DELETE button only if administrator -->
<?php if ($caps['can_delete']): ?>
    <button onclick="deleteProduct(<?php echo $id; ?>)">Delete</button>
<?php else: ?>
    <span style="color:#999;" title="Viewers and Editors cannot delete">
        Delete (Not Allowed)
    </span>
<?php endif; ?>

<!-- Show EDIT button if editor or admin -->
<?php if ($caps['can_edit']): ?>
    <button onclick="editProduct(<?php echo $id; ?>)">Edit</button>
<?php endif; ?>

<!-- Show CREATE button if editor or admin -->
<?php if ($caps['can_create']): ?>
    <button onclick="newProduct()">+ New Product</button>
<?php endif; ?>
```

### Example 3: Complete CRUD Operations with Permissions

```php
<?php
session_start();
require_once __DIR__ . '/db_config.php';
require_once __DIR__ . '/helpers/subadmin_actions.php';

header('Content-Type: application/json');

$action = $_POST['action'] ?? '';
$perms = $_SESSION['subadmin_permissions'] ?? [];

// CREATE
if ($action === 'create') {
    SubAdminActions::enforceSilent('manage_products', 'create', $perms);
    // ... create logic ...
}

// READ (always allowed if has access)
if ($action === 'list') {
    SubAdminActions::enforceSilent('manage_products', 'view', $perms);
    // ... read logic ...
}

// UPDATE
if ($action === 'update') {
    SubAdminActions::enforceSilent('manage_products', 'edit', $perms);
    // ... edit logic ...
}

// DELETE
if ($action === 'delete') {
    SubAdminActions::enforceSilent('manage_products', 'delete', $perms);
    // ... delete logic ...
}

echo json_encode(['success' => true]);
exit;
?>
```

## Helper Functions Reference

### PermissionHelper Class

```php
// Check if can perform specific action
bool PermissionHelper::can($feature, $action, $permissions)
// Actions: 'view', 'create', 'edit', 'delete'

// Check if has any access
bool PermissionHelper::hasAccess($feature, $permissions)

// Get permission level
string PermissionHelper::getLevel($feature, $permissions)
// Returns: 'none', 'viewer', 'editor', 'administrator'

// Get all accessible features
array PermissionHelper::getAccessibleFeatures($permissions)
// Returns: ['feature' => 'level', ...]
```

### SubAdminActions Class

```php
// Check action and get response
array SubAdminActions::checkAction($feature, $action, $permissions)
// Returns: ['allowed' => bool, 'message' => string]

// Silent enforcement (exits if not allowed)
void SubAdminActions::enforceSilent($feature, $action, $permissions)
// HTTP 403 if denied, continues if allowed

// Get all capabilities
array SubAdminActions::getCapabilities($feature, $permissions)
// Returns: [
//   'can_view' => bool,
//   'can_create' => bool,
//   'can_edit' => bool,
//   'can_delete' => bool,
//   'level' => string
// ]
```

## Common Scenarios

### Scenario 1: Sub-admin is Viewer
```
Trying to: Update a product
Permission: manage_products = 'viewer'
Result: Error - "Edit operation not allowed"
```

### Scenario 2: Sub-admin is Editor
```
Trying to: Delete a product
Permission: manage_products = 'editor'
Result: Error - "Delete operation not allowed. Only Administrators can delete content."
```

### Scenario 3: Sub-admin is Administrator
```
Trying to: Delete a product
Permission: manage_products = 'administrator'
Result: Success - Product deleted
```

## Permission Matrix

| Action | None | Viewer | Editor | Admin |
|--------|------|--------|--------|-------|
| view   | ❌   | ✅     | ✅     | ✅    |
| create | ❌   | ❌     | ✅     | ✅    |
| edit   | ❌   | ❌     | ✅     | ✅    |
| delete | ❌   | ❌     | ❌     | ✅    |

## Session Variables

After login, sub-admin sessions contain:

```php
$_SESSION['is_subadmin'] = true;
$_SESSION['subadmin_permissions'] = [
    'manage_products' => 'editor',
    'manage_blogs' => 'viewer',
    'manage_users' => 'administrator',
    'manage_orders' => 'none',
    // ... all 25 features
];
```

## Best Practices

### ✅ DO:
1. Always use `SubAdminActions::enforceSilent()` in API handlers
2. Check permissions before showing sensitive buttons
3. Test both allowed and denied scenarios
4. Log permission violations for audit trail
5. Use consistent feature names from the list

### ❌ DON'T:
1. Trust client-side permission checks alone
2. Skip backend permission verification
3. Use incorrect feature names
4. Cache permissions in frontend
5. Allow bypass of permission checks

## Backward Compatibility

Old boolean permissions are automatically converted:

```php
// Old format (still works)
'manage_products' => true  → Converted to 'editor'
'manage_products' => false → Converted to 'none'

// New format (use this)
'manage_products' => 'viewer'
'manage_products' => 'editor'
'manage_products' => 'administrator'
```

## Testing Permission Enforcement

### Manual Test
1. Create sub-admin with Viewer access to Products
2. Go to Products page as that sub-admin
3. Edit button should be hidden or disabled
4. Try to edit via API → Should return 403 error

### Automated Test Example
```php
// test_permissions.php
<?php
require_once 'helpers/permission_helper.php';

$perms = ['manage_products' => 'viewer'];

// Should be true
assert(PermissionHelper::can('manage_products', 'view', $perms) === true);

// Should be false
assert(PermissionHelper::can('manage_products', 'create', $perms) === false);
assert(PermissionHelper::can('manage_products', 'edit', $perms) === false);
assert(PermissionHelper::can('manage_products', 'delete', $perms) === false);

echo "All tests passed!";
?>
```

## Migration Checklist

For each sub-admin page:

- [ ] Include permission helper: `require_once 'helpers/subadmin_actions.php'`
- [ ] Add enforcement to DELETE action handlers
- [ ] Add enforcement to CREATE action handlers
- [ ] Add enforcement to UPDATE action handlers
- [ ] Hide DELETE buttons for non-admin users
- [ ] Hide CREATE buttons for viewers
- [ ] Test with Viewer permission level
- [ ] Test with Editor permission level
- [ ] Test with Administrator permission level
- [ ] Test attempts to bypass permissions

## Support

For detailed documentation, see:
- `PERMISSION_HIERARCHY_README.md` - Full reference
- `PERMISSION_SYSTEM_SUMMARY.md` - System overview
- This file - Developer integration guide

---

**Last Updated:** January 2024
**Version:** 1.0
**Status:** Production Ready ✅
