#!/bin/bash

# Production Deployment Script
# This script prepares the application for production deployment

set -e

echo "🚀 Starting Production Deployment..."

# Check if we're in the right directory
if [ ! -f "composer.json" ]; then
    echo "❌ Error: Must be run from project root directory"
    exit 1
fi

# Backup current .env if it exists
if [ -f ".env" ]; then
    echo "📦 Backing up current .env to .env.backup"
    cp .env .env.backup
fi

# Copy production environment file
echo "📝 Setting up production environment..."
cp .env.production .env

# Clear all caches
echo "🧹 Clearing caches..."
rm -rf storage/cache/*
rm -rf var/cache/*
rm -rf cache/*

# Install production dependencies (no dev dependencies)
echo "📦 Installing production dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

# Build production assets
echo "🎨 Building production assets..."
npm run build

# Set correct permissions
echo "🔐 Setting correct permissions..."
chmod -R 755 storage/
chmod -R 755 var/
chmod -R 755 public/

# Create necessary directories
mkdir -p storage/logs
mkdir -p storage/cache
mkdir -p var/cache
mkdir -p var/logs

# Run database migrations
echo "🗄️ Running database migrations..."
php console.php db:migrate --force

# Clear PHP opcache if available
if command -v cachetool &> /dev/null; then
    echo "🔄 Clearing PHP opcache..."
    cachetool opcache:reset
fi

# Restart services (if using systemctl)
if command -v systemctl &> /dev/null; then
    echo "🔄 Restarting services..."
    sudo systemctl restart php8.4-fpm
    sudo systemctl restart nginx
fi

echo "✅ Production deployment complete!"
echo ""
echo "⚠️  IMPORTANT REMINDERS:"
echo "1. Ensure APP_ENV=production in .env"
echo "2. Ensure APP_DEBUG=false in .env"
echo "3. Update database credentials if needed"
echo "4. Update ADMIN_ALLOWED_IPS in .env for admin access"
echo "5. Test the site to ensure everything works"
echo ""
echo "🔒 Security Checklist:"
echo "[ ] Performance debug is disabled"
echo "[ ] Session debug info is hidden"
echo "[ ] Admin routes are IP-restricted"
echo "[ ] Error messages are generic"
echo "[ ] HTTPS is enforced"