<?php
/**
 * UNIFIED PERMISSION ENFORCER
 * 
 * Single centralized file for all permission enforcement logic
 * Replaces/supplements the 25+ individual enforce_manage_*.php files
 * 
 * Usage:
 *   require_once __DIR__ . '/permission_enforcer.php';
 *   PermissionEnforcer::guardPage('manage_products');
 *   PermissionEnforcer::guardAction('manage_products', 'delete');
 *   $caps = PermissionEnforcer::getCapabilities('manage_products');
 */

require_once __DIR__ . '/permission_helper.php';
require_once __DIR__ . '/subadmin_actions.php';

class PermissionEnforcer {
    
    /**
     * Check if current user is full admin
     * @return bool
     */
    private static function isAdmin() {
        return isset($_SESSION['is_admin']) && $_SESSION['is_admin'] === true;
    }
    
    /**
     * Check if current user is sub-admin
     * @return bool
     */
    private static function isSubadmin() {
        return isset($_SESSION['is_subadmin']) && $_SESSION['is_subadmin'] === true;
    }
    
    /**
     * Get sub-admin permissions from session
     * @return array
     */
    private static function getPermissions() {
        return $_SESSION['subadmin_permissions'] ?? [];
    }
    
    /**
     * ENFORCE PAGE ACCESS
     * 
     * Full admins: Always pass
     * Sub-admins: Must have view permission for feature
     * Others: Redirect to login
     * 
     * Usage: PermissionEnforcer::guardPage('manage_products');
     * 
     * @param string $feature Feature name to check
     */
    public static function guardPage($feature) {
        // Full admins always have access
        if (self::isAdmin()) {
            return true;
        }
        
        // Not logged in at all?
        if (!self::isSubadmin()) {
            header('Location: admin_login.php');
            exit;
        }
        
        // Sub-admin must have view access
        $permissions = self::getPermissions();
        $allowed = PermissionHelper::can($feature, 'view', $permissions);
        
        if (!$allowed) {
            $_SESSION['error_message'] = "You don't have permission to view this feature.";
            header('Location: subadmin_dashboard.php');
            exit;
        }
        
        return true;
    }
    
    /**
     * ENFORCE ACTION
     * 
     * Full admins: Always pass
     * Sub-admins: Check specific action permission
     * Others: Return 403 Forbidden
     * 
     * Usage: PermissionEnforcer::guardAction('manage_products', 'delete');
     * 
     * @param string $feature Feature name
     * @param string $action Action: view, create, edit, delete
     */
    public static function guardAction($feature, $action) {
        // Full admins always have access
        if (self::isAdmin()) {
            return true;
        }
        
        // Not logged in?
        if (!self::isSubadmin()) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access denied']);
            exit;
        }
        
        // Sub-admin must have permission for action
        $permissions = self::getPermissions();
        $result = SubAdminActions::checkAction($feature, $action, $permissions);
        
        if (!$result['allowed']) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => $result['message']]);
            exit;
        }
        
        return true;
    }
    
    /**
     * GET CAPABILITIES FOR UI RENDERING
     * 
     * Returns capability array for conditional button/form display
     * Usage: $caps = PermissionEnforcer::getCapabilities('manage_products');
     *        if ($caps['can_delete']) { show delete button }
     * 
     * @param string $feature Feature name
     * @return array ['can_view', 'can_create', 'can_edit', 'can_delete', 'level']
     */
    public static function getCapabilities($feature) {
        // Full admins have all capabilities
        if (self::isAdmin()) {
            return [
                'can_view' => true,
                'can_create' => true,
                'can_edit' => true,
                'can_delete' => true,
                'level' => 'administrator'
            ];
        }
        
        // Sub-admin or not logged in
        if (!self::isSubadmin()) {
            return [
                'can_view' => false,
                'can_create' => false,
                'can_edit' => false,
                'can_delete' => false,
                'level' => 'none'
            ];
        }
        
        // Sub-admin: get actual capabilities
        $permissions = self::getPermissions();
        return SubAdminActions::getCapabilities($feature, $permissions);
    }
    
    /**
     * QUICK BOOLEAN CHECK
     * 
     * Usage: if (PermissionEnforcer::can('manage_products', 'delete')) { ... }
     * 
     * @param string $feature Feature name
     * @param string $action Action to check
     * @return bool
     */
    public static function can($feature, $action) {
        // Full admins always can
        if (self::isAdmin()) {
            return true;
        }
        
        // Sub-admins check permissions
        if (self::isSubadmin()) {
            $permissions = self::getPermissions();
            return PermissionHelper::can($feature, $action, $permissions);
        }
        
        // Others cannot
        return false;
    }
    
    /**
     * GET PERMISSION LEVEL FOR A FEATURE
     * 
     * Returns: 'administrator', 'editor', 'viewer', 'none'
     * 
     * @param string $feature Feature name
     * @return string Permission level
     */
    public static function getLevel($feature) {
        // Admin level
        if (self::isAdmin()) {
            return 'administrator';
        }
        
        // Sub-admin or unauthorized
        if (self::isSubadmin()) {
            $permissions = self::getPermissions();
            return PermissionHelper::getLevel($feature, $permissions);
        }
        
        return 'none';
    }
    
    /**
     * CHECK IF USER HAS ANY ACCESS TO FEATURE
     * 
     * @param string $feature Feature name
     * @return bool
     */
    public static function hasAccess($feature) {
        return self::can($feature, 'view');
    }
    
    /**
     * VALIDATE API REQUEST (FOR JSON ENDPOINTS)
     * 
     * Use before processing API request from admin actions
     * Exits with 403 JSON if not allowed
     * 
     * Usage: PermissionEnforcer::validateApiAction('manage_products', 'delete');
     * 
     * @param string $feature Feature name
     * @param string $action Action to validate
     */
    public static function validateApiAction($feature, $action) {
        self::guardAction($feature, $action);
    }
    
    /**
     * RENDER CONDITIONAL DELETE BUTTON
     * 
     * Renders delete button only if user can delete
     * Otherwise renders disabled button
     * 
     * @param string $feature Feature name
     * @param int $id Item ID
     * @param string $label Button label
     * @param string $confirmText Confirmation text
     */
    public static function renderDeleteButton($feature, $id, $label = 'Delete', $confirmText = 'Are you sure?') {
        $caps = self::getCapabilities($feature);
        
        if (!$caps['can_delete']) {
            echo '<button class="btn" disabled style="background:#ccc; color:#999; cursor:not-allowed; opacity:0.6;" title="Delete not allowed for this feature">' . htmlspecialchars($label) . '</button>';
            return;
        }
        
        echo '<button class="btn" type="button" onclick="if(confirm(\'' . htmlspecialchars(addslashes($confirmText)) . '\')) { deleteItem(' . (int)$id . '); }" style="background:#e74c3c; color:#fff;">' . htmlspecialchars($label) . '</button>';
    }
    
    /**
     * RENDER CONDITIONAL CREATE BUTTON
     * 
     * @param string $feature Feature name
     * @param string $label Button label
     * @param string $onclick Onclick handler
     */
    public static function renderCreateButton($feature, $label = '+ Add New', $onclick = 'showCreateForm()') {
        $caps = self::getCapabilities($feature);
        
        if (!$caps['can_create']) {
            echo '<button class="btn" disabled style="background:#ccc; color:#999; cursor:not-allowed; opacity:0.6;" title="Create not allowed for this feature">' . htmlspecialchars($label) . '</button>';
            return;
        }
        
        echo '<button class="btn" type="button" onclick="' . htmlspecialchars($onclick) . '" style="background:#4CAF50; color:#fff;">' . htmlspecialchars($label) . '</button>';
    }
    
    /**
     * RENDER CONDITIONAL EDIT BUTTON
     * 
     * @param string $feature Feature name
     * @param int $id Item ID
     * @param string $label Button label
     */
    public static function renderEditButton($feature, $id, $label = 'Edit') {
        $caps = self::getCapabilities($feature);
        
        if (!$caps['can_edit']) {
            echo '<button class="btn" disabled style="background:#ccc; color:#999; cursor:not-allowed; opacity:0.6;" title="Edit not allowed for this feature">' . htmlspecialchars($label) . '</button>';
            return;
        }
        
        echo '<button class="btn" type="button" onclick="editItem(' . (int)$id . ')" style="background:#2196F3; color:#fff;">' . htmlspecialchars($label) . '</button>';
    }
}

?>
