<?php
class PermissionMiddleware {
    private $auth;
    private $adminData;
    
    public function __construct($auth, $adminData) {
        $this->auth = $auth;
        $this->adminData = $adminData;
    }
    
    /**
     * Check if admin has required permission
     */
    public function requirePermission($permissionKey, $redirectUrl = 'dashboard-multi.php') {
        if (!$this->auth->hasPermission($this->adminData, $permissionKey)) {
            $errorMsg = urlencode("Access denied. Required permission: $permissionKey");
            header("Location: $redirectUrl?error=$errorMsg");
            exit;
        }
    }
    
    /**
     * Check if admin has specific permission (convenience method)
     */
    public function hasPermission($permissionKey) {
        return $this->auth->hasPermission($this->adminData, $permissionKey);
    }
    
    /**
     * Check if admin is master admin (convenience method)
     */
    public function isMasterAdmin() {
        return isset($this->adminData['is_master']) && $this->adminData['is_master'];
    }
    
    /**
     * Check if admin has market access (convenience method)
     */
    public function hasMarketAccess($marketName, $accessType = 'can_view') {
        return $this->auth->hasMarketAccess($this->adminData, $marketName, $accessType);
    }
    
    /**
     * Check if admin has master access
     */
    public function requireMasterAdmin($redirectUrl = 'dashboard-multi.php') {
        if (!isset($this->adminData['is_master']) || !$this->adminData['is_master']) {
            $errorMsg = urlencode("Access denied. Master admin only.");
            header("Location: $redirectUrl?error=$errorMsg");
            exit;
        }
    }
    
    /**
     * Check if admin has access to specific market
     */
    public function requireMarketAccess($marketName, $accessType = 'can_view', $redirectUrl = 'dashboard-multi.php') {
        if (!$this->auth->hasMarketAccess($this->adminData, $marketName, $accessType)) {
            $errorMsg = urlencode("Access denied. No $accessType access to market $marketName");
            header("Location: $redirectUrl?error=$errorMsg");
            exit;
        }
    }
    
    /**
     * Check multiple permissions (AND logic)
     */
    public function requireAllPermissions($permissions, $redirectUrl = 'dashboard-multi.php') {
        foreach ($permissions as $permission) {
            if (!$this->auth->hasPermission($this->adminData, $permission)) {
                $errorMsg = urlencode("Access denied. Missing required permissions.");
                header("Location: $redirectUrl?error=$errorMsg");
                exit;
            }
        }
    }
    
    /**
     * Check if admin has any of the specified permissions (OR logic)
     */
    public function requireAnyPermission($permissions, $redirectUrl = 'dashboard-multi.php') {
        foreach ($permissions as $permission) {
            if ($this->auth->hasPermission($this->adminData, $permission)) {
                return true; // Has at least one permission
            }
        }
        
        $errorMsg = urlencode("Access denied. No required permissions found.");
        header("Location: $redirectUrl?error=$errorMsg");
        exit;
    }
    
    /**
     * Filter markets based on admin access
     */
    public function filterAccessibleMarkets($markets, $accessType = 'can_view') {
        if (isset($this->adminData['is_master']) && $this->adminData['is_master']) {
            return $markets; // Master admin sees all markets
        }
        
        $accessibleMarkets = [];
        foreach ($markets as $market) {
            if ($this->auth->hasMarketAccess($this->adminData, $market, $accessType)) {
                $accessibleMarkets[] = $market;
            }
        }
        
        return $accessibleMarkets;
    }
    
    /**
     * Get admin's accessible markets
     */
    public function getAccessibleMarkets($accessType = 'can_view') {
        return $this->auth->getAccessibleMarkets($this->adminData, $accessType);
    }
    
    /**
     * Check if current admin can manage another admin
     */
    public function canManageAdmin($targetAdminId) {
        // Only master admin can manage other admins
        if (!isset($this->adminData['is_master']) || !$this->adminData['is_master']) {
            return false;
        }
        
        // Master admin can manage all sub-admins in their site
        return true;
    }
    
    /**
     * Log admin action
     */
    public function logAction($actionType, $description, $targetTable = null, $targetId = null) {
        $adminId = $this->adminData['id'] ?? 0;
        $this->auth->logActivity($adminId, $actionType, $description, $targetTable, $targetId);
    }
    
    /**
     * Get permission display name
     */
    public function getPermissionName($permissionKey) {
        $permissions = $this->adminData['permissions'] ?? [];
        return $permissions[$permissionKey]['name'] ?? $permissionKey;
    }
    
    /**
     * Check if admin is logged in and session is valid
     */
    public static function validateSession($pdo) {
        if (!isset($_SESSION['admin_session_id'])) {
            return false;
        }
        
        $auth = new MultiTenantAuth($pdo);
        $sessionData = $auth->validateSession($_SESSION['admin_session_id']);
        
        if ($sessionData) {
            // Update session data
            $_SESSION['admin_data'] = $sessionData;
            return $sessionData;
        }
        
        // Session invalid, clear it
        session_destroy();
        return false;
    }
    
    /**
     * Require valid session (use at top of protected pages)
     */
    public static function requireValidSession($pdo, $redirectUrl = 'login-multi.php') {
        $adminData = self::validateSession($pdo);
        if (!$adminData) {
            header("Location: $redirectUrl");
            exit;
        }
        return $adminData;
    }
    
    /**
     * Create middleware instance from session
     */
    public static function fromSession($pdo) {
        $adminData = self::requireValidSession($pdo);
        $auth = new MultiTenantAuth($pdo);
        return new self($auth, $adminData);
    }
}

/**
 * Helper function to quickly check permissions in templates
 */
function hasPermission($permissionKey) {
    global $adminData, $auth;
    if (!$auth || !$adminData) return false;
    return $auth->hasPermission($adminData, $permissionKey);
}

/**
 * Helper function to check market access in templates
 */
function hasMarketAccess($marketName, $accessType = 'can_view') {
    global $adminData, $auth;
    if (!$auth || !$adminData) return false;
    return $auth->hasMarketAccess($adminData, $marketName, $accessType);
}

/**
 * Helper function to check if current user is master admin
 */
function isMasterAdmin() {
    global $adminData;
    return isset($adminData['is_master']) && $adminData['is_master'];
}

/**
 * Helper function to get admin's accessible markets
 */
function getAccessibleMarkets($accessType = 'can_view') {
    global $adminData, $auth;
    if (!$auth || !$adminData) return [];
    return $auth->getAccessibleMarkets($adminData, $accessType);
}
?>