#!/bin/bash

# Elite SACCO - Post-Deployment Setup Script
# Run this script after uploading to Hostinger via SSH

echo "=========================================="
echo "Elite SACCO - Hostinger Setup Script"
echo "=========================================="
echo ""

# Check if in correct directory
if [ ! -f "artisan" ]; then
    echo "❌ Error: artisan file not found. Please run this script from the application root directory."
    exit 1
fi

echo "✓ Running in correct directory"
echo ""

# Step 1: Fix permissionsphp artisan view:clear
php artisan view:cache

# Step 2: Generate app key if not exists
echo "Step 2: Checking application key..."
if grep -q "APP_KEY=base64:" .env; then
    if grep -q "APP_KEY=base64:$" .env; then
        echo "  Generating new application key..."
        php artisan key:generate --force
        echo "✓ Application key generated"
    else
        echo "✓ Application key already set"
    fi
else
    echo "  Generating new application key..."
    php artisan key:generate --force
    echo "✓ Application key generated"
fi
echo ""

# Step 3: Run migrations
echo "Step 3: Running database migrations..."
read -p "  Continue with migrations? (y/n) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    php artisan migrate --force
    echo "✓ Migrations completed"
else
    echo "⊘ Migrations skipped"
fi
echo ""

# Step 4: Seed database
echo "Step 4: Database seeding (optional)..."
read -p "  Seed database with sample data? (y/n) " -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]; then
    php artisan db:seed --force
    echo "✓ Database seeded"
else
    echo "⊘ Seeding skipped"
fi
echo ""

# Step 5: Optimize for production
echo "Step 5: Optimizing for production..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan optimize
echo "✓ Production optimization complete"
echo ""

# Step 6: Create image directories
echo "Step 6: Creating image directories..."
mkdir -p public/images/payments/membership
mkdir -p public/images/payments/savings
mkdir -p public/images/payments/repayments
chmod -R 755 public/images
echo "✓ Image directories created"
echo ""

echo "=========================================="
echo "✓ Setup Complete!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Verify .env file is configured correctly"
echo "2. Set document root to: elite-sacco/public"
echo "3. Enable HTTPS/SSL in hPanel"
echo "4. Visit your domain to verify"
echo ""
echo "For detailed instructions, see HOSTINGER_DEPLOYMENT.md"
