# Database Backup System - Complete Setup

## ✅ What's Been Implemented

### 1. **Backend API Endpoints** (Admin Only)
- `POST /admin/backup` - Trigger manual backup
- `GET /admin/backups` - List all available backups
- `POST /admin/restore?filename=<name>` - Restore from backup

### 2. **Frontend Admin Panel**
- New "ניהול" (Management) tab in navigation (visible to admin users only)
- 🛡️ Admin button in top bar
- Full backup management interface:
  - Create new backups instantly
  - View all backups with dates and sizes
  - Restore from any backup with confirmation

### 3. **Automated Weekly Backups**
- Batch script: `run_backup.bat`
- Full setup guide: `WEEKLY_BACKUP_SETUP.md`
- Configured for Windows Task Scheduler

## 🚀 How to Use

### **Manual Backup (Admin User)**

1. Login with admin account
2. Click 🛡️ "ניהול" button in top bar (or use the ניהול tab)
3. Click "צור גיבוי חדש" (Create New Backup)
4. Backup is created, compressed, and uploaded to R2
5. See confirmation toast: "גיבוי נוצר בהצלחה! 📦"

### **Restore from Backup (Admin User)**

1. Go to Admin Panel (🛡️ ניהול)
2. View all available backups in the table
3. Click "שחזר" (Restore) button for desired backup
4. Confirm the warning (this will delete current data!)
5. Page will refresh automatically after restore

### **Setup Weekly Automatic Backups**

Follow the instructions in `WEEKLY_BACKUP_SETUP.md`:

**Quick Steps:**
1. Open Task Scheduler (`Win + R` → `taskschd.msc`)
2. Create Task → "Recipe DB Weekly Backup"
3. Set trigger: Weekly, Sunday, 2:00 AM
4. Set action: Run `C:\Path\To\backend\run_backup.bat`
5. Configure to run even when not logged in

## 📁 Files Created/Modified

### Backend
- ✅ `backup_restore_api.py` - Core backup/restore functions
- ✅ `main.py` - Added admin endpoints
- ✅ `requirements.txt` - Added boto3 dependency
- ✅ `.env` - Added R2 credentials
- ✅ `run_backup.bat` - Windows batch script for scheduled tasks
- ✅ `BACKUP_README.md` - Complete documentation
- ✅ `WEEKLY_BACKUP_SETUP.md` - Task Scheduler setup guide

### Frontend
- ✅ `backupApi.js` - API calls for backup operations
- ✅ `components/AdminPanel.jsx` - Admin UI component
- ✅ `components/TopBar.jsx` - Added admin button
- ✅ `App.jsx` - Added admin view and navigation
- ✅ `App.css` - Added admin panel styles

## 🔐 Security

- **Admin-only access**: All backup endpoints check `is_admin` flag
- **Non-admin users**: Cannot see the admin button or access backup endpoints
- **403 Forbidden**: Returned if non-admin tries to access admin endpoints

## 💾 Backup Details

### What's Backed Up
- Complete PostgreSQL database (recipes_db)
- All tables: users, recipes, grocery lists, shares, notifications

### Backup Process
1. Uses `pg_dump` to export database
2. Compresses with gzip (typically 80-90% size reduction)
3. Uploads to Cloudflare R2 with timestamp
4. Filename format: `recipes_db_YYYYMMDD_HHMMSS.sql.gz`
5. Local backups auto-cleanup (keeps last 3)

### Restore Process
1. Downloads from R2
2. Decompresses file
3. **Drops all existing tables** (CASCADE)
4. Restores from SQL file
5. Cleans up temporary files

## 🧪 Testing

### Test Manual Backup
```bash
cd backend
python backup_db.py
```

### Test Manual Restore
```bash
cd backend
python restore_db.py
```

### Test via Web UI
1. Login as admin
2. Navigate to Admin Panel
3. Click "צור גיבוי חדש"
4. Check R2 bucket for new file

## ⚠️ Important Notes

1. **Restore is destructive**: It deletes ALL current data
2. **Admin access required**: Set user's `is_admin = true` in database
3. **R2 credentials**: Already configured in `.env`
4. **Weekly backups**: Manual setup required (follow WEEKLY_BACKUP_SETUP.md)
5. **PostgreSQL tools**: Must have `pg_dump` and `psql` in system PATH

## 🔧 Troubleshooting

### "Admin access required" error
- Check if user has `is_admin = true` in database
- Run: `SELECT username, is_admin FROM users;` in psql

### Backup fails
- Check `backend/backup.log` for errors
- Verify R2 credentials in `.env`
- Verify database credentials in `.env`
- Test: `python backup_db.py` manually

### Can't see admin button
- Verify user's `is_admin` flag in database
- Refresh page after changing admin status
- Check browser console for errors

### Scheduled backup doesn't run
- Check Task Scheduler → Task History
- Verify `run_backup.bat` path is correct
- Check `backend/backup.log` for errors
- Test batch file manually first

## 📊 What Admins Can Do

✅ Create manual backups anytime
✅ View all backups with dates and sizes  
✅ Restore from any backup point
✅ See backup history in table format
✅ All regular user features (recipes, grocery lists, etc.)

## Next Steps

1. **✅ Test the system**: Create a manual backup from Admin Panel
2. **📅 Setup weekly backups**: Follow WEEKLY_BACKUP_SETUP.md
3. **🔒 Secure admin access**: Only give admin rights to trusted users
4. **📝 Document your backup strategy**: When/how often you back up

---

**Your database is now protected with automated backups! 🎉**
