#!/bin/bash

# REEN ERP - Environment Setup Script
echo "🚀 Starting REEN ERP setup..."

# 1. Copy .env file if it doesn't exist
if [ ! -f .env ]; then
    echo "📄 Creating .env file from .env.example..."
    cp .env.example .env
else
    echo "✅ .env file already exists."
fi

# 2. Install Composer Dependencies
echo "📦 Installing PHP dependencies..."
composer install --no-interaction --prefer-dist --optimize-autoloader

# 3. Install NPM Dependencies & Build Assets
echo "🎨 Installing NPM dependencies..."
npm install
echo "🏗️ Building assets with Vite..."
npm run build

# 4. Generate Application Key
echo "🔑 Generating application key..."
php artisan key:generate --force

# 5. Create Storage Link
echo "🔗 Creating storage link..."
php artisan storage:link

# 6. Database Migration and Seeding
# WARNING: This will prompt before wiping data if in production
echo "🗄️ Running database migrations and seeders..."
php artisan migrate:fresh --seed --force

# 7. Set Permissions (Linux Specific)
echo "🛡️ Setting folder permissions..."
chmod -R 775 storage bootstrap/cache
chown -R $USER:www-data storage bootstrap/cache 2>/dev/null || true

# 8. Clear Caches
echo "🧹 Clearing caches..."
php artisan optimize:clear

echo "✨ REEN ERP setup complete! You can now run 'php artisan serve'."