#!/bin/bash
set -euo pipefail

# =============================================================================
# KHWWC Single-File cPanel Deployment
# =============================================================================
# Upload this script to:
# /home/kirinyag/public_html/app.kirinyagahealthcareworkerswelfare.co.ke/
# Then run: bash deploy.sh
# =============================================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ZIP_FILE="${SCRIPT_DIR}/KHWWC_PRODUCTION_DEPLOYMENT_FINAL_20260831.zip"
APP_DIR="${SCRIPT_DIR}/khwwc"

info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[OK]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }

echo "============================================"
echo " KHWWC cPanel Deployment"
echo "============================================"
echo "Directory: $SCRIPT_DIR"
echo ""

# Step 1: Verify ZIP exists
if [ ! -f "$ZIP_FILE" ]; then
    error "ZIP file not found: $ZIP_FILE"
    error "Upload KHWWC_PRODUCTION_DEPLOYMENT_FINAL_20260831.zip first"
    exit 1
fi

# Step 2: Extract
if [ -d "$APP_DIR" ]; then
    warn "Removing old khwwc/ directory..."
    rm -rf "$APP_DIR"
fi

info "Extracting..."
mkdir -p "$APP_DIR"
unzip -q "$ZIP_FILE" -d "$SCRIPT_DIR"
success "Extracted to $APP_DIR"

# Step 3: Setup .env
info "Setting up environment..."
cd "$APP_DIR"

if [ ! -f .env ]; then
    cp .env.example .env
    success "Created .env from .env.example"
else
    warn ".env exists, backing up..."
    cp .env .env.backup.$(date +%Y%m%d_%H%M%S)
fi

# Step 4: Generate JWT
info "Generating JWT secret..."
JWT_SECRET=$(php -r "echo bin2hex(random_bytes(32));")
sed -i "s/^JWT_SECRET=.*/JWT_SECRET=${JWT_SECRET}/" .env
success "JWT_SECRET set"

# Step 5: Generate APP_KEY
info "Generating APP_KEY..."
php artisan key:generate --no-interaction --force
success "APP_KEY generated"

# Step 6: Permissions
info "Setting permissions..."
chmod -R 755 storage bootstrap/cache
chmod -R 775 storage
mkdir -p storage/app/public storage/app/backups storage/framework/{cache,sessions,views} storage/logs
success "Permissions set"

# Step 7: Migrations
info "Running migrations..."
php artisan migrate --no-interaction --force
success "Migrations complete"

# Step 8: Seed admin
info "Seeding admin users..."
php artisan db:seed --class=ProductionAdminSeeder --no-interaction --force || warn "Seeder failed or already seeded"

# Step 9: Optimize
info "Optimizing..."
php artisan config:clear --no-interaction
php artisan route:clear --no-interaction
php artisan view:clear --no-interaction
php artisan cache:clear --no-interaction
php artisan config:cache --no-interaction
php artisan route:cache --no-interaction
php artisan view:cache --no-interaction
success "Optimization complete"

echo ""
echo "============================================"
echo " Deployment Complete"
echo "============================================"
echo ""
echo "Verify:"
echo "  https://app.kirinyagahealthcareworkerswelfare.co.ke/api/health"
echo ""
echo "Login:"
echo "  Super Admin: superadmin@khwwc.local / Super2026"
echo "  Admin: admin@khwwc.local / Admin2026"
echo ""
echo "CHANGE DEFAULT PASSWORDS!"
echo ""
echo "App directory: $APP_DIR"
echo "Public directory: $APP_DIR/public"
echo ""
