# Help Desk System - Setup & Implementation Guide

## Overview
This is a custom in-house help desk system that replaces the Zendesk integration. It allows users to submit support tickets, track their status, and enables support staff to manage and respond to tickets through an admin interface.

**Current Status:** System is ready for deployment. Limited to test users (IDs 2 & 22) by default.

---

## Database Setup

### 1. Create Database Tables
Run the migration to create all required tables:

```bash
mysql -h <host> -u <user> -p <database> < curric/migrations/helpdesk_init.sql
```

Or via PhpMyAdmin/MySQL GUI, execute the SQL file.

**Tables Created:**
- `helpdesk_team` - Support staff members and their roles
- `helpdesk_tickets` - Support tickets from users
- `helpdesk_comments` - Comments/replies on tickets (public and internal)
- `helpdesk_attachments` - Files attached to tickets and comments

---

## Zendesk Import (Optional)

### 1. Set Zendesk API Token
Before importing, configure your Zendesk credentials. Add to your `.env` file:

```
ZENDESK_API_TOKEN=your_zendesk_token_here
```

Or edit `curric/class/HelpDeskImporter.class.php` line 15-21 to add credentials directly (not recommended for production).

### 2. Run Import Script
From the command line (not via browser):

```bash
php admin/import_zendesk.php
```

This will:
- Fetch all tickets from Zendesk
- Map requester emails to local user IDs (creating users if needed)
- Import comments and attachments
- Map ticket statuses and priorities

**Import Progress:**
- The script outputs progress in real-time
- Check the summary at the end for statistics
- Any errors are logged and displayed

---

## System Configuration

### 1. Add Support Team Members
Access the team management page:
- Navigate to: `admin/helpdesk_manage_team.php`
- Requires login as an admin-role user (see below for initial setup)

**Team Roles:**
- **Support Staff** (default) - Can view, reply to, and update ticket status
- **Team Lead** - Same as support + manage lower staff
- **Administrator** - Full access including team management

### 2. Initial Admin Setup
After creating tables, you need to manually add an initial admin:

```sql
-- Add yourself to the support team as admin
INSERT INTO helpdesk_team (user_id, display_name, email, role, is_active)
VALUES (1, 'Your Name', 'your@email.com', 'admin', 1);
```

Replace `user_id=1` with your actual user ID in the system.

---

## User-Facing Features

### Create New Ticket
**URL:** `/help_desk.php`

Features:
- Subject and description (required)
- Category selection (general, bug, feature_request, technical, account)
- Multiple file attachments (images, PDF, text, Word docs - max 5MB each)
- Auto-populated requester email
- Shows recent tickets preview

**Access Control:** Currently limited to user IDs 2 & 22 for testing

### View All Tickets
**URL:** `/view_all_help_desk_tickets.php`

Features:
- List all user's tickets with status badges
- Pagination (15 tickets per page)
- Click any ticket to view full details in modal
- View full description, all comments, and attachments
- See status, priority, and assignment information
- Comments show author, timestamp, and internal flag

---

## Admin Interface

### Ticket Management Dashboard
**URL:** `/admin/helpdesk_admin.php`

Features:
- **Statistics Cards:** Open tickets, pending, resolved this month, total
- **Filters:** Status, Priority, Assignee, Search by subject/description
- **Inline Editing:**
  - Change ticket status via dropdown
  - Assign to team member via dropdown
- **Ticket Detail Modal:** View full ticket and comments
- **Pagination:** 20 tickets per page

### Team Management
**URL:** `/admin/helpdesk_manage_team.php`

Features:
- Add team members from existing users
- Edit member roles, email, display name
- Deactivate members (unassigns their tickets)
- Remove members from team
- Role management (Support Staff, Team Lead, Admin)

---

## API Endpoints

All endpoints require authentication (session-based via `header.php`).

### Get Ticket Detail
**Endpoint:** `GET /ajax/ajax_helpdesk_get_detail.php?id=<ticket_id>`

**Response:**
```json
{
  "success": true,
  "ticket": {
    "id": 1,
    "subject": "Can't login",
    "description": "...",
    "status": "open",
    "priority": "high",
    "category": "technical",
    "created_at": "2026-04-01 10:30:00",
    "comments": [...],
    "attachments": [...]
  }
}
```

### List Tickets
**Endpoint:** `POST /ajax/ajax_helpdesk_get_tickets.php`

**Query Parameters:**
- `status` - Filter by status (open, pending, resolved, closed)
- `priority` - Filter by priority (low, normal, high, urgent)
- `assignee_id` - Filter by assigned team member
- `search` - Search in subject/description
- `sort_by` - Order by (created_at, updated_at, priority, status)
- `sort_dir` - ASC or DESC
- `page` - Pagination page number
- `per_page` - Tickets per page (default: 20, max: 100)

### Update Ticket
**Endpoint:** `POST /ajax/ajax_helpdesk_update_ticket.php`

**Parameters:**
- `ticket_id` (required)
- `status` - One of: open, pending, resolved, closed
- `priority` - One of: low, normal, high, urgent
- `assignee_id` - Team member ID or empty to unassign

**Requires:** Team member status

### Add Comment
**Endpoint:** `POST /ajax/ajax_helpdesk_add_comment.php`

**Parameters:**
- `ticket_id` (required)
- `comment` (required) - Comment text (max 10000 chars)
- `is_internal` - 1 for internal-only comments (team members only)

---

## File Structure

```
hero-aws/
├── help_desk.php                           # User: Create new ticket
├── view_all_help_desk_tickets.php          # User: View all tickets with detail modal
├── admin/
│   ├── helpdesk_admin.php                  # Admin: Dashboard & ticket management
│   ├── helpdesk_manage_team.php            # Admin: Team member management
│   └── import_zendesk.php                  # CLI: Import tickets from Zendesk
├── ajax/
│   ├── ajax_helpdesk_get_detail.php        # Get single ticket + comments
│   ├── ajax_helpdesk_get_tickets.php       # List tickets with filtering
│   ├── ajax_helpdesk_update_ticket.php     # Update status/priority/assignee
│   └── ajax_helpdesk_add_comment.php       # Add comment to ticket
├── curric/
│   ├── class/
│   │   ├── HelpDeskTicket.class.php        # Entity: Ticket operations
│   │   ├── HelpDeskRepository.class.php    # Data access layer
│   │   └── HelpDeskImporter.class.php      # Zendesk importer
│   └── migrations/
│       └── helpdesk_init.sql               # Database schema
└── uploads/
    └── helpdesk/                           # Attachment storage (auto-created)
```

---

## Extending the System

### Add New Categories
Edit the category dropdown in `help_desk.php` and update any category-related filters.

### Add Custom Fields
1. Add columns to `helpdesk_tickets` table
2. Update `HelpDeskTicket.class.php` properties
3. Update form fields in `help_desk.php`
4. Update modal display in `view_all_help_desk_tickets.php`

### Change File Upload Rules
Modify in `help_desk.php` lines 65-73:
```php
$allowed_types = array('image/jpeg', 'image/png', ...); // Add MIME types
$max_file_size = 5 * 1024 * 1024; // Change size limit
```

### Customize Email Notifications
Currently, no emails are sent. To add:
1. Create a notification class in `curric/class/`
2. Trigger after `$ticket->addComment()` calls
3. Use existing mail functionality from the codebase

---

## Security Considerations

✓ **Implemented:**
- Prepared statements via `DB.class.php` (prevents SQL injection)
- Session-based authentication via `DriveUser`
- Role-based access control (team member vs. regular user)
- File upload validation (MIME type, size, filename sanitization)
- Internal comments only visible to team members
- XSS prevention via `htmlspecialchars()` in output

⚠️ **To Consider:**
- Rate limiting on ticket creation (prevent spam)
- Audit logging of admin changes
- Encryption for sensitive attachment data
- CSRF protection on POST forms
- Email verification for new users
- Two-factor authentication for admin accounts

---

## Troubleshooting

### "Feature limited to test users"
Your user ID is not in the allowed list (2, 22). To enable for more users, edit:
- `help_desk.php` line 14-15
- `view_all_help_desk_tickets.php` line 15-16

Change:
```php
$allowed_users = array(2, 22); // Add your user ID here
```

### Import fails with "Could not find/create requester"
Zendesk user has an email that doesn't match any local user AND new user creation failed. Check:
- Database write permissions
- User email is valid
- No duplicate email exists

### Attachments not saving
Check:
- `uploads/helpdesk/` directory exists and is writable
- MIME type is in `$allowed_types`
- File size is under the limit
- Server disk space available

### Admin panel shows "Access Denied"
You must:
1. Be a registered user in the system
2. Have an entry in `helpdesk_team` table with `is_active=1`
3. Have role of 'admin' to access team management

---

## Next Steps

1. **Run migration:** Execute `helpdesk_init.sql`
2. **Create admin user:** INSERT statement above
3. **Import Zendesk data (optional):** Run import script
4. **Add team members:** Via admin panel
5. **Enable for production:** Remove/update user ID restrictions
6. **Replace old pages:** Update navigation to point to `/help_desk.php` instead of old Zendesk links
7. **Monitor:** Check ticket queue regularly

---

## Support & Maintenance

- **Backup:** Regular database backups recommended
- **Performance:** Add indexes if searches slow down (see migration file for current indexes)
- **Scaling:** For >1000 tickets, consider archiving old resolved tickets
- **Updates:** Check code for security patches regularly

---

**System Created:** April 2026
**MySQL Version:** 5.7+
**PHP Version:** 7.6+
**Dependencies:** None (uses built-in DB.class.php and Entity classes)
