#!/bin/bash

# ── Bdzoon Laravel Setup Script ───────────────────────────────────────
set -e
GREEN='\033[0;32m'; RED='\033[0;31m'; YELLOW='\033[1;33m'; NC='\033[0m'
log() { echo -e "${GREEN}[✓]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
err() { echo -e "${RED}[✗]${NC} $1"; exit 1; }

echo ""
echo "======================================"
echo "  Bdzoon E-Commerce — Laravel Setup  "
echo "======================================"
echo ""

# 1. Composer install
log "Installing PHP dependencies..."
composer install --optimize-autoloader --no-interaction || err "composer install failed"

# 2. Copy .env if missing
if [ ! -f .env ]; then
    cp .env.example .env
    warn ".env copied from .env.example — update DB credentials"
fi

# 3. Generate APP_KEY
log "Generating application key..."
php artisan key:generate --force

# 4. Create database (optional — if mysql available)
warn "Creating database 'bdzoon' (if MySQL available)..."
mysql -u root -e "CREATE DATABASE IF NOT EXISTS bdzoon CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null && log "Database created" || warn "Manual DB creation needed"

# 5. Run migrations
log "Running migrations..."
php artisan migrate --force || err "Migration failed — check DB credentials in .env"

# 6. Seed database
log "Seeding database..."
php artisan db:seed --force || warn "Seeder failed"

# 7. Storage link
log "Creating storage symlink..."
php artisan storage:link

# 8. Cache config
log "Caching config..."
php artisan config:clear
php artisan route:clear

echo ""
echo "======================================"
echo "  ✓ Setup Complete!"
echo "======================================"
echo ""
echo "  Admin:    admin@bdzoon.com / Admin@1234"
echo "  API URL:  http://localhost:8000/api/v1"
echo ""
echo "  Run: php artisan serve"
echo ""
