#!/bin/bash

# MikhMon WhatsApp Gateway - Quick Install Script
# For Linux/macOS

echo "=========================================="
echo "MikhMon WhatsApp Gateway Installer"
echo "=========================================="
echo ""

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is not installed!"
    echo "Please install Node.js first:"
    echo "https://nodejs.org/"
    exit 1
fi

echo "✅ Node.js version: $(node --version)"
echo "✅ NPM version: $(npm --version)"
echo ""

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    echo "❌ Error: package.json not found!"
    echo "Please run this script from whatsapp-gateway directory"
    exit 1
fi

# Install dependencies
echo "📦 Installing dependencies..."
npm install

if [ $? -ne 0 ]; then
    echo "❌ Failed to install dependencies"
    exit 1
fi

echo ""
echo "✅ Dependencies installed successfully!"
echo ""

# Create .env file if not exists
if [ ! -f ".env" ]; then
    echo "📝 Creating .env file..."
    cp .env.example .env
    
    # Generate random API key
    API_KEY=$(openssl rand -hex 32)
    
    # Update .env with random API key
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS
        sed -i '' "s/your-secret-api-key-change-this/$API_KEY/" .env
    else
        # Linux
        sed -i "s/your-secret-api-key-change-this/$API_KEY/" .env
    fi
    
    echo "✅ .env file created with random API key"
    echo ""
    echo "⚠️  IMPORTANT: Update your API key in MikhMon config:"
    echo "   File: mikhmon/include/whatsapp_config.php"
    echo "   API Key: $API_KEY"
    echo ""
else
    echo "ℹ️  .env file already exists, skipping..."
    echo ""
fi

# Create auth_info directory
if [ ! -d "auth_info" ]; then
    mkdir -p auth_info
    echo "✅ Created auth_info directory"
fi

echo ""
echo "=========================================="
echo "✅ Installation Complete!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Update API key in mikhmon/include/whatsapp_config.php"
echo "2. Start the gateway: npm start"
echo "3. Scan QR code in admin panel"
echo ""
echo "For production, use PM2:"
echo "  npm install -g pm2"
echo "  npm run pm2"
echo ""
echo "Admin Panel:"
echo "  http://localhost/mikhmon/settings/whatsapp_gateway_admin.php"
echo ""
echo "Documentation:"
echo "  See WHATSAPP_SELFHOSTED_GUIDE.md"
echo ""
