# Backup Monitor Dashboard — Setup Guide

## Prerequisites
- PHP 8.3+
- Composer
- MySQL 8.0+
- Node.js 20+ (for Breeze frontend assets)

---

## Installation

```bash
# 1. Install PHP dependencies
composer install

# 2. Copy environment file
cp .env.example .env

# 3. Generate application key
php artisan key:generate

# 4. Configure database in .env
#    DB_DATABASE=backup_monitor
#    DB_USERNAME=root
#    DB_PASSWORD=yourpassword

# 5. Run migrations + seeders
php artisan migrate --seed

# 6. Install Laravel Breeze (auth UI)
php artisan breeze:install blade --dark
npm install && npm run build

# 7. Start the development server
php artisan serve

# 8. Start the queue worker (separate terminal)
php artisan queue:work --queue=backups,default

# 9. Start the scheduler (separate terminal)
php artisan schedule:work
```

---

## Default Credentials (after seeding)

| Email                   | Password | Role   |
|-------------------------|----------|--------|
| admin@example.com       | password | Admin  |
| viewer@example.com      | password | Viewer |

---

## Key Artisan Commands

```bash
# Sync all enabled servers (runs daily via scheduler)
php artisan backup:sync

# Sync a single server by ID
php artisan backup:sync --server=1

# Force re-sync (overwrite today's existing report)
php artisan backup:sync --force

# Dispatch to queue instead of running inline
php artisan backup:sync --queue

# Skip email notification
php artisan backup:sync --no-email

# Delete old reports beyond retention period
php artisan backup:cleanup
```

---

## Cron Setup (Production)

Add to your server's crontab:

```cron
* * * * * cd /path/to/app && php artisan schedule:run >> /dev/null 2>&1
```

The scheduler is configured to run `backup:sync` at 01:00 AM daily  
(configurable in Settings → Scheduler Time).

---

## Architecture Overview

```
app/
├── Console/Commands/
│   ├── SyncBackupsCommand.php       # php artisan backup:sync
│   └── CleanupOldReportsCommand.php # php artisan backup:cleanup
├── Contracts/
│   ├── Repositories/                # Interfaces for DI
│   └── Services/                    # JetBackupServiceInterface
├── Exports/
│   └── BackupReportsExport.php      # Excel/CSV export
├── Http/Controllers/Admin/          # Web controllers
├── Http/Controllers/Api/            # JSON API controllers
├── Jobs/
│   ├── SyncServerBackupJob.php      # Queued per-server sync
│   └── SendDailyReportJob.php       # Queued email dispatch
├── Mail/
│   └── DailyBackupReport.php        # Daily summary email
├── Models/
│   ├── Server.php                   # Encrypted api_key
│   ├── BackupReport.php             # Status helpers, scopes
│   ├── BackupError.php              # Error classification
│   ├── Setting.php                  # Key-value settings w/ cache
│   ├── AuditLog.php                 # User action log
│   └── User.php                     # role: admin|viewer
├── Repositories/
│   ├── ServerRepository.php
│   └── BackupReportRepository.php
└── Services/
    ├── JetBackupService.php         # API client, retry logic
    ├── BackupErrorParser.php        # Error pattern matching
    ├── BackupSyncService.php        # Orchestrates sync + persist
    ├── SyncResult.php               # Value object
    └── AuditLogService.php
```

---

## JetBackup API Integration

The `JetBackupService` makes HTTP requests to:

| Method | Endpoint                           | Purpose              |
|--------|------------------------------------|----------------------|
| GET    | `/api/v1/accounts`                 | Connection test      |
| GET    | `/api/v1/backup/jobs`              | List backup jobs     |
| GET    | `/api/v1/backup/jobs/{id}`         | Job details          |

- API keys are encrypted with Laravel's `Crypt::encryptString()` (AES-256-CBC)
- Requests retry up to 3 times with exponential back-off (1s, 2s)
- SSL verification is disabled by default (cPanel self-signed certs)
- Configurable timeout via `JETBACKUP_API_TIMEOUT` (default: 30s)

---

## Error Detection Patterns

The `BackupErrorParser` automatically classifies these error types:

| Type       | Triggers                                          |
|------------|--------------------------------------------------|
| email      | "Email account didn't return password"           |
| database   | "Database export failed", "mysqldump error"      |
| rsync      | "rsync failed", "rsync error"                    |
| transfer   | "transfer failed"                                |
| permission | "permission denied"                              |
| disk       | "disk full", "no space left on device"           |
| timeout    | "timeout", "connection timed out"                |
| api        | "API unavailable", "curl error", "failed to connect" |

---

## Security

- API keys encrypted at rest (Laravel Crypt / AES-256-CBC)
- CSRF protection on all forms
- Admin middleware on all mutating actions
- Active-user check on every request
- Input validation via FormRequest classes
- SQL injection prevented via Eloquent ORM
- All routes behind authentication

---

## Running Tests

```bash
php artisan test

# Or with coverage
php artisan test --coverage
```

---

## Environment Variables Reference

| Variable                  | Default    | Description                     |
|---------------------------|------------|---------------------------------|
| `JETBACKUP_API_TIMEOUT`   | 30         | HTTP timeout per request (sec)  |
| `JETBACKUP_API_RETRY`     | 3          | Max retry attempts              |
| `BACKUP_REPORT_EMAIL`     | —          | Daily report recipient          |
| `BACKUP_SCHEDULER_TIME`   | 01:00      | Daily sync time (24h)           |
| `BACKUP_RETENTION_DAYS`   | 365        | How long to keep reports        |
| `COMPANY_NAME`            | My Company | Shown in emails and title bar   |
