# Connecticut Elderly Services PCA Certification Training Platform

## Quick Start

```bash
# 1. Install dependencies
npm install

# 2. Copy configuration
cp .env.example .env

# 3. Start the application
npm start

# 4. Open browser
# http://localhost:3000
```

## About This Application

This is a Node.js + Express web application (v0.1) for administering the Connecticut Elderly Services PCA (Personal Care Attendant) certification training program. It runs on cPanel with Phusion Passenger. Admin auth uses MySQL; learner data uses SQLite.

### Key Features

- **12 Full Training Modules** - Complete lesson content with knowledge check quizzes
- **19-Section Final Exam** - Comprehensive certification test
- **PDF Certificates** - Automatically generated upon passing
- **Admin Dashboard** - Manage learners, track completion, view statistics
- **Professional Design** - Modern, responsive, mobile-friendly interface
- **Secure Scoring** - Server-side exam evaluation
- **Dual Database** - SQLite for learner data; MySQL for admin authentication

## For Learners

### Starting Training
1. Go to http://localhost:3000
2. Click "Begin Training"
3. Enter your name and select your agency
4. Start Module 1

### Training Modules
- Each module has a lesson to read
- Complete the 5-question quiz
- Must score 70% or higher to pass
- Complete all 12 modules to unlock the final exam

### Final Exam
- 19 sections covering all PCA competencies
- 100+ true/false questions
- Must score 70%+ in EVERY section
- Scores by section shown after exam
- Certificate generated immediately upon passing

### Certificate
- Download as PDF
- Official Connecticut Elderly Services certificate
- Includes certificate ID and completion date
- Ready to share with employers

## For Administrators

### Accessing Admin Panel
- URL: `/admin/login` — login requires a **username** and **password**
- **No terminal?** Set `ADMIN_SETUP_TOKEN` in your environment, then visit `/admin/bootstrap?token=YOUR_TOKEN` to create the first admin account through the browser. Remove the token afterward.
- **Have terminal access?** Run `node scripts/create-admin.js <username> <password>`

### Admin Dashboard Shows
- **Statistics**: Total learners, completions, pass rate
- **Learner Roster**: Full table with names, agencies, dates, status
- **Certificate Links**: Download links for completed learners
- **Agency Management**: View and add new agency codes

## Configuration

Edit `.env` file:

```
PORT=3000
SESSION_SECRET=your-secret-key-change-this     # required

# For browser-based first-admin setup (no terminal needed)
ADMIN_SETUP_TOKEN=your-strong-random-token     # remove after setup

# Optional email configuration
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your-email@gmail.com
EMAIL_PASS=your-app-password
```

Admin credentials live in the **MySQL database** (not SQLite, not `.env`). Create your first admin via the browser at `/admin/bootstrap?token=YOUR_TOKEN`, or via terminal:
```bash
node scripts/create-admin.js tony YourPassword
```

## Pre-Configured Agencies

- **DEMO123** - Demo Agency (test learners)
- **TEST456** - Test Agency

Add more through the admin dashboard.

## Training Content Overview

### 12 Modules
1. Emergency Response
2. Universal Precautions
3. Communication
4. Monitoring Condition Changes
5. Positioning
6. Safe Lifting
7. Safe Transfers
8. Medication Safety
9. Professional Boundaries
10. Brain Injury, Dementia & Behavior
11. Reporting Abuse & Neglect
12. Personal Care Skills

### 19 Exam Sections
All sections from the Connecticut DSS PCA Certification Test, including:
- Preventing Emergency Situations
- Universal Precautions
- Communication
- Monitoring Condition Changes
- Positioning
- Lifting & Transfers
- Medication Safety
- Caregiver Boundaries
- Acquired Brain Injury
- Reporting Abuse & Neglect
- Personal Care (bathing, hair, mouth care, dressing)

## File Structure

```
ces-training/
├── app.js                 # Main application
├── package.json           # Dependencies
├── .env.example          # Configuration template
│
├── data/                 # Database (auto-created)
├── public/               # Static files (CSS, JS)
├── lib/                  # Business logic
├── routes/               # API routes
└── views/                # HTML templates (EJS)
```

## Troubleshooting

### Port Already in Use
```bash
# Change PORT in .env to another port (e.g., 3001, 8000)
PORT=3001
npm start
```

### Database Issues
```bash
# Remove database and let it auto-recreate
rm data/training.db
npm start
```

### Dependencies Won't Install
```bash
# Clear npm cache and try again
npm cache clean --force
npm install
```

### Can't Access Admin Panel
- Make sure you've run `node scripts/create-admin.js <username> <password>` at least once
- Usernames are stored lowercase — check your input
- Check the Node.js console / cPanel error log for details

## Customization

### Change Logo/Organization Name
- Edit `views/layout.ejs` (header)
- Edit `lib/certificate.js` (certificate text)

### Change Colors
- Edit `public/css/style.css` starting at `:root` section
- Primary: #1a3a5c (navy)
- Secondary: #f0a500 (gold)

### Add New Modules
- Add to `lib/modules.js`
- Update module count in code
- Test with knowledge check quizzes

### Reset Admin Password
- Run: `node scripts/create-admin.js <username> <newpassword>`
- Or use the "Change Password" form in the admin dashboard Settings tab

## Security Notes

⚠️ **BEFORE PRODUCTION DEPLOYMENT:**

1. **Create your admin account** using the bootstrap script:
   ```bash
   node scripts/create-admin.js tony YourStrongPassword
   ```

2. **Set SESSION_SECRET** in `.env` (the app will refuse to start in production without it):
   ```
   SESSION_SECRET=your-unique-random-string
   ```

3. **Configure Email** (optional)
   - Set EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASS

4. **Enable HTTPS**
   - Use reverse proxy (nginx) or application-level SSL

5. **Backup Database**
   - Regularly backup `data/training.db`
   - Contains all learner records

## Database

**SQLite3** (`data/training.db`) — created automatically, stores learner data:
- **agencies** table - Organization codes
- **learners** table - Learner records
- **module_progress** table - Completion tracking

**MySQL/MariaDB** (cPanel) — stores admin credentials only:
- **admin_users** table - Admin accounts with scrypt-hashed passwords
- Configure via cPanel environment variables (DB_HOST, DB_USER, DB_PASS, DB_NAME)
- **You must create this table once in phpMyAdmin before first use:**

```sql
CREATE TABLE IF NOT EXISTS admin_users (
  id            INT          AUTO_INCREMENT PRIMARY KEY,
  username      VARCHAR(100) NOT NULL UNIQUE,
  display_name  VARCHAR(255) NOT NULL DEFAULT '',
  password_hash VARCHAR(255) NOT NULL,
  role          VARCHAR(50)  NOT NULL DEFAULT 'agency',
  active        TINYINT(1)   NOT NULL DEFAULT 1,
  last_login    DATETIME     NULL,
  created_at    DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP
);
```

- **Inspect existing admin accounts** (phpMyAdmin → SQL tab):
```sql
SELECT id, username, display_name, role, active, last_login, created_at
FROM admin_users ORDER BY created_at;
```

- **Delete the legacy "admin" account if it exists** (phpMyAdmin → SQL tab):
```sql
DELETE FROM admin_users WHERE username = 'admin';
```

## Deployment Options

### cPanel
1. Upload and extract the zip so files land at `public_html/ces-training/`
2. In **cPanel → Node.js App → Environment Variables** set: `NODE_ENV=production`, `SESSION_SECRET`, `ADMIN_SETUP_TOKEN`, `DB_HOST`, `DB_USER`, `DB_PASS`, `DB_NAME`, `DB_PORT=3306`
3. Set startup file to `app.js`, run NPM Install, then Restart
4. Visit `/admin/bootstrap?token=YOUR_TOKEN` to create the first admin account
5. Remove `ADMIN_SETUP_TOKEN` from env vars and restart after setup

### Docker
```dockerfile
FROM node:18
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD ["npm", "start"]
```

### Heroku
```bash
git push heroku main
heroku config:set SESSION_SECRET=your-secret
heroku run node scripts/create-admin.js tony YourPassword
```

### Cloud Providers
Works with AWS, DigitalOcean, Azure, Google Cloud, etc.

## Support & Documentation

- **SETUP.md** - Detailed setup guide
- **PROJECT_SUMMARY.md** - Complete technical overview
- **app.js** - Main application file
- Source code well-commented

## Browser Compatibility

- Chrome/Edge 90+
- Firefox 88+
- Safari 14+
- Mobile browsers supported

## System Requirements

- Node.js 14.0 or higher
- 50 MB disk space
- SQLite for learner data (auto-created); MySQL/MariaDB for admin auth (cPanel)

## License

Connecticut Elderly Services PCA Training Platform
© 2024 Connecticut Department of Social Services

---

## Next Steps

1. Run `npm install` to install dependencies
2. Copy `.env.example` to `.env` and configure
3. Run `npm start` to start the application
4. Visit http://localhost:3000 in your browser
5. Test with agency code DEMO123 or TEST456

For detailed instructions, see **SETUP.md**
