#!/bin/bash
# Load settings from DB using a temporary PHP script
SETTINGS=$(php -r "require '../db/config.php'; \$s = []; \$stmt = db()->query('SELECT setting_key, setting_value FROM bot_settings'); while(\$row = \$stmt->fetch()) \$s[\$row['setting_key']] = \$row['setting_value']; echo json_encode(\$s);")

DISCORD_TOKEN=$(echo $SETTINGS | php -r "echo json_decode(file_get_contents('php://stdin'), true)['discord_token'] ?? '';")
VC_ID=$(echo $SETTINGS | php -r "echo json_decode(file_get_contents('php://stdin'), true)['voice_channel_id'] ?? '';")
SAHUR_TIME=$(echo $SETTINGS | php -r "echo json_decode(file_get_contents('php://stdin'), true)['sahur_time'] ?? '';")
CLIENT_ID=$(echo $SETTINGS | php -r "echo json_decode(file_get_contents('php://stdin'), true)['client_id'] ?? '';")

if [ -z "$DISCORD_TOKEN" ]; then
    echo "Error: Discord Token is missing in settings."
    exit 1
fi

# Kill previous instances
pkill -f "node index.js" || true

# Add ffmpeg-static to PATH
export PATH="$PATH:$(pwd)/node_modules/ffmpeg-static"

# Start bot with PM2 for "jalan selamanya"
# We pass environment variables to PM2
DISCORD_TOKEN="$DISCORD_TOKEN" VC_ID="$VC_ID" SAHUR_TIME="$SAHUR_TIME" CLIENT_ID="$CLIENT_ID" pm2 start index.js --name "sahur-bot" --log bot.log --force
echo "Bot started with PM2."
