# Trainer Role & Ticket System Plan

## Overview
Add a trainer role with login capability and a ticket/chat system between students and trainers. Super admins can view all conversations.

## Requirements

### 1. Trainer Role & Authentication
- Users can be assigned "trainer" role
- Trainers can login with their user account
- Trainers are linked to Trainer profiles
- Admin can assign trainer role to any user

### 2. Course Page Actions
On course detail page (e.g., `/courses/kwrs-ardwynw-llmbtdyyn`):
- **Button 1: "Help"** - Opens ticket for course-related help
- **Button 2: "Request to Apply"** - Opens ticket for application/mentoring
- Both buttons create tickets linked to the course trainer
- Send notifications to trainer
- Redirect to ticket chat page

### 3. Ticket/Chat System
- Tickets are linked to: course, student (user), and trainer
- Real-time messaging between student and trainer
- Status tracking: open, in_progress, resolved, closed
- Super admin can view ALL tickets and conversations

### 4. Notifications
- When student creates ticket → notify trainer
- When trainer replies → notify student
- In-app notifications using existing Notification model

---

## Database Models

### 1. User Model Extension
**File:** `app/models/user.py`

Add field:
```python
role = db.Column(db.String(20), default="student")  # student, trainer, admin
```

### 2. Trainer Model Extension
**File:** `app/models/course.py`

Add field to link Trainer to User:
```python
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
```

### 3. New Models
**File:** `app/models/ticket.py`

#### TrainerTicket
```python
class TrainerTicket(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    course_id = db.Column(db.Integer, db.ForeignKey("courses.id"))
    student_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    trainer_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    ticket_type = db.Column(db.String(50))  # "help" or "apply"
    subject = db.Column(db.String(255))
    status = db.Column(db.String(20), default="open")  # open, in_progress, resolved, closed
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
```

#### TrainerTicketMessage
```python
class TrainerTicketMessage(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ticket_id = db.Column(db.Integer, db.ForeignKey("trainer_tickets.id"))
    sender_id = db.Column(db.Integer, db.ForeignKey("users.id"))
    message = db.Column(db.Text, nullable=False)
    is_read = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
```

---

## Implementation Phases

### Phase 1: Database & Models
1. Add `role` field to User model
2. Add `user_id` to Trainer model
3. Create `TrainerTicket` model
4. Create `TrainerTicketMessage` model
5. Create migration

### Phase 2: Admin Routes
1. Add trainer role assignment in admin user management
2. Link trainers to users in admin trainer management
3. Add admin tickets dashboard (view all tickets)
4. Routes:
   - `/admin/tickets` - All tickets list
   - `/admin/tickets/<id>` - View ticket conversation
   - `/admin/users/<id>/set-role` - Set user role

### Phase 3: Ticket System Routes
**File:** `app/routes/tickets.py` (new blueprint)

Routes:
- `/tickets/new/<course_id>/<type>` - Create new ticket (help/apply)
- `/tickets/<id>` - View ticket & chat
- `/tickets/<id>/message` - Send message (POST)
- `/tickets` - My tickets (for students/trainers)
- `/api/tickets/<id>/messages` - Poll for new messages

### Phase 4: Course Page Updates
**File:** `app/templates/courses/detail.html`

Add after trainer info in sidebar:
```html
<!-- Trainer Actions -->
<div class="pt-4 border-t border-white/10 space-y-2">
    <button onclick="openTicket('help')" class="w-full bg-blue-500/20 text-blue-400 px-4 py-2 rounded-lg text-sm hover:bg-blue-500/30 transition">
        <span>💬</span> طلب مساعدة
    </button>
    <button onclick="openTicket('apply')" class="w-full bg-emerald-500/20 text-emerald-400 px-4 py-2 rounded-lg text-sm hover:bg-emerald-500/30 transition">
        <span>📝</span> التقديم للمدرب
    </button>
</div>
```

### Phase 5: Templates
1. `tickets/my_tickets.html` - User's ticket list
2. `tickets/detail.html` - Ticket chat interface
3. `admin/tickets.html` - Admin all tickets list
4. `admin/ticket_detail.html` - Admin ticket view

### Phase 6: Notifications
Integrate with existing Notification model:
- Create helper function `send_ticket_notification()`
- Notify trainer on new ticket
- Notify student on trainer reply
- Notify admin on all new tickets

### Phase 7: Super Admin Access
- Admin can view any ticket
- Admin can reply to any ticket
- Add "View as Admin" indicator when admin views ticket
- Filter tickets by status, trainer, course

---

## Database Schema Changes

### SQL Migration
```sql
-- Add role to users
ALTER TABLE users ADD COLUMN role VARCHAR(20) DEFAULT 'student';
UPDATE users SET role = 'admin' WHERE is_admin = true;

-- Add user_id to trainers
ALTER TABLE trainers ADD COLUMN user_id INTEGER REFERENCES users(id);

-- Create trainer_tickets table
CREATE TABLE trainer_tickets (
    id SERIAL PRIMARY KEY,
    course_id INTEGER REFERENCES courses(id),
    student_id INTEGER REFERENCES users(id),
    trainer_id INTEGER REFERENCES users(id),
    ticket_type VARCHAR(50), -- 'help' or 'apply'
    subject VARCHAR(255),
    status VARCHAR(20) DEFAULT 'open',
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- Create trainer_ticket_messages table
CREATE TABLE trainer_ticket_messages (
    id SERIAL PRIMARY KEY,
    ticket_id INTEGER REFERENCES trainer_tickets(id) ON DELETE CASCADE,
    sender_id INTEGER REFERENCES users(id),
    message TEXT NOT NULL,
    is_read BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT NOW()
);
```

---

## File Structure

```
app/
├── models/
│   ├── user.py          # Add role field
│   ├── course.py        # Add user_id to Trainer
│   └── ticket.py        # New: TrainerTicket, TrainerTicketMessage
├── routes/
│   ├── tickets.py       # New blueprint for tickets
│   └── admin.py         # Add ticket management routes
├── templates/
│   ├── courses/
│   │   └── detail.html  # Add help/apply buttons
│   ├── tickets/
│   │   ├── my_tickets.html
│   │   └── detail.html  # Chat interface
│   └── admin/
│       ├── tickets.html
│       └── ticket_detail.html
└── helpers/
    └── notification.py  # Ticket notification helper
```

---

## API Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | `/tickets/new/<course_id>/<type>` | Create new ticket |
| GET | `/tickets` | My tickets (filtered by role) |
| GET | `/tickets/<id>` | View ticket & messages |
| POST | `/tickets/<id>/message` | Send message |
| GET | `/api/tickets/<id>/messages` | Poll new messages (AJAX) |
| GET | `/admin/tickets` | All tickets (admin only) |
| GET | `/admin/tickets/<id>` | View any ticket (admin) |
| POST | `/admin/tickets/<id>/close` | Close ticket (admin) |
| POST | `/admin/users/<id>/role` | Set user role (admin) |

---

## Security Considerations

1. **Permission Checks**
   - `@login_required` on all ticket routes
   - Students only see their own tickets
   - Trainers only see tickets assigned to them
   - Admins see all tickets

2. **CSRF Protection**
   - All POST forms require CSRF token

3. **Input Sanitization**
   - Sanitize all user messages
   - Prevent XSS in chat interface

---

## UX Flow

### Student Flow:
1. Student views course page
2. Clicks "Help" or "Request to Apply"
3. Modal opens to enter subject/message
4. Submit creates ticket
5. Redirect to ticket chat page
6. Receives notification when trainer replies

### Trainer Flow:
1. Receives notification of new ticket
2. Clicks notification → ticket chat
3. Reads student message
4. Replies with message
5. Can close ticket when resolved

### Admin Flow:
1. Accesses `/admin/tickets`
2. Sees all tickets across platform
3. Can click any ticket to view/reply
4. Can assign tickets or close them
