#!/bin/bash
# ─────────────────────────────────────────────────────────────
# VoiceIQ — Quick Deploy Script
# Run from /var/www/feedback-saas after uploading project files
# Usage: chmod +x deploy.sh && sudo ./deploy.sh
# ─────────────────────────────────────────────────────────────

set -e

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  VoiceIQ — Deploy Script"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# 1. Composer install
echo "[1/8] Installing PHP dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

# 2. Copy env if not exists
if [ ! -f .env ]; then
    echo "[2/8] Creating .env from .env.example..."
    cp .env.example .env
    php artisan key:generate
else
    echo "[2/8] .env already exists. Skipping."
fi

# 3. Permissions
echo "[3/8] Setting permissions..."
chown -R www-data:www-data /var/www/feedback-saas
chmod -R 755 /var/www/feedback-saas
chmod -R 775 /var/www/feedback-saas/storage
chmod -R 775 /var/www/feedback-saas/bootstrap/cache

# 4. Migrations
echo "[4/8] Running migrations..."
php artisan migrate --force

# 5. Seed admin
echo "[5/8] Seeding admin user..."
php artisan db:seed --class=AdminSeeder --force

# 6. Cache
echo "[6/8] Caching config, routes, views..."
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 7. Storage link
echo "[7/8] Creating storage symlink..."
php artisan storage:link

# 8. Supervisor
echo "[8/8] Restarting queue workers..."
supervisorctl reread
supervisorctl update
supervisorctl restart feedback-saas-worker:* 2>/dev/null || true

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  ✓ Deploy complete!"
echo "  Admin: admin@feedbacksaas.com"
echo "  Pass:  Admin@12345  (change immediately)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
