# Permission Hierarchy System Documentation

## Overview
The permission hierarchy system provides three tiers of access control for sub-admins:
- **Viewer**: Read-only access
- **Editor**: Can view, create, and edit (but NOT delete)
- **Administrator**: Full access (view, create, edit, delete)

## Three-Tier Permission Levels

### 1. Viewer (Read-Only)
- ✅ Can VIEW all content
- ❌ Cannot CREATE
- ❌ Cannot EDIT  
- ❌ Cannot DELETE

### 2. Editor
- ✅ Can VIEW content
- ✅ Can CREATE new items
- ✅ Can EDIT existing items
- ❌ Cannot DELETE

### 3. Administrator
- ✅ Can VIEW content
- ✅ Can CREATE new items
- ✅ Can EDIT existing items
- ✅ Can DELETE items

## Features with Hierarchy Support

All 25 admin features now support permission hierarchy:

1. manage_site_title
2. manage_logo
3. manage_slider_images
4. manage_colors
5. manage_categories
6. manage_pages
7. manage_social
8. manage_blogs
9. manage_products
10. manage_users
11. manage_subadmins
12. manage_orders
13. manage_news
14. manage_marquee
15. manage_footer_marquee
16. manage_featured_categories
17. manage_carousel
18. manage_slider_settings
19. manage_awards
20. manage_latest_products
21. manage_video
22. manage_footer_settings
23. manage_seo
24. manage_homepage
25. manage_settings

## How to Use the Permission System

### In Admin Panel (admin_subadmins.php)

1. Select a user to make sub-admin
2. For each feature, select the permission level:
   - **None** = No access
   - **Viewer** = Read-only
   - **Editor** = Can view, create, edit
   - **Administrator** = Full access

### In Sub-Admin Dashboard

The sub-admin dashboard displays available features with color-coded permission levels:
- **Blue** = Viewer access
- **Orange** = Editor access
- **Green** = Administrator access

### In Sub-Admin Pages (Developers)

To enforce permissions in sub-admin action handlers:

```php
<?php
require_once __DIR__ . '/helpers/subadmin_actions.php';

// Check if sub-admin can perform delete action
SubAdminActions::enforceSilent('manage_products', 'delete', $_SESSION['subadmin_permissions']);

// Continue with delete operation...
?>
```

### Available Helper Functions

#### PermissionHelper

```php
// Check if sub-admin can perform an action
PermissionHelper::can($feature, $action, $permissions);
// $action: 'view', 'create', 'edit', 'delete'

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

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

// Get all accessible features
PermissionHelper::getAccessibleFeatures($permissions); // Returns array of features with level > 'none'
```

#### SubAdminActions

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

// Silently enforce permission (exits if not allowed)
SubAdminActions::enforceSilent($feature, $action, $permissions);

// Get all capabilities for a feature
SubAdminActions::getCapabilities($feature, $permissions);
// Returns: ['can_view', 'can_create', 'can_edit', 'can_delete', 'level']
```

## Integration with Existing Pages

### Example: Products Admin Page

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

// If sub-admin is trying to delete a product
if ($_POST['action'] === 'delete_product') {
    SubAdminActions::enforceSilent('manage_products', 'delete', $_SESSION['subadmin_permissions']);
    // If we reach here, deletion is allowed
}

// Get current capabilities to decide UI elements
$caps = SubAdminActions::getCapabilities('manage_products', $_SESSION['subadmin_permissions']);
?>

<!-- Show edit button only if editor or admin -->
<?php if ($caps['can_edit']): ?>
    <button>Edit</button>
<?php endif; ?>

<!-- Show delete button only if admin -->
<?php if ($caps['can_delete']): ?>
    <button>Delete</button>
<?php endif; ?>
```

## Permission Persistence

Permissions are stored in two places:

1. **JSON Storage** (data/subadmins.json)
   ```json
   {
     "2": {
       "user_id": 2,
       "display_name": "Editor User",
       "permissions": {
         "manage_products": "editor",
         "manage_blogs": "viewer",
         "manage_users": "administrator"
       },
       "updated_at": "2024-01-15T10:30:00+00:00"
     }
   }
   ```

2. **Session Storage** ($_SESSION['subadmin_permissions'])
   - Automatically populated when sub-admin logs in
   - Same structure as JSON storage

## Migration from Old System

The system automatically converts old boolean permissions to the new hierarchy:
- Old `true` value → Converted to `'editor'`
- Old `false` value → Converted to `'none'`

This ensures backward compatibility with existing sub-admin accounts.

## Security Notes

1. Always use `SubAdminActions::enforceSilent()` in API handlers
2. Always check permissions before showing UI elements
3. Never trust client-side permission checks
4. Always verify in the backend/API
5. Permission levels are case-sensitive: 'viewer', 'editor', 'administrator', 'none'

## Troubleshooting

### Sub-admin can't delete items
- Check permission level is set to 'administrator'
- Verify page is using `SubAdminActions::enforceSilent()` enforcement

### Delete button showing but action fails
- Ensure API handler calls `SubAdminActions::enforceSilent()` before delete operation

### Permission changes not reflecting
- Clear browser cache
- Logout and login again to refresh session

## Future Enhancements

Possible additions:
- Feature-specific read filtering (viewers see only published items)
- Time-based access (e.g., 9 AM - 5 PM only)
- IP-based restrictions
- Audit logging of all sub-admin actions
- Role templates for faster setup
