#!/bin/bash
# =====================================================
# AUTO REQUEST APPROVAL BOT - ONE-COMMAND INSTALLER
# =====================================================
# Usage: curl -sSL <your-raw-url>/install.sh | sudo bash
# Or:    sudo bash install.sh
# =====================================================

set -e

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

# Config
INSTALL_DIR="/var/www/bot"
REPO_URL="https://github.com/your-username/auto-request-approval.git"

echo -e "${BLUE}"
echo "╔═══════════════════════════════════════════════════╗"
echo "║   AUTO REQUEST APPROVAL BOT - VPS INSTALLER       ║"
echo "╚═══════════════════════════════════════════════════╝"
echo -e "${NC}"

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: Please run as root (sudo bash install.sh)${NC}"
    exit 1
fi

# =====================================================
# STEP 1: Collect Configuration
# =====================================================
echo -e "${YELLOW}[1/8] Configuration${NC}"
echo "---------------------------------------------------"

read -p "Enter your domain (e.g., bot.example.com): " DOMAIN
read -p "Enter your Telegram Bot Token: " BOT_TOKEN
read -p "Enter your Telegram User ID (Owner): " OWNER_ID
read -p "Enter Admin IDs (comma-separated, or press Enter for same as Owner): " ADMIN_IDS
ADMIN_IDS=${ADMIN_IDS:-$OWNER_ID}

read -p "Enter MySQL database name [telegram_bot]: " DB_NAME
DB_NAME=${DB_NAME:-telegram_bot}

read -p "Enter MySQL username [botuser]: " DB_USER
DB_USER=${DB_USER:-botuser}

read -sp "Enter MySQL password: " DB_PASS
echo ""

if [ -z "$DB_PASS" ]; then
    echo -e "${RED}Error: MySQL password cannot be empty${NC}"
    exit 1
fi

echo -e "${GREEN}✓ Configuration collected${NC}"
echo ""

# =====================================================
# STEP 2: Install System Dependencies
# =====================================================
echo -e "${YELLOW}[2/8] Installing dependencies...${NC}"
echo "---------------------------------------------------"

apt update && apt upgrade -y

# Install PHP 8.1 and extensions
apt install -y software-properties-common
add-apt-repository -y ppa:ondrej/php
apt update
apt install -y php8.1-fpm php8.1-mysql php8.1-curl php8.1-mbstring php8.1-xml unzip curl git

# Install MySQL
apt install -y mysql-server

# Install Nginx
apt install -y nginx

# Install Certbot
apt install -y certbot python3-certbot-nginx

echo -e "${GREEN}✓ Dependencies installed${NC}"
echo ""

# =====================================================
# STEP 3: Setup MySQL Database
# =====================================================
echo -e "${YELLOW}[3/8] Setting up database...${NC}"
echo "---------------------------------------------------"

mysql -e "CREATE DATABASE IF NOT EXISTS ${DB_NAME} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -e "CREATE USER IF NOT EXISTS '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';"
mysql -e "GRANT ALL PRIVILEGES ON ${DB_NAME}.* TO '${DB_USER}'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"

echo -e "${GREEN}✓ Database created${NC}"
echo ""

# =====================================================
# STEP 4: Clone/Setup Bot Files
# =====================================================
echo -e "${YELLOW}[4/8] Setting up bot files...${NC}"
echo "---------------------------------------------------"

mkdir -p $INSTALL_DIR

if [ -d "$INSTALL_DIR/.git" ]; then
    echo "Updating existing installation..."
    cd $INSTALL_DIR
    git pull
else
    echo "Fresh installation..."
    if [ -f "./composer.json" ]; then
        # Running from local directory
        cp -r ./* $INSTALL_DIR/
        cp -r ./.env.example $INSTALL_DIR/ 2>/dev/null || true
        cp -r ./.gitignore $INSTALL_DIR/ 2>/dev/null || true
    else
        # Clone from git
        git clone $REPO_URL $INSTALL_DIR
    fi
fi

cd $INSTALL_DIR

# Install Composer dependencies
if [ -f "composer.phar" ]; then
    php composer.phar install --no-dev --optimize-autoloader
else
    curl -sS https://getcomposer.org/installer | php
    php composer.phar install --no-dev --optimize-autoloader
fi

# Create logs directory
mkdir -p logs

echo -e "${GREEN}✓ Bot files ready${NC}"
echo ""

# =====================================================
# STEP 5: Configure Environment
# =====================================================
echo -e "${YELLOW}[5/8] Configuring environment...${NC}"
echo "---------------------------------------------------"

cat > $INSTALL_DIR/.env << EOF
# Telegram Bot Configuration
BOT_TOKEN=${BOT_TOKEN}

# MySQL Database Configuration
DB_HOST=localhost
DB_USER=${DB_USER}
DB_PASS=${DB_PASS}
DB_NAME=${DB_NAME}

# Bot Admin Configuration
ADMIN_IDS=${ADMIN_IDS}
OWNER_ID=${OWNER_ID}

# Logging level (debug, info, warning, error)
LOG_LEVEL=error

# New Features Configuration
CRON_SECRET=$(openssl rand -hex 16)
SITE_URL=https://${DOMAIN}
AUTO_REPLY_TEXT="Use /start to interact with the bot."
EOF

chmod 600 $INSTALL_DIR/.env

echo -e "${GREEN}✓ Environment configured${NC}"
echo ""

# =====================================================
# STEP 6: Import Database Schema
# =====================================================
echo -e "${YELLOW}[6/8] Importing database schema...${NC}"
echo "---------------------------------------------------"

mysql -u $DB_USER -p"$DB_PASS" $DB_NAME < $INSTALL_DIR/schema_install.sql

echo -e "${GREEN}✓ Database schema imported${NC}"
echo ""

# =====================================================
# STEP 7: Configure Nginx + SSL
# =====================================================
echo -e "${YELLOW}[7/8] Configuring Nginx and SSL...${NC}"
echo "---------------------------------------------------"

cat > /etc/nginx/sites-available/bot << EOF
server {
    listen 80;
    server_name ${DOMAIN};
    root ${INSTALL_DIR};
    index webhook.php;

    location / {
        try_files \$uri \$uri/ /webhook.php?\$query_string;
    }

    location ~ \.php\$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_read_timeout 300;
        fastcgi_send_timeout 300;
    }

    location ~ /\. {
        deny all;
    }
}
EOF

ln -sf /etc/nginx/sites-available/bot /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default 2>/dev/null || true

nginx -t && systemctl restart nginx

# Set proper permissions
chown -R www-data:www-data $INSTALL_DIR
chmod -R 755 $INSTALL_DIR
chmod 600 $INSTALL_DIR/.env
chmod 777 $INSTALL_DIR/logs

echo ""
echo -e "${YELLOW}Installing SSL certificate...${NC}"
certbot --nginx -d $DOMAIN --non-interactive --agree-tos --register-unsafely-without-email || {
    echo -e "${YELLOW}SSL installation requires manual setup. Run: sudo certbot --nginx -d ${DOMAIN}${NC}"
}

echo -e "${GREEN}✓ Nginx configured${NC}"
echo ""

# =====================================================
# STEP 8: Set Webhook & Cron
# =====================================================
echo -e "${YELLOW}[8/8] Final setup...${NC}"
echo "---------------------------------------------------"

# Set webhook with allowed_updates (chat_member is needed for channel farewell)
WEBHOOK_URL="https://${DOMAIN}/webhook.php"
WEBHOOK_RESPONSE=$(curl -s -X POST "https://api.telegram.org/bot${BOT_TOKEN}/setWebhook" \
    -d "url=${WEBHOOK_URL}" \
    -d 'allowed_updates=["message","callback_query","chat_join_request","my_chat_member","chat_member"]')
echo "Webhook: $WEBHOOK_RESPONSE"

# Set bot commands
COMMANDS='[{"command":"start","description":"Start the bot and open the main menu"}]'
curl -s "https://api.telegram.org/bot${BOT_TOKEN}/setMyCommands?commands=$COMMANDS" > /dev/null

# Setup Systemd Service (Robust Cron Runner)
echo "Setting up Systemd service..."

SERVICE_FILE="/etc/systemd/system/bot-cron.service"
cat > $SERVICE_FILE << EOF
[Unit]
Description=Telegram Bot Cron Runner
After=network.target mysql.service

[Service]
Type=simple
User=root
WorkingDirectory=${INSTALL_DIR}
ExecStart=/usr/bin/php ${INSTALL_DIR}/cron.php
Restart=always
RestartSec=60
StandardOutput=append:${INSTALL_DIR}/logs/cron.log
StandardError=append:${INSTALL_DIR}/logs/cron.log

[Install]
WantedBy=multi-user.target
EOF

# Reload and Start
systemctl daemon-reload
systemctl enable bot-cron
systemctl restart bot-cron

echo "Systemd service 'bot-cron' started."

echo -e "${GREEN}✓ Webhook and cron configured${NC}"
echo ""

# =====================================================
# DONE!
# =====================================================
echo -e "${GREEN}"
echo "╔═══════════════════════════════════════════════════╗"
echo "║          INSTALLATION COMPLETE! ✓                 ║"
echo "╚═══════════════════════════════════════════════════╝"
echo -e "${NC}"
echo ""
echo -e "Bot URL:     ${BLUE}https://${DOMAIN}${NC}"
echo -e "Webhook:     ${BLUE}https://${DOMAIN}/webhook.php${NC}"
echo -e "Install Dir: ${BLUE}${INSTALL_DIR}${NC}"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo "1. Send /start to your bot on Telegram"
echo "2. Add the bot as admin to your channel"
echo ""
echo -e "${YELLOW}Useful Commands:${NC}"
echo "  Updates:       cd $INSTALL_DIR && sudo ./deploy.sh"
echo "  View logs:     tail -f $INSTALL_DIR/logs/cron.log"
echo "  Cron Status:   systemctl status bot-cron"
echo "  Restart Cron:  systemctl restart bot-cron"
echo "  Edit config:   sudo nano $INSTALL_DIR/.env"
echo ""
