# Biblical Guide Admin Dashboard - Implementation Plan

## Current Application Analysis

### Existing Infrastructure
- **Framework**: Next.js 15 with App Router
- **Database**: PostgreSQL with Prisma ORM
- **Authentication**: Custom JWT-based auth system
- **UI**: Tailwind CSS + shadcn/ui (main app) + MUI (admin dashboard)
- **Internationalization**: next-intl (English/Romanian)
- **Deployment**: PM2 with production build

### Current Database Schema
The app already has a solid foundation with these models:
- `User` (with role field supporting "admin", "moderator", "user")
- `Session` (JWT token management)
- `ChatConversation` & `ChatMessage` (AI chat system)
- `PrayerRequest` & `Prayer` (prayer wall functionality)
- `Bookmark` & `ChapterBookmark` (user bookmarks)
- `BiblePassage` (Bible content with embeddings)
- `ReadingHistory` (user activity tracking)

### Existing API Endpoints
- Authentication: `/api/auth/*`
- Bible operations: `/api/bible/*`
- Chat system: `/api/chat/*`
- Prayer wall: `/api/prayers/*`
- User management: `/api/user/*`
- Health check: `/api/health`

## Implementation Plan

### Phase 1: Foundation (Week 1)

#### 1.1 Admin Authentication & Authorization
**New API Routes:**
- `POST /api/admin/auth/login` - Admin login (separate from user login)
- `POST /api/admin/auth/logout` - Admin logout
- `GET /api/admin/auth/me` - Get current admin info

**Database Changes:**
```sql
-- Add admin-specific fields to User model
ALTER TABLE "User" ADD COLUMN "adminCreatedAt" TIMESTAMP;
ALTER TABLE "User" ADD COLUMN "adminLastLogin" TIMESTAMP;
ALTER TABLE "User" ADD COLUMN "adminPermissions" TEXT[]; -- ['users', 'content', 'system']

-- Create audit log table
CREATE TABLE "AdminAuditLog" (
  "id" TEXT NOT NULL PRIMARY KEY,
  "adminId" TEXT NOT NULL,
  "action" TEXT NOT NULL,
  "resource" TEXT NOT NULL,
  "resourceId" TEXT,
  "details" JSONB,
  "ipAddress" TEXT,
  "userAgent" TEXT,
  "createdAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY ("adminId") REFERENCES "User"("id") ON DELETE CASCADE
);

-- Create settings table
CREATE TABLE "AppSettings" (
  "id" TEXT NOT NULL PRIMARY KEY,
  "key" TEXT NOT NULL UNIQUE,
  "value" JSONB NOT NULL,
  "updatedBy" TEXT NOT NULL,
  "updatedAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY ("updatedBy") REFERENCES "User"("id")
);
```

**Components to Create:**
- `/app/admin/login/page.tsx` - Admin login page
- `/components/admin/auth/admin-login-form.tsx`
- `/components/admin/layout/admin-layout.tsx`
- `/lib/admin-auth.ts` - Admin authentication utilities

#### 1.2 Basic Admin Dashboard Layout
**New Pages:**
- `/app/admin/page.tsx` - Dashboard overview
- `/app/admin/layout.tsx` - Admin layout with navigation

**Components:**
- `/components/admin/dashboard/overview-cards.tsx`
- `/components/admin/layout/sidebar-nav.tsx`
- `/components/admin/layout/header.tsx`

#### 1.3 Dashboard Overview (Read-only)
**Metrics Cards:**
- Total users count
- Daily active users (last 24h login)
- AI conversations today
- Prayer requests today

**API Routes:**
- `GET /api/admin/stats/overview` - Basic dashboard metrics
- `GET /api/admin/stats/users` - User statistics

### Phase 2: User Management (Week 2)

#### 2.1 User Management Interface
**New Pages:**
- `/app/admin/users/page.tsx` - User list and search
- `/app/admin/users/[id]/page.tsx` - User detail view

**API Routes:**
- `GET /api/admin/users` - List users with filtering
- `GET /api/admin/users/[id]` - Get user details
- `PUT /api/admin/users/[id]/status` - Update user status (suspend/ban)
- `DELETE /api/admin/users/[id]` - Delete user (GDPR)
- `POST /api/admin/users/[id]/reset-password` - Force password reset

**Components:**
- `/components/admin/users/user-table.tsx`
- `/components/admin/users/user-filters.tsx`
- `/components/admin/users/user-detail-modal.tsx`
- `/components/admin/users/user-actions.tsx`

#### 2.2 Content Moderation
**Database Schema Addition:**
```sql
-- Add moderation fields to PrayerRequest
ALTER TABLE "PrayerRequest" ADD COLUMN "moderationStatus" TEXT DEFAULT 'pending'; -- pending, approved, rejected
ALTER TABLE "PrayerRequest" ADD COLUMN "moderatedBy" TEXT;
ALTER TABLE "PrayerRequest" ADD COLUMN "moderatedAt" TIMESTAMP;
ALTER TABLE "PrayerRequest" ADD COLUMN "moderationNote" TEXT;

-- Create content reports table
CREATE TABLE "ContentReport" (
  "id" TEXT NOT NULL PRIMARY KEY,
  "reporterId" TEXT,
  "contentType" TEXT NOT NULL, -- 'prayer', 'chat'
  "contentId" TEXT NOT NULL,
  "reason" TEXT NOT NULL,
  "description" TEXT,
  "status" TEXT DEFAULT 'pending', -- pending, resolved, dismissed
  "resolvedBy" TEXT,
  "resolvedAt" TIMESTAMP,
  "createdAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY ("reporterId") REFERENCES "User"("id"),
  FOREIGN KEY ("resolvedBy") REFERENCES "User"("id")
);
```

**New Pages:**
- `/app/admin/moderation/page.tsx` - Moderation queue
- `/app/admin/moderation/prayers/page.tsx` - Prayer moderation

**API Routes:**
- `GET /api/admin/moderation/prayers` - Get prayers pending moderation
- `PUT /api/admin/moderation/prayers/[id]` - Approve/reject prayer
- `GET /api/admin/moderation/reports` - Get content reports

### Phase 3: Analytics & Monitoring (Week 3)

#### 3.1 Analytics Dashboard
**New Pages:**
- `/app/admin/analytics/page.tsx` - Analytics overview
- `/app/admin/analytics/users/page.tsx` - User analytics
- `/app/admin/analytics/engagement/page.tsx` - Engagement metrics

**API Routes:**
- `GET /api/admin/analytics/users` - User growth, retention metrics
- `GET /api/admin/analytics/conversations` - Chat analytics
- `GET /api/admin/analytics/prayers` - Prayer wall analytics
- `GET /api/admin/analytics/bible-usage` - Bible reading stats

**Components:**
- `/components/admin/analytics/growth-chart.tsx` (using MUI X Charts)
- `/components/admin/analytics/engagement-metrics.tsx`
- `/components/admin/analytics/user-segments.tsx`

#### 3.2 AI Chat Monitoring
**Database Schema Addition:**
```sql
-- Add monitoring fields to ChatConversation
ALTER TABLE "ChatConversation" ADD COLUMN "tokensUsed" INTEGER DEFAULT 0;
ALTER TABLE "ChatConversation" ADD COLUMN "costEstimate" DECIMAL(10,4);
ALTER TABLE "ChatConversation" ADD COLUMN "flagged" BOOLEAN DEFAULT FALSE;
ALTER TABLE "ChatConversation" ADD COLUMN "flagReason" TEXT;

-- Create AI usage tracking
CREATE TABLE "AIUsageLog" (
  "id" TEXT NOT NULL PRIMARY KEY,
  "conversationId" TEXT,
  "model" TEXT NOT NULL,
  "inputTokens" INTEGER NOT NULL,
  "outputTokens" INTEGER NOT NULL,
  "cost" DECIMAL(10,4) NOT NULL,
  "responseTime" INTEGER, -- milliseconds
  "createdAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY ("conversationId") REFERENCES "ChatConversation"("id")
);
```

**New Pages:**
- `/app/admin/chat/page.tsx` - Chat monitoring overview
- `/app/admin/chat/conversations/page.tsx` - Live conversation feed
- `/app/admin/chat/costs/page.tsx` - Cost tracking

**API Routes:**
- `GET /api/admin/chat/overview` - Chat usage metrics
- `GET /api/admin/chat/conversations` - Recent conversations
- `GET /api/admin/chat/costs` - Cost analysis
- `PUT /api/admin/chat/conversations/[id]/flag` - Flag conversation

### Phase 4: System Administration (Week 4)

#### 4.1 System Settings & Configuration
**New Pages:**
- `/app/admin/settings/page.tsx` - App settings
- `/app/admin/settings/features/page.tsx` - Feature toggles
- `/app/admin/settings/admins/page.tsx` - Admin user management

**API Routes:**
- `GET /api/admin/settings` - Get all settings
- `PUT /api/admin/settings` - Update settings
- `GET /api/admin/system/health` - System health check
- `POST /api/admin/system/maintenance` - Toggle maintenance mode

**Settings Schema:**
```typescript
interface AppSettings {
  siteName: string;
  supportEmail: string;
  aiChatEnabled: boolean;
  prayerWallEnabled: boolean;
  userRegistrationOpen: boolean;
  dailyVerseEnabled: boolean;
  aiModel: 'gpt-4' | 'gpt-3.5-turbo';
  maxChatsPerUserPerDay: number;
  maintenanceMode: boolean;
}
```

#### 4.2 Communications
**Database Schema:**
```sql
CREATE TABLE "EmailTemplate" (
  "id" TEXT NOT NULL PRIMARY KEY,
  "key" TEXT NOT NULL UNIQUE,
  "subject" TEXT NOT NULL,
  "bodyHtml" TEXT NOT NULL,
  "bodyText" TEXT NOT NULL,
  "variables" TEXT[], -- Available template variables
  "updatedBy" TEXT NOT NULL,
  "updatedAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY ("updatedBy") REFERENCES "User"("id")
);

CREATE TABLE "EmailCampaign" (
  "id" TEXT NOT NULL PRIMARY KEY,
  "name" TEXT NOT NULL,
  "subject" TEXT NOT NULL,
  "bodyHtml" TEXT NOT NULL,
  "targetSegment" TEXT NOT NULL, -- 'all', 'active', 'dormant'
  "status" TEXT DEFAULT 'draft', -- draft, scheduled, sending, sent
  "scheduledAt" TIMESTAMP,
  "sentAt" TIMESTAMP,
  "recipientCount" INTEGER DEFAULT 0,
  "createdBy" TEXT NOT NULL,
  "createdAt" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY ("createdBy") REFERENCES "User"("id")
);
```

**New Pages:**
- `/app/admin/communications/page.tsx` - Email campaigns
- `/app/admin/communications/templates/page.tsx` - Email templates

## Technical Implementation Details

### Authentication Flow
1. **Admin Login**: Separate from user login, checks `role` field
2. **JWT Enhancement**: Include admin permissions in token
3. **Route Protection**: Middleware checks for admin role
4. **Audit Logging**: Log all admin actions automatically

### Database Migrations
```typescript
// prisma/migrations/add-admin-features.sql
-- Run the SQL statements from each phase above
```

### Middleware Enhancement
```typescript
// Update middleware.ts
const adminPaths = ['/admin'];
const isAdminPath = adminPaths.some(path =>
  request.nextUrl.pathname.startsWith(path)
);

if (isAdminPath) {
  // Check for admin authentication
  // Verify admin role and permissions
}
```

### API Response Standards
```typescript
// Standard admin API response format
interface AdminApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
  pagination?: {
    page: number;
    limit: number;
    total: number;
  };
}
```

### Real-time Features
- **WebSocket Integration**: Extend existing WebSocket for admin notifications
- **Auto-refresh**: Key metrics update every 30 seconds
- **Live Activity Feed**: Real-time user actions display

## Security Implementation

### Access Control
```typescript
// lib/admin-permissions.ts
export enum AdminPermission {
  VIEW_USERS = 'users:read',
  MANAGE_USERS = 'users:write',
  MODERATE_CONTENT = 'content:moderate',
  VIEW_ANALYTICS = 'analytics:read',
  MANAGE_SYSTEM = 'system:manage'
}

export function hasPermission(user: User, permission: AdminPermission): boolean {
  if (user.role === 'admin') return true; // Super admin
  return user.adminPermissions?.includes(permission) || false;
}
```

### Audit Logging
```typescript
// lib/admin-audit.ts
export async function logAdminAction(
  adminId: string,
  action: string,
  resource: string,
  resourceId?: string,
  details?: any,
  request?: Request
) {
  await prisma.adminAuditLog.create({
    data: {
      adminId,
      action,
      resource,
      resourceId,
      details,
      ipAddress: getClientIP(request),
      userAgent: request?.headers.get('user-agent')
    }
  });
}
```

## File Structure
```
app/
├── admin/
│   ├── layout.tsx
│   ├── page.tsx                    # Dashboard overview
│   ├── login/
│   │   └── page.tsx               # Admin login
│   ├── users/
│   │   ├── page.tsx               # User management
│   │   └── [id]/
│   │       └── page.tsx           # User details
│   ├── moderation/
│   │   ├── page.tsx               # Moderation queue
│   │   └── prayers/
│   │       └── page.tsx           # Prayer moderation
│   ├── analytics/
│   │   ├── page.tsx               # Analytics overview
│   │   ├── users/
│   │   │   └── page.tsx           # User analytics
│   │   └── engagement/
│   │       └── page.tsx           # Engagement metrics
│   ├── chat/
│   │   ├── page.tsx               # Chat monitoring
│   │   ├── conversations/
│   │   │   └── page.tsx           # Live conversations
│   │   └── costs/
│   │       └── page.tsx           # Cost tracking
│   ├── settings/
│   │   ├── page.tsx               # App settings
│   │   ├── features/
│   │   │   └── page.tsx           # Feature toggles
│   │   └── admins/
│   │       └── page.tsx           # Admin management
│   └── communications/
│       ├── page.tsx               # Email campaigns
│       └── templates/
│           └── page.tsx           # Email templates
├── api/
│   └── admin/
│       ├── auth/
│       ├── users/
│       ├── moderation/
│       ├── analytics/
│       ├── chat/
│       ├── settings/
│       └── communications/
components/
└── admin/
    ├── auth/
    ├── layout/
    ├── dashboard/
    ├── users/
    ├── moderation/
    ├── analytics/
    ├── chat/
    ├── settings/
    └── communications/
lib/
├── admin-auth.ts
├── admin-permissions.ts
├── admin-audit.ts
└── admin-utils.ts
```

## Next Steps

1. **Phase 1 Setup** (Week 1):
   - Create admin authentication system
   - Build basic dashboard layout
   - Implement overview metrics

2. **Progressive Enhancement** (Weeks 2-4):
   - Add user management features
   - Implement content moderation
   - Build analytics dashboard
   - Add system administration tools

3. **Testing & Security**:
   - Unit tests for admin functions
   - Security audit of admin routes
   - Performance testing with large datasets

4. **Documentation**:
   - Admin user guide
   - API documentation for admin endpoints
   - Deployment and maintenance procedures

## MUI Integration for Admin Dashboard

### Required MUI Packages
```bash
npm install @mui/material @emotion/react @emotion/styled
npm install @mui/x-data-grid @mui/x-charts @mui/x-date-pickers
npm install @mui/icons-material @mui/lab
npm install @fontsource/roboto # MUI default font
```

### Admin Theme Configuration
```typescript
// lib/admin-theme.ts
import { createTheme } from '@mui/material/styles';

export const adminTheme = createTheme({
  palette: {
    mode: 'light',
    primary: {
      main: '#1976d2', // Professional blue
      contrastText: '#ffffff'
    },
    secondary: {
      main: '#dc004e',
    },
    background: {
      default: '#f5f5f5',
      paper: '#ffffff'
    },
    grey: {
      100: '#f5f5f5',
      200: '#eeeeee',
      300: '#e0e0e0',
      400: '#bdbdbd',
      500: '#9e9e9e'
    }
  },
  typography: {
    fontFamily: ['Roboto', 'Arial', 'sans-serif'].join(','),
    h4: {
      fontWeight: 600,
      fontSize: '1.5rem'
    },
    h6: {
      fontWeight: 500,
      fontSize: '1.125rem'
    }
  },
  components: {
    MuiCard: {
      styleOverrides: {
        root: {
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
          borderRadius: 8
        }
      }
    },
    MuiDataGrid: {
      styleOverrides: {
        root: {
          border: 'none',
          '& .MuiDataGrid-cell': {
            borderBottom: '1px solid #f0f0f0'
          }
        }
      }
    }
  }
});
```

### Key MUI Components for Admin Features

#### Dashboard Overview
- **MUI Card** + **CardContent** for metrics cards
- **MUI Typography** for headings and stats
- **MUI Chip** for status indicators
- **MUI LinearProgress** for loading states

#### User Management
- **MUI Data Grid** with server-side pagination, sorting, filtering
- **MUI Avatar** for user profile pictures
- **MUI Chip** for user status (Active, Suspended, etc.)
- **MUI IconButton** for quick actions (View, Edit, Ban)
- **MUI Dialog** for user detail modals

#### Content Moderation
- **MUI List** + **ListItem** for moderation queue
- **MUI Accordion** for expandable prayer requests
- **MUI ButtonGroup** for Approve/Reject actions
- **MUI Badge** for pending counts

#### Analytics Dashboard
- **MUI X Charts (LineChart, BarChart, PieChart)** for visualizations
- **MUI DatePicker** for date range selection
- **MUI Select** for metric filtering
- **MUI Grid** for responsive chart layout

#### System Administration
- **MUI Switch** for feature toggles
- **MUI Slider** for numeric settings (rate limits)
- **MUI TextField** for configuration values
- **MUI Alert** for system status messages

### Admin Layout Components
```typescript
// components/admin/layout/admin-layout.tsx
import { ThemeProvider } from '@mui/material/styles';
import { CssBaseline, Box, Drawer, AppBar, Toolbar } from '@mui/material';
import { adminTheme } from '@/lib/admin-theme';

export function AdminLayout({ children }: { children: React.ReactNode }) {
  return (
    <ThemeProvider theme={adminTheme}>
      <CssBaseline />
      <Box sx={{ display: 'flex' }}>
        <AppBar position="fixed">
          <Toolbar>
            {/* Admin header */}
          </Toolbar>
        </AppBar>
        <Drawer variant="permanent">
          {/* Admin navigation */}
        </Drawer>
        <Box component="main" sx={{ flexGrow: 1, p: 3, mt: 8 }}>
          {children}
        </Box>
      </Box>
    </ThemeProvider>
  );
}
```

### Data Grid Configuration Example
```typescript
// components/admin/users/user-data-grid.tsx
import { DataGrid, GridColDef, GridActionsCellItem } from '@mui/x-data-grid';
import { Chip, Avatar } from '@mui/material';
import { Visibility, Block, Delete } from '@mui/icons-material';

const columns: GridColDef[] = [
  {
    field: 'avatar',
    headerName: '',
    width: 60,
    renderCell: (params) => <Avatar src={params.value} />,
    sortable: false,
    filterable: false
  },
  { field: 'email', headerName: 'Email', width: 250 },
  { field: 'name', headerName: 'Name', width: 200 },
  { field: 'createdAt', headerName: 'Joined', width: 120, type: 'date' },
  { field: 'lastLoginAt', headerName: 'Last Active', width: 120, type: 'dateTime' },
  {
    field: 'role',
    headerName: 'Status',
    width: 120,
    renderCell: (params) => (
      <Chip
        label={params.value}
        color={params.value === 'active' ? 'success' : 'default'}
        size="small"
      />
    )
  },
  {
    field: 'actions',
    type: 'actions',
    headerName: 'Actions',
    width: 120,
    getActions: (params) => [
      <GridActionsCellItem icon={<Visibility />} label="View" />,
      <GridActionsCellItem icon={<Block />} label="Suspend" />,
      <GridActionsCellItem icon={<Delete />} label="Delete" />
    ]
  }
];
```

### Chart Configuration Example
```typescript
// components/admin/analytics/user-growth-chart.tsx
import { LineChart } from '@mui/x-charts/LineChart';
import { Card, CardHeader, CardContent } from '@mui/material';

export function UserGrowthChart({ data }: { data: any[] }) {
  return (
    <Card>
      <CardHeader title="User Growth" />
      <CardContent>
        <LineChart
          width={600}
          height={300}
          series={[
            {
              data: data.map(d => d.users),
              label: 'Total Users',
              color: '#1976d2'
            }
          ]}
          xAxis={[
            {
              scaleType: 'point',
              data: data.map(d => d.date)
            }
          ]}
        />
      </CardContent>
    </Card>
  );
}
```

This implementation plan leverages the existing robust infrastructure while adding comprehensive admin capabilities using MUI components for a professional, consistent admin interface, ensuring minimal disruption to the current application.