# Admin Panel Integration Guide

## Overview

This guide explains how to connect the admin UI components to the backend tRPC procedures for full functionality.

## Architecture

### Backend (tRPC Routers)
- `admin.games` - Game management
- `admin.support` - Support tickets
- `admin.users` - User management
- `admin.casino` - Casino configuration

### Frontend Components
- `AdminDashboardHome` - Main dashboard
- `AdminGameAnalyticsDeep` - Game analytics
- `AdminPlayerManagement` - Player tools
- `AdminFraudDetection` - Fraud monitoring
- `AdminAuditLogs` - Audit trail
- `AdminCasinoSettings` - Game settings
- `AdminCustomerSupport` - Support management
- `AdminAnalyticsReporting` - Analytics
- `AdminSystemConfiguration` - System settings

### Real-Time Features
- `AdminNotificationCenter` - WebSocket notifications
- `useAdminNotifications` - React hook for notifications
- `adminWebSocketManager` - Server-side WebSocket manager

## Integration Steps

### 1. Connect Game Management UI

**File**: `client/src/pages/AdminCasinoSettings.tsx`

```typescript
import { trpc } from '@/lib/trpc';

export default function AdminCasinoSettings() {
  const { data: games } = trpc.adminGamesDetail.getAll.useQuery();
  const updateGameMutation = trpc.adminGamesDetail.updateGame.useMutation();

  const handleUpdateGame = async (gameId: string, updates: any) => {
    await updateGameMutation.mutateAsync({ gameId, ...updates });
  };

  // Component implementation...
}
```

### 2. Connect Support Ticket Management

**File**: `client/src/pages/AdminCustomerSupport.tsx`

```typescript
import { trpc } from '@/lib/trpc';

export default function AdminCustomerSupport() {
  const { data: tickets } = trpc.adminSupport.getTickets.useQuery();
  const replyMutation = trpc.adminSupport.replyToTicket.useMutation();

  const handleReply = async (ticketId: string, message: string) => {
    await replyMutation.mutateAsync({ ticketId, message });
  };

  // Component implementation...
}
```

### 3. Connect Player Management

**File**: `client/src/pages/AdminPlayerManagement.tsx`

```typescript
import { trpc } from '@/lib/trpc';

export default function AdminPlayerManagement() {
  const { data: players } = trpc.adminUsers.getPlayers.useQuery();
  const suspendMutation = trpc.adminUsers.suspendUser.useMutation();

  const handleSuspendPlayer = async (userId: string, reason: string) => {
    await suspendMutation.mutateAsync({ userId, reason });
  };

  // Component implementation...
}
```

### 4. Connect Fraud Detection

**File**: `client/src/pages/AdminFraudDetection.tsx`

```typescript
import { trpc } from '@/lib/trpc';

export default function AdminFraudDetection() {
  const { data: alerts } = trpc.adminUsers.getFraudAlerts.useQuery();
  const reviewMutation = trpc.adminUsers.reviewFraudAlert.useMutation();

  const handleReviewAlert = async (alertId: string, action: string) => {
    await reviewMutation.mutateAsync({ alertId, action });
  };

  // Component implementation...
}
```

### 5. Enable Real-Time Notifications

The WebSocket notification system is already configured. To trigger notifications from backend:

```typescript
// In your tRPC procedures
import { adminWebSocketManager } from '@/server/_core/websocket';

// After an important action
adminWebSocketManager.notifyAdmins({
  type: 'fraud_alert',
  title: 'Fraud Alert',
  message: 'Suspicious activity detected',
  severity: 'critical',
  timestamp: new Date(),
  data: { userId: '123', amount: 5000 }
});
```

### 6. Mobile Responsive Design

The admin panel is fully responsive:
- **Desktop**: Full sidebar navigation
- **Tablet**: Collapsible sidebar
- **Mobile**: Hamburger menu with slide-out navigation

All components automatically adapt to screen size using Tailwind's responsive classes.

## Database Schema Updates

### Add Audit Log Table

```sql
CREATE TABLE audit_logs (
  id INT PRIMARY KEY AUTO_INCREMENT,
  admin_id INT NOT NULL,
  action VARCHAR(255) NOT NULL,
  target_type VARCHAR(100),
  target_id VARCHAR(100),
  details JSON,
  ip_address VARCHAR(45),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (admin_id) REFERENCES users(id)
);
```

### Add Support Tickets Table

```sql
CREATE TABLE support_tickets (
  id INT PRIMARY KEY AUTO_INCREMENT,
  user_id INT NOT NULL,
  subject VARCHAR(255) NOT NULL,
  message TEXT NOT NULL,
  status ENUM('open', 'in_progress', 'resolved', 'closed'),
  priority ENUM('low', 'medium', 'high', 'critical'),
  assigned_to INT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id),
  FOREIGN KEY (assigned_to) REFERENCES users(id)
);
```

### Add Fraud Alerts Table

```sql
CREATE TABLE fraud_alerts (
  id INT PRIMARY KEY AUTO_INCREMENT,
  user_id INT NOT NULL,
  alert_type VARCHAR(100),
  risk_score INT,
  details JSON,
  status ENUM('pending', 'investigating', 'resolved'),
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id)
);
```

## Testing

### Test WebSocket Connection

```typescript
// In browser console
const ws = new WebSocket('ws://localhost:3000/api/admin-ws');
ws.onmessage = (e) => console.log('Message:', JSON.parse(e.data));
```

### Test tRPC Procedures

```typescript
// In browser console
import { trpc } from '@/lib/trpc';

// Test game management
trpc.adminGamesDetail.getAll.useQuery();

// Test player management
trpc.adminUsers.getPlayers.useQuery();
```

## Performance Optimization

1. **Pagination**: Implement pagination for large datasets
2. **Caching**: Use tRPC query caching for frequently accessed data
3. **Lazy Loading**: Load admin components only when needed
4. **WebSocket Limits**: Limit concurrent WebSocket connections

## Security Considerations

1. **Role-Based Access**: Verify admin role in all procedures
2. **Audit Logging**: Log all admin actions
3. **Rate Limiting**: Implement rate limiting for sensitive operations
4. **IP Whitelisting**: Optional IP whitelist for admin access
5. **Two-Factor Authentication**: Require 2FA for admin accounts

## Troubleshooting

### WebSocket Connection Issues
- Check if WebSocket server is running
- Verify firewall allows WebSocket connections
- Check browser console for errors

### tRPC Procedure Errors
- Verify admin role is set correctly
- Check database connection
- Review error logs in server console

### UI Not Updating
- Clear browser cache
- Restart dev server
- Check for TypeScript errors

## Next Steps

1. Implement database migrations for audit logs, tickets, and alerts
2. Wire up all form submissions to tRPC procedures
3. Add real-time notifications for critical events
4. Implement role-based access control
5. Add comprehensive error handling and validation
