# Deployment Commands - Road Distance Implementation

## Prerequisites

Ensure the following are configured in your `.env` file:

```env
GOOGLE_MAPS_API_KEY=your_api_key_here
```

## Deployment Steps for Dev Environment

### 1. Pull Latest Code

```bash
git pull origin main
```

### 2. Backend Deployment

```bash
cd afinet-portal-backend

# Install/update dependencies (if any new packages)
composer install --no-dev --optimize-autoloader

# Clear all caches
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

# Run migrations (if any new migrations exist)
php artisan migrate --force

# Run seeders for customer type updates
php artisan db:seed --class=ProductCustomerTypeSeeder --force

# Rebuild caches
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Restart queue workers (if using queues)
php artisan queue:restart
```

### 3. Frontend Deployment

```bash
cd ../afinet-portal

# Install dependencies (if package.json changed)
npm install

# Build for production
npm run build

# Restart the application (if using PM2)
pm2 restart afinet-portal
```

### 4. Verify Deployment

```bash
# Test road distance calculation
cd ../afinet-portal-backend
php artisan tinker

# In tinker:
$gm = new App\Services\GoogleMapsService();
$km = new App\Services\KmzCoverageService($gm);
$result = $km->checkCoverage(-17.8252, 31.0335, 100, 500);
echo "Feasibility: " . $result['feasibility'] . "\n";
echo "Distance: " . ($result['distance_to_coverage'] ?? 'N/A') . "m\n";
echo "Method: " . ($result['distance_method'] ?? 'N/A') . "\n";
exit
```

## Quick Deployment Script

Create a file `deploy-road-distance.sh`:

```bash
#!/bin/bash

echo "=== Deploying Road Distance Implementation ==="

# Backend
cd afinet-portal-backend
echo "📦 Installing backend dependencies..."
composer install --no-dev --optimize-autoloader

echo "🧹 Clearing caches..."
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

echo "🗄️ Running migrations..."
php artisan migrate --force

echo "🌱 Running seeders..."
php artisan db:seed --class=ProductCustomerTypeSeeder --force

echo "⚡ Rebuilding caches..."
php artisan config:cache
php artisan route:cache
php artisan view:cache

echo "🔄 Restarting queue workers..."
php artisan queue:restart

# Frontend
cd ../afinet-portal
echo "📦 Installing frontend dependencies..."
npm install

echo "🏗️ Building frontend..."
npm run build

echo "🔄 Restarting application..."
pm2 restart afinet-portal

echo "✅ Deployment complete!"
```

Make it executable:
```bash
chmod +x deploy-road-distance.sh
./deploy-road-distance.sh
```

## Windows Deployment Script

Create a file `deploy-road-distance.bat`:

```batch
@echo off
echo === Deploying Road Distance Implementation ===

REM Backend
cd afinet-portal-backend
echo Installing backend dependencies...
call composer install --no-dev --optimize-autoloader

echo Clearing caches...
call php artisan cache:clear
call php artisan config:clear
call php artisan route:clear
call php artisan view:clear

echo Running migrations...
call php artisan migrate --force

echo Running seeders...
call php artisan db:seed --class=ProductCustomerTypeSeeder --force

echo Rebuilding caches...
call php artisan config:cache
call php artisan route:cache
call php artisan view:cache

echo Restarting queue workers...
call php artisan queue:restart

REM Frontend
cd ..\afinet-portal
echo Installing frontend dependencies...
call npm install

echo Building frontend...
call npm run build

echo Restarting application...
call pm2 restart afinet-portal

echo Deployment complete!
cd ..
```

## Rollback Plan (If Issues Occur)

```bash
# Backend rollback
cd afinet-portal-backend

# Rollback migrations (if needed)
php artisan migrate:rollback --step=1

# Clear caches
php artisan cache:clear
php artisan config:clear

# Restore previous code
git checkout HEAD~1

# Reinstall dependencies
composer install --no-dev --optimize-autoloader

# Rebuild caches
php artisan config:cache
php artisan route:cache
```

## Testing After Deployment

### 1. Test Road Distance API

```bash
curl -X POST https://your-dev-domain.com/api/website/check-feasibility \
  -H "Content-Type: application/json" \
  -d '{
    "address": "Harare CBD, Zimbabwe",
    "latitude": -17.8252,
    "longitude": 31.0335,
    "questionnaire_answers": {
      "usage_type": "home",
      "user_count": "1-5",
      "primary_activity": "streaming"
    }
  }'
```

Expected response:
```json
{
  "success": true,
  "data": {
    "feasibility_status": "medium",
    "coverage_zone": "harare",
    "feasibility_details": "{\"distance_to_coverage\":\"111m\",\"distance_method\":\"road\"}"
  }
}
```

### 2. Test Portal Products Page

1. Login to portal
2. Navigate to Products page
3. Verify products show correctly based on customer type
4. Check that feasibility banner appears if no check completed

### 3. Test Embed

Visit: `https://your-dev-domain.com/embed/coverage-check`

1. Complete questionnaire
2. Enter address
3. Submit coverage check
4. Verify results show with road distance

## Environment Variables Checklist

Ensure these are set in production `.env`:

```env
# Google Maps (Required for road distance)
GOOGLE_MAPS_API_KEY=your_production_api_key

# Database
DB_CONNECTION=mysql
DB_HOST=your_db_host
DB_PORT=3306
DB_DATABASE=your_db_name
DB_USERNAME=your_db_user
DB_PASSWORD=your_db_password

# App
APP_ENV=production
APP_DEBUG=false
APP_URL=https://your-production-domain.com

# Cache
CACHE_DRIVER=redis
SESSION_DRIVER=redis
QUEUE_CONNECTION=redis
```

## Monitoring After Deployment

### 1. Check Logs

```bash
# Laravel logs
tail -f afinet-portal-backend/storage/logs/laravel.log

# Look for:
# - Google Maps API errors
# - KMZ coverage check errors
# - Distance calculation warnings
```

### 2. Monitor API Usage

Check Google Cloud Console for:
- Distance Matrix API calls
- API errors/failures
- Quota usage

### 3. Database Checks

```sql
-- Check recent feasibility checks
SELECT 
    id,
    feasibility_status,
    coverage_zone,
    JSON_EXTRACT(feasibility_details, '$.distance_method') as distance_method,
    JSON_EXTRACT(feasibility_details, '$.distance_to_coverage') as distance,
    created_at
FROM feasibility_checks
ORDER BY created_at DESC
LIMIT 10;

-- Verify customer types are set
SELECT 
    code,
    name,
    customer_type,
    service_category
FROM products
WHERE customer_type IS NOT NULL;
```

## Common Issues & Solutions

### Issue 1: Google Maps API Not Working

**Symptoms:** `distance_method: "estimated"` in responses

**Solution:**
```bash
# Check API key is set
php artisan tinker
config('services.google_maps.api_key')

# If null, update .env and clear cache
php artisan config:clear
php artisan config:cache
```

### Issue 2: Products Not Filtering Correctly

**Symptoms:** Wrong products showing for customer type

**Solution:**
```bash
# Re-run seeder
php artisan db:seed --class=ProductCustomerTypeSeeder --force

# Clear cache
php artisan cache:clear
```

### Issue 3: KMZ Files Not Found

**Symptoms:** All locations showing "low" feasibility

**Solution:**
```bash
# Check KMZ files exist
ls -la afinet-portal-backend/storage/app/coverage/

# Should see:
# - harare.kmz
# - bulawayo.kmz

# If missing, upload KMZ files to storage/app/coverage/
```

## Success Criteria

✅ Road distance calculation working (check `distance_method: "road"`)
✅ Service type thresholds applied correctly
✅ Products filtered by customer type
✅ Embed using same logic as portal
✅ No errors in logs
✅ Google Maps API calls successful

## Support Contacts

- **Backend Issues:** Check Laravel logs
- **Frontend Issues:** Check browser console
- **API Issues:** Check Google Cloud Console
- **Database Issues:** Check MySQL logs

---

**Deployment Date:** _____________
**Deployed By:** _____________
**Environment:** Dev/Staging/Production
**Status:** ✅ Success / ❌ Failed / ⏳ In Progress
