#!/bin/bash

# KeywordMatcherPro Deployment Script
# This script helps with deploying the application to o2switch or similar hosting

echo "==================================="
echo "KeywordMatcherPro Deployment Helper"
echo "==================================="
echo ""

# Check if .env exists
if [ ! -f .env ]; then
    echo "⚠️  .env file not found. Copying from .env.example..."
    cp .env.example .env
    echo "✓ .env file created. Please edit it with your configuration."
    echo ""
fi

# Install dependencies
echo "📦 Installing Composer dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction
if [ $? -eq 0 ]; then
    echo "✓ Dependencies installed successfully"
else
    echo "✗ Failed to install dependencies"
    exit 1
fi

# Generate app key if not set
if ! grep -q "APP_KEY=base64:" .env; then
    echo ""
    echo "🔑 Generating application key..."
    php artisan key:generate --force
    echo "✓ Application key generated"
fi

# Run migrations
echo ""
echo "🗄️  Running database migrations..."
read -p "Run migrations now? (y/n): " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    php artisan migrate --force
    if [ $? -eq 0 ]; then
        echo "✓ Migrations completed successfully"
    else
        echo "✗ Migration failed. Please check database connection."
    fi
fi

# Set permissions
echo ""
echo "🔐 Setting directory permissions..."
chmod -R 755 storage
chmod -R 755 bootstrap/cache

# Create required directories
mkdir -p storage/app/exports
mkdir -p storage/framework/cache
mkdir -p storage/framework/sessions
mkdir -p storage/framework/views
mkdir -p storage/logs

echo "✓ Permissions set successfully"

# Create storage link
echo ""
echo "🔗 Creating storage symlink..."
php artisan storage:link
echo "✓ Storage link created"

# Optimize for production
echo ""
echo "⚡ Optimizing for production..."
php artisan config:cache
php artisan route:cache
echo "✓ Optimization complete"

# Display next steps
echo ""
echo "==================================="
echo "✅ Deployment preparation complete!"
echo "==================================="
echo ""
echo "Next steps:"
echo "1. Edit .env file with your API keys and database credentials"
echo "2. Set up cron job: * * * * * cd $(pwd) && php artisan schedule:run >> /dev/null 2>&1"
echo "3. Test the installation by visiting your domain"
echo "4. Check logs: tail -f storage/logs/laravel.log"
echo ""
echo "For full deployment instructions, see DEPLOYMENT.md"
echo ""
