#!/bin/bash
# =============================================================
# Kharis Hub – Installation Script
# Kharis Empowerment Centre Church Management System
# =============================================================

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

echo -e "${BLUE}"
echo "  ██╗  ██╗██╗  ██╗ █████╗ ██████╗ ██╗███████╗    ██╗  ██╗██╗   ██╗██████╗ "
echo "  ██║ ██╔╝██║  ██║██╔══██╗██╔══██╗██║██╔════╝    ██║  ██║██║   ██║██╔══██╗"
echo "  █████╔╝ ███████║███████║██████╔╝██║███████╗    ███████║██║   ██║██████╔╝"
echo "  ██╔═██╗ ██╔══██║██╔══██║██╔══██╗██║╚════██║    ██╔══██║██║   ██║██╔══██╗"
echo "  ██║  ██╗██║  ██║██║  ██║██║  ██║██║███████║    ██║  ██║╚██████╔╝██████╔╝"
echo "  ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚══════╝    ╚═╝  ╚═╝ ╚═════╝ ╚═════╝ "
echo -e "${NC}"
echo -e "${GREEN}  Church Management System v1.0 – Installation Script${NC}"
echo "  ============================================================="
echo ""

check_command() {
    if ! command -v "$1" &> /dev/null; then
        echo -e "${RED}[ERROR] $1 is required but not installed.${NC}"
        exit 1
    fi
}

step() {
    echo -e "\n${YELLOW}▶ $1${NC}"
}

success() {
    echo -e "${GREEN}  ✓ $1${NC}"
}

# Check requirements
step "Checking requirements..."
check_command "php"
check_command "composer"
check_command "mysql"
PHP_VERSION=$(php -r "echo PHP_VERSION;")
echo "  PHP version: $PHP_VERSION"
success "Requirements OK"

# Copy .env
step "Setting up environment file..."
if [ ! -f ".env" ]; then
    cp .env.example .env
    success ".env file created from .env.example"
else
    echo "  .env already exists, skipping..."
fi

# Prompt for DB credentials
echo ""
echo -e "${BLUE}  Database Configuration${NC}"
echo "  -----------------------"
read -p "  Database Host [127.0.0.1]: " DB_HOST
DB_HOST=${DB_HOST:-127.0.0.1}
read -p "  Database Port [3306]: " DB_PORT
DB_PORT=${DB_PORT:-3306}
read -p "  Database Name [kharis_hub]: " DB_NAME
DB_NAME=${DB_NAME:-kharis_hub}
read -p "  Database Username [root]: " DB_USER
DB_USER=${DB_USER:-root}
read -s -p "  Database Password: " DB_PASS
echo ""

# Update .env
sed -i "s/DB_HOST=.*/DB_HOST=$DB_HOST/" .env
sed -i "s/DB_PORT=.*/DB_PORT=$DB_PORT/" .env
sed -i "s/DB_DATABASE=.*/DB_DATABASE=$DB_NAME/" .env
sed -i "s/DB_USERNAME=.*/DB_USERNAME=$DB_USER/" .env
sed -i "s/DB_PASSWORD=.*/DB_PASSWORD=$DB_PASS/" .env

# App URL
echo ""
read -p "  Application URL [http://localhost]: " APP_URL
APP_URL=${APP_URL:-http://localhost}
sed -i "s|APP_URL=.*|APP_URL=$APP_URL|" .env

success "Environment configured"

# Install dependencies
step "Installing PHP dependencies (this may take a few minutes)..."
composer install --no-dev --optimize-autoloader --no-interaction
success "Dependencies installed"

# Generate app key
step "Generating application key..."
php artisan key:generate
success "Application key generated"

# Create database
step "Creating database (if not exists)..."
mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" -e "CREATE DATABASE IF NOT EXISTS \`$DB_NAME\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null
if [ $? -eq 0 ]; then
    success "Database ready"
else
    echo -e "${YELLOW}  Warning: Could not create database automatically. Please create it manually.${NC}"
fi

# Run migrations
step "Running database migrations..."
php artisan migrate --force
success "Migrations complete"

# Seed database
step "Seeding database with default data..."
php artisan db:seed --force
success "Database seeded"

# Storage link
step "Creating storage symlink..."
php artisan storage:link
success "Storage linked"

# Cache config
step "Optimizing for production..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
success "Optimized"

# Set permissions
step "Setting file permissions..."
chmod -R 775 storage bootstrap/cache
success "Permissions set"

echo ""
echo -e "${GREEN}  =============================================================${NC}"
echo -e "${GREEN}  ✓  Kharis Hub installed successfully!${NC}"
echo -e "${GREEN}  =============================================================${NC}"
echo ""
echo -e "  ${BLUE}Access your application at:${NC} $APP_URL"
echo ""
echo -e "  ${BLUE}Default Login Credentials:${NC}"
echo "  ┌─────────────────────────────────────────────────┐"
echo "  │  Admin:   admin@kharishub.com / Admin@12345     │"
echo "  │  Pastor:  pastor@kharishub.com / Pastor@12345   │"
echo "  │  Finance: finance@kharishub.com / Finance@12345 │"
echo "  └─────────────────────────────────────────────────┘"
echo ""
echo -e "  ${YELLOW}⚠  Please change default passwords immediately after login!${NC}"
echo ""
