#!/bin/bash

# --- Colors for Output ---
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}==============================================${NC}"
echo -e "${GREEN}      Laravel Project Auto-Installer         ${NC}"
echo -e "${BLUE}==============================================${NC}"

# 1. Copy .env if not exists
if [ ! -f .env ]; then
    echo -e "${BLUE}[1/7] Creating .env file from .env.example...${NC}"
    cp .env.example .env
fi

# 2. Check for vendor folder (if empty, run temporary composer container)
if [ ! -d "vendor" ]; then
    echo -e "${BLUE}[2/7] Vendor folder missing. Installing dependencies via Docker...${NC}"
    docker run --rm \
        -u "$(id -u):$(id -g)" \
        -v "$(pwd):/var/www/html" \
        -w /var/www/html \
        laravelsail/php83-composer:latest \
        composer install --ignore-platform-reqs
else
    echo -e "${GREEN}[2/7] Vendor folder exists. Skipping composer install.${NC}"
fi

# 3. Start Docker Containers
echo -e "${BLUE}[3/7] Booting up Docker containers (Sail)...${NC}"
./vendor/bin/sail up -d

# Wait for database to be ready
echo -e "${BLUE}Waiting for database healthcheck...${NC}"
sleep 10

# 4. Generating Application Key
echo -e "${BLUE}[4/7] Securing Application...${NC}"
./vendor/bin/sail artisan key:generate

# 5. Running Migrations & Seeders
echo -e "${BLUE}[5/7] Preparing Database (Migration & Seeding)...${NC}"
./vendor/bin/sail artisan migrate:fresh --seed

# 6. Creating Storage Link & NPM
echo -e "${BLUE}[6/7] Connecting Storage & Installing NPM...${NC}"
chmod +x artisan
chmod +x sail
./vendor/bin/sail artisan storage:link
./vendor/bin/sail npm install
./vendor/bin/sail npm run build

# 7. Finalizing
echo -e "${BLUE}[7/7] Launching application...${NC}"
./vendor/bin/sail artisan up

echo -e "${BLUE}==============================================${NC}"
echo -e "${GREEN}   SUCCESS! Application is ready to use.     ${NC}"
echo -e "   URL: http://localhost:8888                ${NC}"
echo -e "   Monitoring: http://localhost:8888/system-monitoring ${NC}"
echo -e "${BLUE}==============================================${NC}"
