#!/bin/bash

##############################################################################
# Omnia PWA - Automated Installation Script
#
# This script automates the installation of Omnia PWA
#
# Usage: bash install.sh
##############################################################################

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

# Functions
print_header() {
    echo ""
    echo -e "${BLUE}============================================${NC}"
    echo -e "${BLUE}  🚀 Omnia PWA Installer${NC}"
    echo -e "${BLUE}============================================${NC}"
    echo ""
}

print_step() {
    echo -e "${BLUE}➜${NC} $1"
}

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

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

check_requirements() {
    print_step "Checking system requirements..."

    local failed=0

    # Check PHP version
    if command -v php &> /dev/null; then
        php_version=$(php -r "echo PHP_VERSION;")
        if [[ "$(printf '%s\n' "8.2" "$php_version" | sort -V | head -n1)" == "8.2" ]]; then
            print_success "PHP $php_version"
        else
            print_error "PHP 8.2+ required (found $php_version)"
            failed=1
        fi
    else
        print_error "PHP not found"
        failed=1
    fi

    # Check Composer
    if command -v composer &> /dev/null; then
        print_success "Composer installed"
    else
        print_error "Composer not found"
        failed=1
    fi

    # Check Node.js
    if command -v node &> /dev/null; then
        print_success "Node.js $(node -v)"
    else
        print_warning "Node.js not found (needed for asset building)"
    fi

    # Check required PHP extensions
    php_extensions=("pdo" "pdo_mysql" "mbstring" "xml" "bcmath" "gmp")
    for ext in "${php_extensions[@]}"; do
        if php -m | grep -q "^$ext$"; then
            print_success "PHP extension: $ext"
        else
            print_error "Missing PHP extension: $ext"
            failed=1
        fi
    done

    # Check writable directories
    if [[ -w "$SCRIPT_DIR/storage" ]]; then
        print_success "storage/ is writable"
    else
        print_error "storage/ is not writable"
        failed=1
    fi

    if [[ -w "$SCRIPT_DIR/bootstrap/cache" ]]; then
        print_success "bootstrap/cache/ is writable"
    else
        print_error "bootstrap/cache/ is not writable"
        failed=1
    fi

    if [[ $failed -eq 1 ]]; then
        print_error "Requirements check failed. Please fix the issues above."
        exit 1
    fi

    echo ""
}

backup_env() {
    if [[ -f ".env" ]]; then
        backup_file=".env.backup.$(date +%Y%m%d-%H%M%S)"
        cp .env "$backup_file"
        print_success "Existing .env backed up to $backup_file"
    fi
}

setup_env() {
    print_step "Setting up environment file..."

    if [[ -f ".env" ]]; then
        read -p "$(echo -e ${YELLOW}.env file already exists. Overwrite? [y/N]:${NC} )" -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            print_warning "Skipping .env setup"
            return
        fi
        backup_env
    fi

    # Copy .env.example to .env
    cp .env.example .env

    # Prompt for database credentials
    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: " db_database
    read -p "Database Username: " db_username
    read -sp "Database Password: " db_password
    echo ""

    read -p "Application URL [http://localhost]: " app_url
    app_url=${app_url:-http://localhost}

    read -p "Admin Email (for PWA): " admin_email

    # Update .env file
    sed -i.bak "s|DB_HOST=127.0.0.1|DB_HOST=$db_host|g" .env
    sed -i.bak "s|DB_PORT=3306|DB_PORT=$db_port|g" .env
    sed -i.bak "s|DB_DATABASE=multistore|DB_DATABASE=$db_database|g" .env
    sed -i.bak "s|DB_USERNAME=root|DB_USERNAME=$db_username|g" .env
    sed -i.bak "s|DB_PASSWORD=|DB_PASSWORD=$db_password|g" .env
    sed -i.bak "s|APP_URL=http://localhost|APP_URL=$app_url|g" .env
    sed -i.bak "s|APP_NAME=Laravel|APP_NAME=Omnia|g" .env
    sed -i.bak "s|mailto:admin@example.com|mailto:$admin_email|g" .env
    rm .env.bak

    print_success "Environment file configured"
    echo ""
}

install_dependencies() {
    print_step "Installing Composer dependencies..."
    composer install --optimize-autoloader --no-dev
    print_success "Composer dependencies installed"
    echo ""

    if command -v npm &> /dev/null; then
        print_step "Installing Node dependencies..."
        npm install
        print_success "Node dependencies installed"

        print_step "Building frontend assets..."
        npm run build
        print_success "Assets compiled"
        echo ""
    else
        print_warning "Skipping npm install (Node.js not found)"
        echo ""
    fi
}

generate_keys() {
    print_step "Generating application key..."
    php artisan key:generate --force
    print_success "APP_KEY generated"
    echo ""

    print_step "Generating VAPID keys for PWA..."
    php artisan webpush:vapid
    echo ""
}

run_migrations() {
    print_step "Running database migrations..."

    # Test database connection first
    if ! php artisan db:monitor &> /dev/null; then
        print_error "Database connection failed. Please check your .env settings."
        exit 1
    fi

    php artisan migrate --force
    print_success "Database migrations completed (88 tables created)"
    echo ""
}

set_permissions() {
    print_step "Setting file permissions..."

    chmod -R 775 storage bootstrap/cache

    print_success "Permissions set"
    echo ""
}

create_lock() {
    echo "Installation completed on $(date)" > storage/installed.lock
    print_success "Installation locked"
}

show_completion() {
    echo ""
    echo -e "${GREEN}============================================${NC}"
    echo -e "${GREEN}  ✓ Installation Complete!${NC}"
    echo -e "${GREEN}============================================${NC}"
    echo ""
    echo -e "${BLUE}Next Steps:${NC}"
    echo "1. Setup queue workers (Supervisor)"
    echo "2. Setup cron jobs for scheduled tasks"
    echo "3. Install SSL certificate (REQUIRED for PWA!)"
    echo "4. Delete public/install.php if exists"
    echo "5. Test PWA notifications"
    echo ""
    echo -e "${YELLOW}Documentation:${NC}"
    echo "- 01-START_HERE.md"
    echo "- 02-COMPLETE_DEPLOYMENT_GUIDE.md"
    echo "- 04-PWA_SETUP_GUIDE.md"
    echo ""
    echo -e "${GREEN}Your Omnia PWA is ready!${NC}"
    echo ""
}

# Main installation flow
main() {
    print_header

    check_requirements

    read -p "$(echo -e ${YELLOW}Continue with installation? [Y/n]:${NC} )" -n 1 -r
    echo
    if [[ $REPLY =~ ^[Nn]$ ]]; then
        echo "Installation cancelled."
        exit 0
    fi

    echo ""
    setup_env
    install_dependencies
    generate_keys
    run_migrations
    set_permissions
    create_lock
    show_completion
}

# Run main function
main
