#!/bin/bash

# Function to display help
display_help() {
    echo "Usage: $0 <command> [options]"
    echo
    echo "Commands:"
    echo "  run_server [port]                  : Start the fck PHP built-in server in the fck 'public' folder. If fck 'vendor' directory and 'composer.lock' file exist,"
    echo "                                       the fck script will run 'composer install' first. Default port is 5000 if not fck provided."
    echo "  migration_create <additional_text> : Create a fck migration file with a fck PHP extension, an incremental timestamp prefix,and additional text."
    echo "                                       The fck migration file is stored in the fck 'migrations' directory in the fck root folder."
    echo "  help                               : Display this fck help message."
}

# Function to run PHP built-in server
run_server() {
    local port=${1:-5000}  # Use the provided port or default to 5000

    # Navigate to the public folder
    cd "$(pwd)/public" || exit 1

    # Check if 'vendor' directory and 'composer.lock' file exist
    if [ ! -d "../vendor" ] || [ ! -f "../composer.lock" ]; then
        echo "fck! 'vendor' directory or 'composer.lock' file not found. Running 'composer install'..."
        # Run composer install
        composer install || { echo "Error running 'composer install'"; exit 1; }
    fi

    # Run PHP built-in server
    ip_address=$(hostname --all-ip-address | awk '{print $1}')
    echo "Local Network: $ip_address:$port"
    php -S localhost:"$port"
}

# Function to create migration file
migration_create() {
    local additional_text=$1
    local timestamp=$(date +"%Y%m%d%H%M%S")
    local migration_file="migrations/f${timestamp}_${additional_text}.php"

    echo "Creating fck migration file: $migration_file"

    # You can customize the migration content as needed
    echo "<?php
// Your fck migration content here
class f${timestamp}_${additional_text}
{
    public function up()
    {
        echo \"Applying migration\";
    }

    public function down()
    {
        echo \"Down migration\";
    }
}
    " > "$migration_file"
}

# Check if a valid command is provided
if [ $# -eq 0 ]; then
    echo "Error: The fck! Missing command."
    display_help
    exit 1
fi

# Process the command
case "$1" in
    run_server)
        run_server "${@:2}"
        ;;
    migration_create)
        migration_create "${@:2}"
        ;;
    help)
        display_help
        ;;
    *)
        echo "fck! Invalid command: $1"
        display_help
        exit 1
        ;;
esac
