# RR3 Community Server - Web Admin Panel

## 🎉 Overview

The RR3 Community Server now includes a **comprehensive web administration panel** for managing your Real Racing 3 server. The web panel provides an intuitive interface for viewing statistics, managing users, configuring catalog items, monitoring sessions, and more.

## 🚀 Quick Start

### 1. Start the Server

```powershell
cd E:\rr3\RR3CommunityServer\RR3CommunityServer
dotnet run
```

### 2. Access the Web Panel

Open your browser and navigate to:
```
http://localhost:5000
```

The root URL will automatically redirect you to the admin dashboard at `/admin`.

## 📋 Features

### Dashboard (`/admin`)
- **Real-time Statistics**: View total users, active sessions, devices, and catalog items
- **Quick Actions**: Navigate to different management sections
- **Recent Activity**: See latest users and active sessions
- **Server Information**: View server URL, platform, .NET version, and uptime

### User Management (`/admin/users`)
- View all registered users
- Search users by Synergy ID or Device ID
- View detailed user information
- Delete user accounts
- Modal dialogs for user details

### Catalog Management (`/admin/catalog`)
- View all catalog items
- Add new items (cars, upgrades, currency, consumables)
- Edit existing items (SKU, name, type, price, availability)
- Toggle item availability (enable/disable items)
- Delete items
- Filter items by type

### Session Management (`/admin/sessions`)
- View active and expired sessions
- Real-time session statistics
- See session expiration times and remaining time
- Terminate active sessions
- Cleanup expired sessions (bulk delete)
- Color-coded session status

### Purchase History (`/admin/purchases`)
- View all in-game purchases
- Search purchases by SKU or User ID
- View purchase statistics (total count, approved count, total value)
- View detailed purchase information
- Delete purchase records

### Server Settings (`/admin/settings`)
- View server configuration (URL, endpoints, database, session timeout)
- APK configuration instructions
- System information (OS, .NET version, uptime, memory usage)
- Database statistics dashboard
- Quick links to documentation and Swagger API
- **Danger Zone**: Reset database (delete all data)

## 🎨 Design Features

### Modern UI
- **Bootstrap 5** for responsive layout
- **Racing-themed color scheme** (red, dark blue)
- **Card-based design** with hover effects
- **Icon integration** using Bootstrap Icons
- **Responsive navigation** for mobile and desktop

### UX Features
- **Real-time stats** on dashboard
- **Modal dialogs** for detailed views
- **Search functionality** on users and purchases
- **Inline editing** for catalog items
- **Confirmation dialogs** for destructive actions
- **Copy-to-clipboard** for server URLs
- **Color-coded badges** for status indicators

### Accessibility
- Semantic HTML structure
- Keyboard-friendly navigation
- Screen-reader friendly labels
- High contrast color scheme
- Clear visual hierarchy

## 📖 Page Details

### Dashboard Widgets

**Statistics Cards:**
- 👥 Total Users - Count of registered players
- 🔄 Active Sessions - Currently online players
- 📱 Total Devices - Registered devices
- 🏪 Catalog Items - Available items

**Recent Activity Tables:**
- Last 5 registered users
- Last 5 active sessions

**Server Info Panel:**
- Server URL with copy button
- Platform and .NET version
- Database type and API endpoint count
- Link to Swagger API documentation

### Catalog Item Types

The catalog supports four item types:
1. **car** - Racing vehicles
2. **upgrade** - Vehicle upgrades (engine, tires, etc.)
3. **currency** - In-game currency (gold, cash)
4. **consumable** - Single-use items

### Session Management

Sessions have a **24-hour expiration** by default. The session manager shows:
- Active sessions (green badge with time remaining)
- Expired sessions (gray, archived)
- Ability to terminate sessions manually
- Bulk cleanup of expired sessions

### Purchase Status

Purchases in the community server are auto-approved by default:
- ✓ **Approved** - Purchase completed
- ⏳ **Pending** - Awaiting approval (unused in community server)

## 🔧 Configuration

### Server URL
The server automatically detects its URL from the request. To use a custom domain:

1. Configure your web server (IIS, nginx, Apache) to proxy to the ASP.NET Core app
2. Update the `appsettings.json` with forwarded headers support
3. The web panel will automatically display the correct URL

### Database Location
SQLite database is stored at:
```
E:\rr3\RR3CommunityServer\RR3CommunityServer\rr3community.db
```

### Seeded Data
The database comes pre-seeded with 3 catalog items:
- 1000 Gold ($0.99)
- Starter Car (Free)
- Engine Upgrade ($4.99)

## 🌐 API Integration

The web panel is built on top of the existing REST API. You can:
- Use the web panel for administration
- Use the REST API (`/swagger`) for programmatic access
- Both use the same database and business logic

### Swagger Documentation
Access interactive API docs at:
```
http://localhost:5000/swagger
```

## 🔐 Security Notes

### Current State (Development)
⚠️ The web panel currently has **NO authentication** - it's open access.

### For Production Use
Before deploying to production, you should:

1. **Add authentication**: Implement ASP.NET Core Identity or another auth system
2. **Use HTTPS**: Configure SSL certificates
3. **Restrict access**: Use firewall rules or IP whitelisting
4. **Secure the database**: Use encryption and secure file permissions
5. **Disable Swagger**: Remove Swagger UI in production builds

Example: Add authentication to `Program.cs`:
```csharp
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/login";
        options.LogoutPath = "/logout";
    });

// In middleware pipeline:
app.UseAuthentication();
app.UseAuthorization();
```

Then add `[Authorize]` attributes to Razor Pages.

## 📁 File Structure

```
RR3CommunityServer/
├── Pages/
│   ├── Admin.cshtml              # Dashboard
│   ├── Admin.cshtml.cs
│   ├── Users.cshtml              # User management
│   ├── Users.cshtml.cs
│   ├── Catalog.cshtml            # Catalog management
│   ├── Catalog.cshtml.cs
│   ├── Sessions.cshtml           # Session management
│   ├── Sessions.cshtml.cs
│   ├── Purchases.cshtml          # Purchase history
│   ├── Purchases.cshtml.cs
│   ├── Settings.cshtml           # Server settings
│   ├── Settings.cshtml.cs
│   ├── _Layout.cshtml            # Master layout
│   └── _ViewStart.cshtml         # Layout binding
├── wwwroot/
│   ├── css/                      # Custom stylesheets
│   └── js/                       # Custom scripts
├── Controllers/                  # REST API controllers
├── Services/                     # Business logic
├── Data/                         # Database context
└── Program.cs                    # App entry point
```

## 🛠️ Customization

### Changing Colors
Edit `_Layout.cshtml` CSS variables:
```css
:root {
    --rr3-primary: #e63946;   /* Racing red */
    --rr3-dark: #1d3557;      /* Dark blue */
    --rr3-light: #f1faee;     /* Light cream */
}
```

### Adding Custom Pages
1. Create new `.cshtml` file in `Pages/` folder
2. Create corresponding `.cshtml.cs` code-behind file
3. Add link to `_Layout.cshtml` navigation
4. Inject `RR3DbContext` in code-behind for database access

### Modifying Dashboard Widgets
Edit `Admin.cshtml` to add/remove cards or change statistics.

## 🐛 Troubleshooting

### Web panel not loading
- Ensure server is running: `dotnet run`
- Check the port (default: 5000 for HTTP, 5001 for HTTPS)
- Check firewall settings

### Database errors
- Delete `rr3community.db` and restart server to recreate
- Check file permissions on database file
- View logs in console output

### Style issues
- Clear browser cache (Ctrl+F5)
- Check browser console for CDN loading errors
- Ensure Bootstrap CDN is accessible

### Missing data
- Use "Reset Database" in Settings page (⚠️ deletes all data!)
- Check that seed data was created on first run
- View raw database with DB Browser for SQLite

## 📚 Related Documentation

- [Server Implementation Guide](./IMPLEMENTATION_GUIDE.md)
- [Network Protocol Analysis](../NETWORK_COMMUNICATION_ANALYSIS.md)
- [APK Modification Guide](../APK_MODIFICATION_GUIDE.md)
- [Project Index](../PROJECT_INDEX.md)

## 🎯 Next Steps

1. **Test the web panel**: Start the server and explore all pages
2. **Add catalog items**: Use the Catalog page to add cars and upgrades
3. **Connect a game client**: Modify an APK to point to your server
4. **Monitor activity**: Watch the dashboard as players connect
5. **Customize**: Modify the UI to match your preferences

## 💡 Tips

- **Use search features**: Quickly find users and purchases
- **Export data**: Use Swagger API to export data programmatically
- **Backup database**: Copy `rr3community.db` file regularly
- **Monitor sessions**: Clean up expired sessions weekly
- **Test purchases**: Add free items to test the purchase flow

---

**Made with ❤️ for game preservation and the Real Racing 3 community**
