<?php
/**
 * Sub-Admin Page Guard
 * Enforces permission checks at the page level
 * Include this at the top of any admin page that sub-admins should access
 * 
 * Usage:
 *   require_once __DIR__ . '/helpers/subadmin_page_guard.php';
 *   $guard = new SubAdminPageGuard('manage_products'); // Feature name
 *   $guard->enforceView(); // Only check view access
 *   $guard->enforceAccess('delete'); // Check specific action
 */

require_once __DIR__ . '/subadmin_actions.php';

class SubAdminPageGuard {
    
    private $feature;
    private $isSubadmin;
    private $permissions;
    
    /**
     * Initialize guard for a specific feature
     * @param string $feature Feature name (e.g., 'manage_products')
     */
    public function __construct($feature) {
        $this->feature = $feature;
        $this->isSubadmin = !empty($_SESSION['is_subadmin']);
        $this->permissions = $_SESSION['subadmin_permissions'] ?? [];
    }
    
    /**
     * Check if current user is admin (full access)
     * @return bool
     */
    public function isAdmin() {
        return !empty($_SESSION['is_admin']);
    }
    
    /**
     * Check if current user is sub-admin
     * @return bool
     */
    public function isSubadmin() {
        return $this->isSubadmin;
    }
    
    /**
     * Enforce minimum 'view' access for this feature
     * Redirect to subadmin_dashboard.php if no access
     */
    public function enforceView() {
        if ($this->isAdmin()) return; // Full admins always have access
        
        if (!$this->isSubadmin) {
            header('Location: admin_login.php');
            exit;
        }
        
        // Sub-admin must have at least 'view' access
        if (!SubAdminActions::checkAction($this->feature, 'view', $this->permissions)['allowed']) {
            $_SESSION['error_message'] = "You don't have permission to view this feature.";
            header('Location: subadmin_dashboard.php');
            exit;
        }
    }
    
    /**
     * Enforce specific action access (for API handlers)
     * Returns array with ['allowed' => bool, 'message' => string]
     * If not allowed, sends JSON error response
     * 
     * @param string $action Action to check: 'view', 'create', 'edit', 'delete'
     * @return bool True if allowed, false otherwise (and response sent)
     */
    public function enforceAction($action) {
        if ($this->isAdmin()) return true; // Full admins always have access
        
        if (!$this->isSubadmin) {
            http_response_code(403);
            echo json_encode([
                'success' => false,
                'message' => 'Access denied. Sub-admin permission required.'
            ]);
            exit;
        }
        
        $result = SubAdminActions::checkAction($this->feature, $action, $this->permissions);
        if (!$result['allowed']) {
            http_response_code(403);
            echo json_encode([
                'success' => false,
                'message' => $result['message']
            ]);
            exit;
        }
        
        return true;
    }
    
    /**
     * Get capabilities for UI conditional rendering
     * Returns array with 'can_view', 'can_create', 'can_edit', 'can_delete', 'level'
     * 
     * @return array Capabilities
     */
    public function getCapabilities() {
        if ($this->isAdmin()) {
            return [
                'can_view' => true,
                'can_create' => true,
                'can_edit' => true,
                'can_delete' => true,
                'level' => 'administrator'
            ];
        }
        
        if (!$this->isSubadmin) {
            return [
                'can_view' => false,
                'can_create' => false,
                'can_edit' => false,
                'can_delete' => false,
                'level' => 'none'
            ];
        }
        
        return SubAdminActions::getCapabilities($this->feature, $this->permissions);
    }
    
    /**
     * Check if can perform action (returns boolean only)
     * @param string $action Action to check
     * @return bool
     */
    public function can($action) {
        if ($this->isAdmin()) return true;
        
        if (!$this->isSubadmin) return false;
        
        return SubAdminActions::checkAction($this->feature, $action, $this->permissions)['allowed'];
    }
    
    /**
     * Show delete button only if user can delete
     * @param string $id ID of item to delete (for onclick)
     * @param string $confirmText Confirm text (optional)
     */
    public function renderDeleteButton($id, $confirmText = 'Delete this item?') {
        if (!$this->can('delete')) {
            echo '<span class="btn" style="background:#ccc; color:#999; cursor:not-allowed; opacity:0.6;" title="Deletes not allowed for this feature">Delete</span>';
            return;
        }
        echo '<button class="btn" type="button" onclick="if(confirm(\'' . htmlspecialchars(addslashes($confirmText)) . '\')) { deleteItem(' . (int)$id . '); }" style="background:#e74c3c; color:#fff;">Delete</button>';
    }
    
    /**
     * Show create/add button only if user can create
     * @param string $label Button label
     * @param string $onclick Onclick handler
     */
    public function renderCreateButton($label = '+Add New', $onclick = 'showCreateForm()') {
        if (!$this->can('create')) {
            echo '<span class="btn" style="background:#ccc; color:#999; cursor:not-allowed; opacity:0.6;" title="Create not allowed for this feature">' . htmlspecialchars($label) . '</span>';
            return;
        }
        echo '<button class="btn" type="button" onclick="' . htmlspecialchars($onclick) . '" style="background:#4CAF50; color:#fff;">' . htmlspecialchars($label) . '</button>';
    }
    
    /**
     * Show edit button only if user can edit
     * @param string $id ID of item to edit (for onclick)
     * @param string $label Button label
     */
    public function renderEditButton($id, $label = 'Edit') {
        if (!$this->can('edit')) {
            echo '<span class="btn" style="background:#ccc; color:#999; cursor:not-allowed; opacity:0.6;" title="Edit not allowed for this feature">' . htmlspecialchars($label) . '</span>';
            return;
        }
        echo '<button class="btn" type="button" onclick="editItem(' . (int)$id . ')" style="background:#2196F3; color:#fff;">' . htmlspecialchars($label) . '</button>';
    }
    
    /**
     * Get permission level string
     * @return string 'none', 'viewer', 'editor', 'administrator'
     */
    public function getLevel() {
        if ($this->isAdmin()) return 'administrator';
        
        if (!$this->isSubadmin) return 'none';
        
        return SubAdminActions::getCapabilities($this->feature, $this->permissions)['level'];
    }
    
    /**
     * Check if sub-admin has any access to this feature
     * @return bool
     */
    public function hasAccess() {
        return $this->can('view');
    }
}

?>
