# ELMIS Database Backup System

A comprehensive database backup solution for the ELMIS (Electronic Logistics Management Information System) with support for multiple storage destinations including local storage, cPanel/FTP, and Google Drive.

## 🚀 Features

- **Automated Daily Backups** - Scheduled backups at configurable intervals
- **Multiple Storage Options** - Local, cPanel/FTP, and Google Drive support
- **Email Notifications** - Get notified on backup success/failure
- **Backup Management** - List, restore, and monitor backup files
- **Compression** - Efficient gzip compression for smaller backup files
- **Cleanup** - Automatic removal of old backups based on retention policy
- **Security** - Encrypted connections and secure credential management

## 📋 Installation & Setup

### 1. Install Required Packages

The following packages are already included in your `composer.json`:

```bash
composer install
```

Required packages:
- `spatie/laravel-backup` - Main backup package
- `league/flysystem-ftp` - FTP storage support  
- `league/flysystem-sftp-v3` - SFTP storage support
- `google/apiclient` - Google Drive API client

### 2. Environment Configuration

Copy the backup configuration from `.env.example` to your `.env` file and configure:

```env
# Backup Configuration
BACKUP_DISK=local
BACKUP_NAME="ELMIS-Database"
BACKUP_FILENAME_PREFIX="elmis-"
BACKUP_MAIL_TO=admin@elmis.afga.org

# Storage Selection: local, cpanel, google
BACKUP_STORAGE=local

# FTP/cPanel Configuration (use when BACKUP_STORAGE=cpanel)
FTP_HOST=ftp.yourdomain.com
FTP_USERNAME=your-ftp-username
FTP_PASSWORD=your-ftp-password
FTP_PORT=21
FTP_ROOT=/public_html/backups
FTP_PASSIVE=true
FTP_SSL=false
FTP_TIMEOUT=30

# Google Drive Configuration (use when BACKUP_STORAGE=google)
GOOGLE_DRIVE_CLIENT_ID=your-google-client-id
GOOGLE_DRIVE_CLIENT_SECRET=your-google-client-secret
GOOGLE_DRIVE_REFRESH_TOKEN=your-refresh-token
GOOGLE_DRIVE_FOLDER=ELMIS-Backups
```

### 3. Storage Setup

#### Local Storage (Default)
No additional setup required. Backups will be stored in `storage/app/backups/`.

#### cPanel/FTP Storage
1. Create a backup directory in your cPanel file manager
2. Configure FTP credentials in `.env`
3. Set `BACKUP_STORAGE=cpanel`

#### Google Drive Storage
1. Create a Google Cloud Project
2. Enable Google Drive API
3. Create OAuth 2.0 credentials
4. Generate refresh token
5. Configure credentials in `.env`
6. Set `BACKUP_STORAGE=google`

**Google Drive Setup Instructions:**

```bash
# 1. Visit Google Cloud Console
https://console.cloud.google.com/

# 2. Create new project or select existing
# 3. Enable Google Drive API
# 4. Create OAuth 2.0 Client ID credentials
# 5. Download credentials JSON
# 6. Use OAuth playground to get refresh token
https://developers.google.com/oauthplayground/
```

### 4. Scheduled Tasks Setup

#### Development (Local)
```bash
php artisan schedule:work
```

#### Production (Cron Job)
Add this to your crontab:
```bash
* * * * * cd /path/to/elmis/backend && php artisan schedule:run >> /dev/null 2>&1
```

## 🎯 Usage

### Manual Backup Commands

#### Create Database Backup
```bash
# Local storage
php artisan backup:database

# Specific storage with notifications
php artisan backup:database --storage=google --notify --cleanup

# Using Spatie backup (full application backup)
php artisan backup:run
```

#### Check Backup Status  
```bash
# Show backup overview
php artisan backup:status

# Detailed file information
php artisan backup:status --detailed --storage=google

# Monitor backup health
php artisan backup:monitor
```

#### List Available Backups
```bash
# List local backups
php artisan backup:restore --list

# List remote backups
php artisan backup:restore --list --storage=google
```

#### Restore Database
```bash
# Interactive restore (will prompt for file selection)
php artisan backup:restore

# Restore specific file
php artisan backup:restore elmis_backup_2024-10-08_12-00-00.sql.gz

# Force restore without confirmation
php artisan backup:restore --force --storage=google
```

#### Cleanup Old Backups
```bash
php artisan backup:clean
```

### Scheduled Backup Tasks

The system automatically runs these scheduled tasks:

| Task | Schedule | Command | Description |
|------|----------|---------|-------------|
| Database Backup | Daily 00:00 | `backup:database` | Creates compressed database backup |
| Full Backup | Daily 01:00 | `backup:run` | Full application backup (Spatie) |
| Cleanup | Weekly Sunday 02:00 | `backup:clean` | Removes old backups |
| Health Monitor | Daily 03:00 | `backup:monitor` | Checks backup integrity |

## ⚙️ Configuration Options

### Backup Retention Policy

Edit `config/backup.php` to customize retention:

```php
'keep_all_backups_for_days' => 7,           // Keep all backups for 7 days
'keep_daily_backups_for_days' => 16,        // Keep daily backups for 16 days  
'keep_weekly_backups_for_weeks' => 8,       // Keep weekly backups for 8 weeks
'keep_monthly_backups_for_months' => 4,     // Keep monthly backups for 4 months
'keep_yearly_backups_for_years' => 2,       // Keep yearly backups for 2 years
```

### Email Notifications

Configure mail settings in `.env`:
```env
MAIL_MAILER=smtp
MAIL_HOST=your-smtp-host
MAIL_PORT=587
MAIL_USERNAME=your-email@domain.com
MAIL_PASSWORD=your-email-password
MAIL_ENCRYPTION=tls
BACKUP_MAIL_TO=admin@elmis.afga.org
```

### Custom Backup Scheduling

Edit `app/Console/Kernel.php` to customize schedule:

```php
protected function schedule(Schedule $schedule): void
{
    // Custom schedule - every 6 hours
    $schedule->command('backup:database --notify')
        ->everyFourHours()
        ->withoutOverlapping();
        
    // Weekly full backup
    $schedule->command('backup:run')
        ->weekly()
        ->sundays()
        ->at('01:00');
}
```

## 🔧 Troubleshooting

### Common Issues

#### 1. Permission Errors
```bash
# Fix storage permissions
chmod -R 755 storage/
chmod -R 777 storage/app/backups/
```

#### 2. MySQL Connection Issues
```bash
# Test MySQL connection
php artisan tinker
DB::connection()->getPdo();
```

#### 3. FTP Connection Problems
```bash
# Test FTP configuration
php artisan backup:status --storage=cpanel
```

#### 4. Google Drive API Errors
- Verify API is enabled in Google Cloud Console
- Check OAuth credentials are valid
- Ensure refresh token hasn't expired

### Logs

Check backup logs in:
- `storage/logs/backup.log` - Custom backup command logs
- `storage/logs/spatie-backup.log` - Spatie backup logs  
- `storage/logs/laravel.log` - General application logs

### Testing

Test your backup configuration:

```bash
# Test backup creation
php artisan backup:database --storage=local

# Verify backup file
php artisan backup:status --detailed

# Test restore (use with caution!)
php artisan backup:restore --list
```

## 🔒 Security Considerations

1. **Credentials** - Never commit `.env` file with real credentials
2. **Backup Location** - Ensure backup storage is secure and encrypted
3. **Access Control** - Limit access to backup files and restoration commands
4. **Network Security** - Use encrypted connections (FTPS, SFTP) when possible
5. **Regular Testing** - Periodically test backup restoration process

## 🎉 Features Summary

✅ **Automated scheduling** with cron integration  
✅ **Multiple storage backends** (Local, FTP, Google Drive)  
✅ **Email notifications** on success/failure  
✅ **Compression** for space efficiency  
✅ **Retention policies** for automatic cleanup  
✅ **Restoration capabilities** with safety checks  
✅ **Monitoring and status** reporting  
✅ **Secure credential** management  
✅ **Comprehensive logging** for troubleshooting  

## 📞 Support

For issues or questions:
1. Check the logs in `storage/logs/`
2. Run `php artisan backup:status` for diagnostics  
3. Verify environment configuration
4. Test individual components (DB connection, storage access)

The backup system is now ready for production use! 🚀
