#!/bin/bash

set -e  # Exit on any error

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# Function to check prerequisites
check_prerequisites() {
    print_status "Checking prerequisites..."

    # Check if composer is installed
    if ! command -v composer &> /dev/null; then
        print_error "Composer is not installed. Please install Composer first."
        exit 1
    fi

    # Check if php is installed
    if ! command -v php &> /dev/null; then
        print_error "PHP is not installed. Please install PHP first."
        exit 1
    fi

    # Check if mysql is installed
    if ! command -v mysql &> /dev/null; then
        print_error "MySQL client is not installed. Please install MySQL client first."
        exit 1
    fi

    # Check if .env.example exists
    if [ ! -f ".env.example" ]; then
        print_error ".env.example file not found. Please ensure you're in a Laravel project directory."
        exit 1
    fi

    print_success "Prerequisites check passed!"
}

# Function to validate database name
validate_db_name() {
    local dbname="$1"
    if [[ ! "$dbname" =~ ^[a-zA-Z][a-zA-Z0-9_]*$ ]]; then
        print_error "Invalid database name. Database name must start with a letter and contain only letters, numbers, and underscores."
        return 1
    fi
    if [ ${#dbname} -gt 64 ]; then
        print_error "Database name too long. Maximum length is 64 characters."
        return 1
    fi
    return 0
}

# Function to test database connection
test_db_connection() {
    local dbuser="$1"
    local dbpass="$2"

    print_status "Testing database connection..."
    if ! mysql -u"$dbuser" -p"$dbpass" -e "SELECT 1;" &> /dev/null; then
        print_error "Failed to connect to MySQL with provided credentials."
        return 1
    fi
    print_success "Database connection successful!"
    return 0
}

# Main setup function
main() {
    print_status "Starting Laravel project setup..."

    # Check prerequisites
    check_prerequisites

    print_status "Creating storage folders..."
    mkdir -p storage/framework/{cache,sessions,views} storage/logs
    chmod -R 775 storage
    chmod -R 775 bootstrap/cache
    print_success "Storage folders created and permissions set!"

    print_status "Copying .env file..."
    if [ -f ".env" ]; then
        print_warning ".env file already exists. Backing up to .env.backup"
        cp .env .env.backup
    fi
    cp .env.example .env
    print_success ".env file copied!"

    # database configuration
    echo
    print_status "Database Configuration"
    echo "=========================="

    # Default values
    dbuser="root"
    dbpass="52002"

    # Get database name with validation
    while true; do
        read -p "Database Name: " dbname
        if validate_db_name "$dbname"; then
            break
        fi
    done

    # Optional: Allow custom database credentials
    read -p "Database Username [default: root]: " custom_dbuser
    if [ -n "$custom_dbuser" ]; then
        dbuser="$custom_dbuser"
    fi

    read -s -p "Database Password [default: 52002]: " custom_dbpass
    echo
    if [ -n "$custom_dbpass" ]; then
        dbpass="$custom_dbpass"
    fi

    # Test database connection
    if ! test_db_connection "$dbuser" "$dbpass"; then
        exit 1
    fi

    # Update .env file
    print_status "Updating .env file..."
    sed -i "s/DB_DATABASE=.*/DB_DATABASE=${dbname}/" .env
    sed -i "s/DB_USERNAME=.*/DB_USERNAME=${dbuser}/" .env
    sed -i "s/DB_PASSWORD=.*/DB_PASSWORD=${dbpass}/" .env
    print_success ".env file updated!"

    # database creation
    print_status "Checking if database exists..."
    DB_EXISTS=$(mysql -u"${dbuser}" -p"${dbpass}" -e "SHOW DATABASES LIKE '${dbname}';" 2>/dev/null | grep "${dbname}" > /dev/null; echo $?)

    if [ $DB_EXISTS -ne 0 ]; then
        print_status "Creating database '${dbname}'..."
        if mysql -u"${dbuser}" -p"${dbpass}" -e "CREATE DATABASE \`${dbname}\`;"; then
            print_success "Database '${dbname}' created successfully!"
        else
            print_error "Failed to create database."
            exit 1
        fi
    else
        print_success "Database '${dbname}' already exists."
    fi

    # Composer and Laravel setup
    echo
    print_status "Installing Dependencies"
    echo "============================"

    print_status "Running composer update..."
    if composer update; then
        print_success "Dependencies installed!"
    else
        print_error "Composer update failed."
        exit 1
    fi

    print_status "Generating app key..."
    if php artisan key:generate; then
        print_success "App key generated!"
    else
        print_error "Failed to generate app key."
        exit 1
    fi

    print_status "Running migrations..."
    if php artisan migrate --seed; then
        print_success "Migrations completed!"
    else
        print_error "Migration failed."
        exit 1
    fi

    # Final setup
    print_status "Setting final permissions..."
    chmod -R 775 storage
    chmod -R 775 bootstrap/cache

    echo
    print_success "🎉 Setup completed successfully!"
    echo
    echo "Next steps:"
    echo "1. Run 'php artisan serve' to start the development server"
    echo "2. Visit http://localhost:8000 in your browser"
    echo "3. Check the .env file for any additional configuration"
}

# Cleanup function on exit
cleanup() {
    if [ $? -ne 0 ]; then
        print_error "Setup failed. Please check the error messages above."
    fi
}

# Set trap for cleanup
trap cleanup EXIT

# Run main function
main "$@"
