# AHA Training - NDA-Gated Website

## 🎯 Project Overview

This is a comprehensive, NDA-gated website for **AHA ACLS, BLS, and PALS training** exclusively for advanced healthcare providers (CRNAs, physicians, nurse anesthesiologists, and critical care specialists).

### Key Features

- ✅ **Public Website** - Clean, professional pages for courses, about, schedule
- 🔐 **Mandatory NDA System** - Legally binding digital signatures required before contact
- 📝 **Signature Capture** - Both typed and hand-drawn digital signatures
- 📄 **PDF Generation** - Corporate-grade PDF documents with watermarks
- 🗄️ **SQLite Database** - Secure storage of NDA records and messages
- 🔒 **Advanced Security** - CSRF protection, rate limiting, browser fingerprinting
- 📧 **Email Notifications** - Admin alerts for NDA signatures and contact messages
- 🚫 **Session-Based Access** - Contact form only accessible after NDA signing
- 🛡️ **Security Rules** - .htaccess protection for private directories

---

## 🖥️ Server Configuration

### Live Site Location
- **URL**: https://adampowell.pro/aha/
- **Git Repository**: `/var/www/aha-training/`
- **Web Root**: `/var/www/adampowell.pro/html/`
- **Symlink**: `/var/www/adampowell.pro/html/aha -> /var/www/aha-training/public`
- **Live Files**: `/var/www/aha-training/` (this is where you should make changes)

### Important Notes
- The live site is served from `/var/www/aha-training/public/` via a symlink
- Changes should be made to files in `/var/www/aha-training/`
- The header file used by the live site is: `/var/www/aha-training/app/includes/header.php`
- Nginx proxies to PHP-FPM 7.3 on the backend

---

## 📁 Directory Structure

```
/aha training/
├── public/                      # Public-facing pages
│   ├── index.php               # Home page
│   ├── about.php               # About page
│   ├── courses.php             # Course information
│   ├── schedule.php            # Schedule information
│   ├── privacy.php             # Privacy policy
│   ├── nda.php                 # NDA signature page
│   └── contact.php             # Contact form (NDA-gated)
│
├── app/                        # Backend logic
│   ├── includes/               # Shared components
│   │   ├── header.php         # Header with navigation
│   │   └── footer.php         # Footer
│   ├── database.php           # Database handler
│   ├── pdf-generator.php      # PDF generation class
│   ├── security.php           # Security utilities
│   ├── email-notifier.php     # Email notification system
│   ├── process-nda.php        # NDA form processor
│   ├── process-contact.php    # Contact form processor
│   └── .htaccess              # Backend security rules
│
├── assets/                     # Frontend assets
│   ├── css/
│   │   └── style.css          # Main stylesheet
│   └── js/
│       └── signature.js       # Signature capture functionality
│
├── private/                    # Restricted access
│   ├── nda_records/           # PDF storage
│   ├── aha_training.db        # SQLite database
│   ├── security.log           # Security event log
│   └── .htaccess              # Deny all access
│
├── security/                   # Security configurations
├── .htaccess                  # Main security rules
└── README.md                  # This file
```

---

## 🚀 Installation & Setup

### Prerequisites

- **PHP 8.0+** with SQLite3 extension enabled
- **Apache 2.4+** with mod_rewrite enabled
- **SSL Certificate** (Let's Encrypt recommended)
- **Email configured** on server (or SMTP service)

### Step 1: Upload Files

Upload the entire `/aha training/` directory to your web server:

```bash
# Via SCP (from local Windows)
scp -r "c:\ADAMANT\ADAMPOWELL PRO\adampowell.pro\aha training" root@198.211.114.12:/var/www/

# Or via FTP/SFTP client
```

### Step 2: Set Permissions

```bash
# Navigate to LIVE SITE directory
cd /var/www/aha-training/

# Set directory permissions
chmod 755 public/ app/ assets/
chmod 700 private/
chmod 755 private/nda_records/

# Set file permissions
find public/ -type f -exec chmod 644 {} \;
find app/ -type f -exec chmod 644 {} \;
find assets/ -type f -exec chmod 644 {} \;

# Make processing scripts executable
chmod 755 app/process-nda.php app/process-contact.php

# Secure .htaccess files
chmod 644 .htaccess app/.htaccess private/.htaccess
```

### Step 3: Initialize Database

The database will be created automatically on first use. To pre-create it:

```bash
# Create database file
touch private/aha_training.db
chmod 666 private/aha_training.db

# Create log files
touch private/security.log
chmod 666 private/security.log
```

### Step 4: Configure Email

Edit `app/email-notifier.php` and set your admin email:

```php
$this->adminEmail = 't3h28@gmail.com'; // Your email
```

### Step 5: Configure Web Server

**For Apache** (already configured via .htaccess files):
- Ensure `AllowOverride All` is set in your Apache config
- Restart Apache: `systemctl restart apache2`

**For Nginx** (create config file):

```nginx
server {
    listen 443 ssl;
    server_name aha.adampowell.pro;

    root /var/www/aha training/public;
    index index.php;

    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/aha.adampowell.pro/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/aha.adampowell.pro/privkey.pem;

    # Block access to private directory
    location /private {
        deny all;
        return 403;
    }

    # Block access to app backend files
    location /app {
        deny all;
        location ~ ^/app/(process-nda|process-contact)\.php$ {
            allow all;
            fastcgi_pass unix:/run/php/php8.0-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }

    # PHP handling
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # Static files
    location /assets {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}
```

### Step 6: SSL Certificate

```bash
# Install Certbot
apt install certbot python3-certbot-apache

# Get certificate
certbot certonly --apache -d aha.adampowell.pro

# Or with Nginx
certbot certonly --nginx -d aha.adampowell.pro
```

### Step 7: Test the System

1. Visit: `https://aha.adampowell.pro/public/index.php`
2. Navigate through public pages
3. Click "Contact (NDA Required)"
4. Sign NDA (test both typed and drawn signatures)
5. Verify email notification received
6. Access contact form
7. Submit test message
8. Check database: `sqlite3 private/aha_training.db "SELECT * FROM nda_records;"`

---

## 🔒 Security Features

### Access Control

- **Private Directory**: `/private/` is completely blocked from web access
- **App Directory**: Only processing scripts (`process-*.php`) are accessible
- **Database**: SQLite file is not web-accessible
- **Session-Based**: Contact form requires valid NDA session

### CSRF Protection

- All forms include CSRF tokens
- Tokens validated on submission
- New tokens generated after use

### Rate Limiting

- **NDA Submissions**: 3 per hour per IP
- **Contact Messages**: 5 per hour per IP
- Configurable in `database.php`

### Browser Fingerprinting

- Captures device/browser information
- Used for session validation
- Stored with NDA records

### Input Sanitization

- All user inputs sanitized
- HTML tags stripped
- Special characters escaped
- SQL injection prevented

### IP Tracking & Geolocation

- IP address logged for all actions
- Geolocation via ip-api.com
- Cloudflare support for real IPs

---

## 📧 Email Configuration

### Default Setup (PHP mail())

The system uses PHP's built-in `mail()` function. Ensure your server has mail configured:

```bash
# Test email
echo "Test email" | mail -s "Test" your@email.com
```

### Recommended: Use SMTP (Production)

For production, consider using PHPMailer with SMTP:

```bash
# Install PHPMailer
cd /var/www/aha-training/
composer require phpmailer/phpmailer
```

Then modify `app/email-notifier.php` to use PHPMailer/SMTP.

---

## 🗄️ Database Schema

### Tables

**nda_records**
- `id` - Auto-increment primary key
- `name` - Signer's full name
- `email` - Signer's email
- `signature_type` - 'typed' or 'drawn'
- `signature_data` - Signature content or image path
- `ip_address` - IP at time of signing
- `location` - Geolocation (City, State, Country)
- `browser_fingerprint` - Device fingerprint hash
- `user_agent` - Browser user agent string
- `pdf_path` - Path to generated PDF
- `nda_hash` - Unique SHA256 hash
- `signed_at` - Timestamp of signature
- `created_at` - Record creation time

**contact_messages**
- `id` - Auto-increment primary key
- `name` - Sender's name
- `email` - Sender's email
- `message` - Message content
- `ip_address` - Sender's IP
- `nda_hash` - Reference to NDA record
- `read_status` - 0 = unread, 1 = read
- `created_at` - Message timestamp

**rate_limits**
- `id` - Auto-increment primary key
- `ip_address` - Client IP
- `action_type` - Type of action (nda_submission, contact_submission)
- `attempt_count` - Number of attempts
- `last_attempt` - Timestamp of last attempt
- `blocked_until` - Block expiration time

### Database Queries

```bash
# Access database
sqlite3 /var/www/aha-training/private/aha_training.db

# View all NDAs
SELECT name, email, signed_at, location FROM nda_records ORDER BY signed_at DESC;

# View unread messages
SELECT * FROM contact_messages WHERE read_status = 0 ORDER BY created_at DESC;

# Check rate limits
SELECT * FROM rate_limits WHERE datetime(blocked_until) > datetime('now');

# Count total NDAs
SELECT COUNT(*) FROM nda_records;
```

---

## 📄 PDF Generation

### Current System (HTML Fallback)

By default, the system generates HTML files that should be converted to PDF. These are stored in `/private/nda_records/` with a `.convert` marker file.

### Install TCPDF (Recommended)

For production-grade PDF generation:

```bash
cd /var/www/aha-training/
composer require tecnickcom/tcpdf
```

The system will automatically detect and use TCPDF if installed.

### PDF Features

- Corporate black letterhead design
- Legal agreement text
- Signer information
- Digital signature (typed or image)
- IP address, location, fingerprint
- Timestamp with timezone
- Watermark: "CONFIDENTIAL - DO NOT DISTRIBUTE"
- SHA256 hash for verification

---

## 🛠️ Maintenance

### View Logs

```bash
# Security events
tail -f /var/www/aha-training/private/security.log

# PHP errors
tail -f /var/log/apache2/error.log
# or
tail -f /var/log/nginx/error.log
```

### Backup Database

```bash
# Create backup
cp /var/www/aha-training/private/aha_training.db ~/backups/aha_training_$(date +%Y%m%d).db

# Automated daily backup (cron)
0 2 * * * cp /var/www/aha-training/private/aha_training.db /root/backups/aha_training_$(date +\%Y\%m\%d).db
```

### Clear Rate Limits

```bash
sqlite3 /var/www/aha-training/private/aha_training.db "DELETE FROM rate_limits WHERE datetime(blocked_until) < datetime('now');"
```

### Clean Old Sessions

```bash
# PHP will handle this automatically, but you can force it:
find /var/lib/php/sessions -name 'sess_*' -mtime +1 -delete
```

---

## 🔧 Troubleshooting

### Issue: NDA submission fails

**Check:**
1. Database permissions: `ls -la private/aha_training.db`
2. PHP error log: `tail -f /var/log/apache2/error.log`
3. SQLite extension: `php -m | grep sqlite3`

### Issue: Email not sending

**Check:**
1. PHP mail configured: `echo "Test" | mail -s "Test" your@email.com`
2. Check spam folder
3. Review email-notifier.php logs

### Issue: Signature not saving

**Check:**
1. Directory permissions: `ls -la private/nda_records/`
2. Browser console for JavaScript errors
3. Verify signature data is being submitted

### Issue: Contact form not accessible

**Check:**
1. NDA session: `print_r($_SESSION)` in contact.php
2. Browser cookies enabled
3. Session save path writable: `ls -la /var/lib/php/sessions/`

### Issue: .htaccess rules not working

**Check:**
1. AllowOverride: `grep -r "AllowOverride" /etc/apache2/`
2. mod_rewrite enabled: `apache2ctl -M | grep rewrite`
3. Restart Apache: `systemctl restart apache2`

---

## 🚀 Phase 2 Enhancements (Future)

The following features can be added in the future:

### Admin Dashboard
- View all NDA records
- Read/respond to contact messages
- Export data to CSV
- View analytics and statistics

### Payment Integration
- Stripe/PayPal for course payments
- Online course registration
- Receipt generation

### Course Management
- Course enrollment system
- Student roster management
- Certificate issuance tracking

### Advanced Features
- SMS 2FA for NDA signing
- Automated NDA reminder emails
- PDF emailed to signer
- reCAPTCHA v3 integration
- Two-factor authentication
- User account system

---

## 📞 Support

For questions or issues:

**Developer Contact:**
- Email: t3h28@gmail.com
- GitHub: [t3h28](https://github.com/t3h28)

**Server Details:**
- IP: 198.211.114.12
- Hostname: DNS
- OS: Debian GNU/Linux 10 (Buster)

---

## 📜 License

This is proprietary software developed for Adam Powell & Adam Powell, LLC.
All rights reserved.

**Security Notice:** This system handles legally binding agreements and personal information.
Ensure all security measures are properly configured before deployment.

---

## ✅ Deployment Checklist

Before going live:

- [ ] All files uploaded to server
- [ ] Permissions set correctly (700 for /private/)
- [ ] Database initialized and writable
- [ ] Email notifications tested
- [ ] SSL certificate installed and working
- [ ] .htaccess files in place
- [ ] Test NDA signature flow (both typed and drawn)
- [ ] Test contact form submission
- [ ] Verify email notifications received
- [ ] Check database records created
- [ ] Test rate limiting
- [ ] Verify private directory is blocked from web
- [ ] Test on mobile devices
- [ ] Review security logs
- [ ] Set up automated backups

---

**Last Updated:** November 3, 2025
**Version:** 1.0.0
**Status:** Production Ready ✅
