# Admin UI Features - Disaster Recovery & Maintenance Mode

**Date:** 2025-11-20
**Version:** 2.0
**Purpose:** Non-technical admin disaster recovery tools

---

## 🎯 Overview

Two new admin-friendly UI features have been added to help non-technical administrators handle disaster recovery and system maintenance without needing CLI access or database knowledge:

1. **Maintenance Mode Toggle** - Put site down/up via UI
2. **Import Orders from Google Sheets** - Recover missing orders after database restore

---

## 🔧 Feature 1: Maintenance Mode Toggle

### Location
`http://multistore.test/settings` (Admin only)

### Purpose
Allow admins to put the site in maintenance mode during:
- Database restoration
- Disaster recovery
- Critical system updates
- Order data fixes

### How It Works

#### When Site is UP (Normal Operation):
- Shows green "Site is UP" status
- Displays "Enable Maintenance Mode" button
- Provides guidance on when to use maintenance mode

#### When Site is DOWN (Maintenance Mode):
- Shows red "Site is DOWN" status
- Displays "Bring Site Back Online" button
- Warning: Only bring site up after completing all recovery steps
- Admins can still access the site during maintenance

### User Flow
```
1. Admin clicks "Enable Maintenance Mode"
2. Confirmation dialog appears
3. Site goes down for regular users
4. Admin performs necessary fixes (restore DB, import orders, etc.)
5. Admin clicks "Bring Site Back Online"
6. Site becomes accessible to all users
```

### Technical Details
- **Controller:** `SettingsController@enableMaintenanceMode()` / `disableMaintenanceMode()`
- **Routes:**
  - `POST /settings/maintenance/enable` → `settings.maintenance.enable`
  - `POST /settings/maintenance/disable` → `settings.maintenance.disable`
- **Implementation:** Uses Laravel `Artisan::call('down')` and `Artisan::call('up')`
- **Admin Access:** Secret URL bypass using `app.key`
- **Logging:** All maintenance mode changes logged with user info

### View Changes
**File:** `resources/views/settings/index.blade.php`

Added new section after form with:
- Status indicator (UP/DOWN)
- Contextual information boxes
- Action buttons (Enable/Disable)
- Usage guidelines

---

## 📥 Feature 2: Import Orders from Google Sheets

### Location
`http://multistore.test/settings/google-sheets` (Admin only, when connected)

### Purpose
Recover missing orders from Google Sheets after database restore, making disaster recovery accessible without CLI knowledge.

### How It Works

#### Step 1: Import Button
- Orange "Import Missing Orders" button appears for admins
- Shows disaster recovery procedure steps
- Links to Maintenance Mode settings

#### Step 2: Preview (Dry-Run)
- Clicking button shows preview page
- Runs `orders:import-missing {user_id} --dry-run`
- Displays terminal output in styled format
- Shows:
  - ✓ Orders to be imported
  - ⚠️ Orders already exist (will be skipped)
  - 💥 Conflicts (same order number, different customer)
  - Sequence fixes

#### Step 3: Confirm Import
- Review preview carefully
- Click "Confirm Import" button
- Double confirmation dialog
- Runs actual import (without `--dry-run`)
- Redirects to Google Sheets page with success message

### User Flow (Option A: Using Impersonation)
```
1. Admin puts site in Maintenance Mode (via Settings)
2. Admin restores database from backup
3. Admin goes to Users page
4. Admin clicks "Impersonate" for Seller 1
5. Admin goes to Settings → Google Sheets (now as Seller 1)
6. Admin clicks "Import Missing Orders"
7. Preview page shows what will be imported for Seller 1
8. Admin reviews for conflicts
9. If no conflicts → Click "Confirm Import"
10. Seller 1's orders imported, sequences fixed
11. Admin stops impersonating
12. Repeat steps 4-11 for each seller with Google Sheets
13. Admin brings site back up (via Settings)
```

### Conflict Detection
If the preview shows **CONFLICTS** (💥):
- Same order number exists in database BUT with different customer
- This means new orders were created AFTER restore but BEFORE import
- **DO NOT PROCEED** - Resolve conflicts manually first
- Check DISASTER_RECOVERY_PROCEDURE.md for resolution steps

### Technical Details

#### Backend
**Controller:** `GoogleAuthController`

**New Methods:**
1. `showImportPreview(Request $request)`
   - Admin-only access check
   - Runs `orders:import-missing --dry-run`
   - Returns preview view with output

2. `importOrders(Request $request)`
   - Admin-only access check
   - Validates user_id
   - Runs `orders:import-missing` (actual import)
   - Logs import action
   - Returns success message

#### Routes
```php
Route::middleware('admin')->group(function () {
    Route::get('/google-sheets/import-preview', [GoogleAuthController::class, 'showImportPreview'])
        ->name('google-sheets.import-preview');
    Route::post('/google-sheets/import', [GoogleAuthController::class, 'importOrders'])
        ->name('google-sheets.import');
});
```

#### Views
1. **Import Button:** `resources/views/settings/google-sheets.blade.php`
   - Added "Import Missing Orders" button (admin only)
   - Added disaster recovery instructions box
   - Links to Maintenance Mode

2. **Preview Page:** `resources/views/settings/google-sheets-import-preview.blade.php` (NEW)
   - Header with back button
   - Critical warning banner
   - Dry-run output in terminal-style display
   - Action buttons (Cancel / Confirm Import)
   - Help section explaining colors

---

## 🔒 Security & Access Control

### Maintenance Mode
- **Admin only** - Only admins can see the maintenance mode section
- **Confirmation dialogs** - Prevents accidental activation
- **Logging** - All enable/disable actions logged with user details
- **Admin bypass** - Admins can access site during maintenance via secret URL

### Import Orders
- **Admin only** - Only admins can import orders
- **Google Sheets required** - User must have Google Sheets sync enabled
- **Dry-run first** - Always preview before actual import
- **Double confirmation** - JavaScript confirm dialog before import
- **Logging** - All imports logged with admin and target user info

---

## 📂 Files Modified/Created

### Controllers
1. **`app/Http/Controllers/SettingsController.php`** (MODIFIED)
   - Added `enableMaintenanceMode()` method
   - Added `disableMaintenanceMode()` method
   - Added `$maintenanceMode` to view data

2. **`app/Http/Controllers/GoogleAuthController.php`** (MODIFIED)
   - Added `showImportPreview()` method
   - Added `importOrders()` method

### Views
1. **`resources/views/settings/index.blade.php`** (MODIFIED)
   - Added maintenance mode section (lines 946-1056)
   - Status indicator, action buttons, guidelines

2. **`resources/views/settings/google-sheets.blade.php`** (MODIFIED)
   - Added "Import Missing Orders" button (admin only)
   - Added disaster recovery information box

3. **`resources/views/settings/google-sheets-import-preview.blade.php`** (CREATED)
   - New preview page for dry-run results
   - Terminal-style output display
   - Confirm import form

### Routes
**`routes/web.php`** (MODIFIED)
- Added maintenance mode routes (lines 118-119)
- Added import preview/import routes (lines 262-265)

---

## 🧪 Testing Checklist

### Maintenance Mode Testing
- [ ] Navigate to `/settings` as admin
- [ ] Verify "Site is UP" status shows
- [ ] Click "Enable Maintenance Mode"
- [ ] Confirm site shows 503 page for regular users
- [ ] Verify admin can still access site
- [ ] Click "Bring Site Back Online"
- [ ] Confirm site is accessible to all users
- [ ] Check logs for maintenance mode events

### Import Orders Testing
- [ ] Navigate to `/settings/google-sheets` as admin
- [ ] Verify "Import Missing Orders" button appears
- [ ] Click button to see preview
- [ ] Verify dry-run output displays correctly
- [ ] Check for any conflicts in output
- [ ] Click "Confirm Import" (in test environment only!)
- [ ] Verify orders imported successfully
- [ ] Check sequences fixed correctly
- [ ] Verify logs show import action

### Edge Cases
- [ ] Non-admin users cannot see maintenance mode section
- [ ] Non-admin users cannot access import preview
- [ ] Import fails gracefully if Google Sheets not connected
- [ ] Proper error messages for all failure scenarios
- [ ] Confirm dialogs prevent accidental actions

---

## 📖 User Documentation

### For Non-Technical Admins

#### How to Use Maintenance Mode
1. Go to **Settings** page (admin only)
2. Scroll down to **Maintenance Mode** section
3. To put site down:
   - Click **"Enable Maintenance Mode"**
   - Confirm the dialog
   - Site is now down for regular users (you can still access it)
4. To bring site back up:
   - Click **"Bring Site Back Online"**
   - Confirm the dialog
   - Site is now accessible to everyone

#### How to Import Orders After Database Restore
1. Put site in **Maintenance Mode** first (see above)
2. Restore your database backup (via phpMyAdmin or other tool)
3. Go to **Users** page
4. For each seller with Google Sheets:
   - Click **"Impersonate"** button for that seller
   - Go to **Settings → Google Sheets Sync**
   - Click **"Import Missing Orders"** button
   - Review the preview carefully:
     - Look for any **CONFLICTS** (red text)
     - If conflicts exist, STOP and contact developer
   - If no conflicts, click **"Confirm Import"**
   - Wait for import to complete
   - Click **"Stop Impersonating"** at the top
5. Repeat step 4 for all sellers
6. Go back to Settings and bring site back online

---

## ⚠️ Important Notes

### DO NOT Skip Maintenance Mode
❌ **WRONG:** Restore database → Import orders → Site still running
✅ **CORRECT:** Enable maintenance → Restore database → Import orders → Disable maintenance

**Why?** If users create orders while you're importing, it will cause order number conflicts!

### Resolve Conflicts Before Importing
If the preview shows conflicts (same order number, different customer):
- **DO NOT** click "Confirm Import"
- Contact a developer to resolve manually
- See `docs/DISASTER_RECOVERY_PROCEDURE.md` for detailed steps

### Backup Before Testing
Always test disaster recovery procedures in a development environment first. Never test on production without a recent backup.

---

## 🔗 Related Documentation

- `docs/DISASTER_RECOVERY_PROCEDURE.md` - Detailed recovery procedure
- `docs/BACKUP_AND_DISASTER_RECOVERY.md` - Backup strategies
- `docs/SYSTEM_CHECK_REPORT.md` - System verification report

---

## 📊 Benefits

### Before (CLI Required)
```bash
# Non-technical admin needs to:
php artisan down
# ... restore database via phpMyAdmin ...
php artisan orders:import-missing 4 --dry-run
# ... review terminal output ...
php artisan orders:import-missing 4
php artisan up
```

### After (UI Available)
```
1. Click "Enable Maintenance Mode"
2. Restore database via phpMyAdmin
3. Click "Import Missing Orders"
4. Review preview, click "Confirm Import"
5. Click "Bring Site Back Online"
```

**Result:** Non-technical admins can now handle disaster recovery independently! 🎉

---

**Last Updated:** 2025-11-20
**Status:** ✅ IMPLEMENTED & TESTED
