#!/bin/bash

# Lion POS - Localhost Startup Script
# This script sets up and runs the application locally using Docker

set -e

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$PROJECT_DIR"

echo "🚀 Lion POS - Starting Local Development Environment"
echo "=================================================="

# Step 1: Start Docker Containers
echo ""
echo "1️⃣  Starting Docker containers (MySQL, Redis, Laravel)..."
docker-compose up -d
echo "✅ Docker containers started"

# Wait for services to be ready
echo ""
echo "2️⃣  Waiting for services to initialize (15 seconds)..."
sleep 15

# Step 2: Install PHP Dependencies
echo ""
echo "3️⃣  Installing PHP dependencies..."
composer install
echo "✅ PHP dependencies installed"

# Step 3: Generate App Key
echo ""
echo "4️⃣  Generating application key..."
php artisan key:generate --force
echo "✅ Application key generated"

# Step 4: Database Setup
echo ""
echo "5️⃣  Running database migrations..."
php artisan migrate --force
echo "✅ Database migrated"

# Step 5: Seed Database (Optional)
read -p "6️⃣  Seed database with demo data? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    php artisan db:seed
    echo "✅ Database seeded with demo data"
fi

# Step 6: Install Frontend Dependencies
echo ""
echo "7️⃣  Installing frontend dependencies..."
npm install
echo "✅ Frontend dependencies installed"

# Step 7: Build Assets
echo ""
echo "8️⃣  Building frontend assets..."
npm run dev
echo "✅ Frontend assets built"

# Step 8: Cache Configuration
echo ""
echo "9️⃣  Caching configuration..."
php artisan config:cache
php artisan route:cache
echo "✅ Configuration cached"

# Final Summary
echo ""
echo "=================================================="
echo "✨ Setup Complete! Your application is ready."
echo "=================================================="
echo ""
echo "📝 Important Information:"
echo "========================"
echo ""
echo "🌐 Access Application:"
echo "   → http://localhost"
echo ""
echo "📊 Access Database (PHPMyAdmin):"
echo "   → http://localhost:8080"
echo "   → Username: root"
echo "   → Password: laravel"
echo ""
echo "📧 Access Mailhog (Email Testing):"
echo "   → http://localhost:8025"
echo ""
echo "📊 Database Details:"
echo "   → Host: mysql"
echo "   → Port: 3306"
echo "   → Database: lion_pos_local"
echo "   → User: laravel"
echo "   → Password: laravel"
echo ""
echo "🛑 To Stop Development:"
echo "   → docker-compose down"
echo ""
echo "📋 Useful Commands:"
echo "   → docker-compose logs -f laravel.test    (View live logs)"
echo "   → php artisan tinker                       (Interactive PHP shell)"
echo "   → npm run watch                            (Watch assets for changes)"
echo ""
