# Profit Tracker – Deployment Guide
## Ubuntu 22.04 / 24.04 VPS

---

## 1. Server Requirements

- Ubuntu 22.04+ VPS (min 1GB RAM)
- PHP 8.1+ with extensions: `imap`, `pdo_mysql`, `mbstring`, `json`
- MySQL 8.0+ or MariaDB 10.6+
- Nginx
- Poppler-utils (PDF text extraction)
- Tesseract OCR (fallback for scanned PDFs)
- Ghostscript (OCR pre-processing)

---

## 2. Install Dependencies

```bash
# Update system
apt update && apt upgrade -y

# Install Nginx + PHP
apt install -y nginx php8.2-fpm php8.2-mysql php8.2-imap \
    php8.2-mbstring php8.2-json php8.2-curl php8.2-cli

# Install MySQL
apt install -y mysql-server
mysql_secure_installation

# Install PDF tools
apt install -y poppler-utils tesseract-ocr ghostscript

# Verify installs
which pdftotext tesseract gs php
```

---

## 3. Deploy Application Files

```bash
# Upload your zip and extract
mkdir -p /var/www/profit-tracker
cd /var/www
unzip profit-tracker.zip -d profit-tracker

# Set permissions
chown -R www-data:www-data /var/www/profit-tracker
chmod -R 755 /var/www/profit-tracker
chmod -R 775 /var/www/profit-tracker/storage

# Create storage directories
mkdir -p /var/www/profit-tracker/storage/attachments
mkdir -p /var/www/profit-tracker/storage/logs
chown -R www-data:www-data /var/www/profit-tracker/storage
```

---

## 4. Configure the Application

Edit `/var/www/profit-tracker/config/config.php`:

```php
// Update these values:
define('APP_URL',    'https://yourdomain.com');
define('APP_SECRET', 'your-random-64-char-secret-here');  // openssl rand -hex 32
define('DB_HOST',    '127.0.0.1');
define('DB_NAME',    'profit_tracker');
define('DB_USER',    'pt_user');
define('DB_PASS',    'your_db_password');
```

Or use environment variables in `/etc/environment`:

```
APP_URL=https://yourdomain.com
APP_SECRET=your-random-secret
DB_HOST=127.0.0.1
DB_NAME=profit_tracker
DB_USER=pt_user
DB_PASS=your_db_password
APP_ENV=production
```

---

## 5. Setup Database

```bash
# Login to MySQL
mysql -u root -p

# Run these SQL commands:
CREATE DATABASE profit_tracker CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'pt_user'@'localhost' IDENTIFIED BY 'your_db_password';
GRANT ALL PRIVILEGES ON profit_tracker.* TO 'pt_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

# Import schema
mysql -u pt_user -p profit_tracker < /var/www/profit-tracker/database/schema.sql
```

---

## 6. Configure Nginx

```bash
# Copy nginx config
cp /var/www/profit-tracker/profit-tracker.nginx.conf /etc/nginx/sites-available/profit-tracker

# Edit and replace 'yourdomain.com' with your actual domain
nano /etc/nginx/sites-available/profit-tracker

# Enable site
ln -s /etc/nginx/sites-available/profit-tracker /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Test and reload
nginx -t && systemctl reload nginx
```

---

## 7. SSL Certificate (Let's Encrypt)

```bash
apt install -y certbot python3-certbot-nginx
certbot --nginx -d yourdomain.com -d www.yourdomain.com

# Auto-renewal
systemctl enable certbot.timer
```

After certbot, uncomment the HTTPS block in the nginx config.

---

## 8. Setup Cron Job

```bash
# Edit crontab for www-data user
crontab -u www-data -e

# Add these lines:
# Sync emails every 15 minutes
*/15 * * * * /usr/bin/php /var/www/profit-tracker/cron/sync.php >> /var/log/pt-sync.log 2>&1

# Regenerate monthly reports daily at midnight
0 0 * * * /usr/bin/php -r "
  require '/var/www/profit-tracker/config/config.php';
  require '/var/www/profit-tracker/app/Models/Database.php';
  require '/var/www/profit-tracker/app/Helpers/helpers.php';
  require '/var/www/profit-tracker/app/Services/PdfParser.php';
  require '/var/www/profit-tracker/app/Services/InvoiceProcessor.php';
  InvoiceProcessor::regenerateMonthlyReports();
" >> /var/log/pt-reports.log 2>&1
```

---

## 9. First Login & Configuration

1. Visit `https://yourdomain.com`
2. Login: `admin@example.com` / `admin123`
3. **Immediately change password** in MySQL:
   ```sql
   UPDATE users SET password='' WHERE email='admin@example.com';
   -- Then use the app's future password change feature, or:
   php -r "echo password_hash('YourNewPassword', PASSWORD_BCRYPT, ['cost'=>12]);"
   -- Paste the hash into:
   UPDATE users SET password='HASH_HERE' WHERE email='admin@example.com';
   ```
4. Go to **Settings** → Add your IMAP email credentials
5. Click **Sync Emails** to run first sync

---

## 10. Firewall Setup

```bash
ufw allow 22/tcp    # SSH
ufw allow 80/tcp    # HTTP
ufw allow 443/tcp   # HTTPS
ufw enable
```

---

## 11. Common IMAP Settings

| Provider     | IMAP Host             | Port | SSL |
|-------------|----------------------|------|-----|
| Gmail        | imap.gmail.com       | 993  | Yes |
| Outlook/365  | outlook.office365.com| 993  | Yes |
| cPanel mail  | mail.yourdomain.com  | 993  | Yes |
| Namecheap    | mail.privateemail.com| 993  | Yes |

> **Gmail users:** Enable "Less secure app access" or use an App Password.

---

## 12. Troubleshooting

```bash
# Check PHP-FPM is running
systemctl status php8.2-fpm

# Check Nginx error log
tail -f /var/log/nginx/error.log

# Check app logs
tail -f /var/www/profit-tracker/storage/logs/$(date +%Y-%m-%d).log

# Test PDF extraction
pdftotext /path/to/invoice.pdf -
tesseract /path/to/image.png stdout

# Test IMAP (PHP)
php -r "var_dump(imap_open('{imap.gmail.com:993/imap/ssl}INBOX','you@gmail.com','password'));"
```

---

## 13. Security Checklist

- [ ] Changed default admin password
- [ ] Set strong `APP_SECRET` (min 32 chars)
- [ ] SSL certificate installed
- [ ] Firewall configured
- [ ] Storage directory not web-accessible (nginx blocks it)
- [ ] Production mode (`APP_ENV=production`) disables error display
- [ ] Regular MySQL backups: `mysqldump profit_tracker > backup.sql`

---

## Architecture Summary

```
Email Inbox (IMAP)
      ↓  (every 15 min via cron)
EmailService → download PDFs
      ↓
PdfParser → extract text → classify
      ↓
InvoiceProcessor → insert to DB
      ↓
Monthly Reports (auto-cached)
      ↓
Dashboard UI (Chart.js)
```
