# Deployment Guide

This guide provides step-by-step instructions for deploying your Laravel Telegram Bot to production and setting up development environments.

## 🚀 Production Deployment Workflow

### Step 1: Upload and Prepare

1. **Upload Code to cPanel**
   ```bash
   # Upload the entire project to your hosting directory
   # Usually public_html/ or a subdomain folder
   ```

2. **Set File Permissions**
   ```bash
   chmod -R 755 storage/
   chmod -R 755 bootstrap/cache/
   ```

### Step 2: Database Setup

1. **Create MySQL Database in cPanel**
   - Go to cPanel → MySQL Databases
   - Create new database: `your_database_name`
   - Create database user with full privileges
   - Note down: database name, username, password

### Step 3: Install Dependencies

```bash
# Navigate to your project directory in cPanel Terminal
cd public_html/your-bot-directory

# Install PHP dependencies
composer install --optimize-autoloader --no-dev

# Install Node.js dependencies (if needed)
npm install --production
```

### Step 4: Interactive Setup

Run the interactive setup wizard:

```bash
php artisan bot:setup --interactive
```

This will guide you through:

1. **Environment Check**
   - PHP version validation
   - Required extensions check
   - File permissions verification

2. **Database Configuration**
   - Database host, port, name
   - Database username and password
   - Connection testing

3. **Telegram Bot Configuration**
   - Bot token from @BotFather
   - Application URL for webhook
   - Bot validation

4. **Application Configuration**
   - Application name and environment
   - Debug mode settings
   - Security key generation

5. **Installation Process**
   - Dependency installation
   - Database migrations
   - Application optimization

6. **Testing & Finalization**
   - Webhook setup
   - Admin user creation
   - Configuration verification

### Step 5: Access Admin Panel

1. Navigate to: `https://yourdomain.com/admin`
2. Configure modules and settings
3. Test bot functionality

## 🛡️ Setting Telegram Webhook

### Automatic Setup (Recommended)

The setup wizard handles webhook configuration automatically. You can also manage it manually:

```bash
# Set webhook
php artisan telegram:set-webhook

# Check webhook status
php artisan telegram:info

# Remove webhook
php artisan telegram:remove-webhook
```

### Manual Webhook Setup

If you need to set the webhook manually:

```bash
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
     -H "Content-Type: application/json" \
     -d '{"url": "https://yourdomain.com/api/telegram/webhook"}'
```

### Webhook Requirements

- ✅ **HTTPS Required**: Telegram only accepts HTTPS URLs
- ✅ **Valid SSL Certificate**: Must be properly configured
- ✅ **Port 443 or 8443**: Standard HTTPS ports only
- ✅ **Response Time**: Must respond within 60 seconds
- ✅ **Response Format**: Must return 200 OK status

## 🔧 Development Environment Setup

### Local Development with Webhook Testing

For testing real Telegram interactions in development:

```bash
# Start development webhook with auto-tunneling
php artisan dev:webhook start

# Using specific tunnel service
php artisan dev:webhook start --ngrok
php artisan dev:webhook start --expose

# Check status
php artisan dev:webhook status

# Stop development webhook
php artisan dev:webhook stop
```

### Development Prerequisites

Install one of these tunneling tools:

#### Option 1: ngrok (Recommended)
```bash
# Download from https://ngrok.com/download
# Or install via package manager:
brew install ngrok  # macOS
snap install ngrok   # Linux
```

#### Option 2: Laravel Expose
```bash
composer global require beyondcode/expose
```

### Development Workflow

1. **Start Development Server**
   ```bash
   php artisan dev:webhook start
   ```

2. **Test Your Bot**
   - Send `/start` to your bot on Telegram
   - Check webhook delivery in logs
   - Test all bot commands and features

3. **Access Local Admin Panel**
   - Open the provided tunnel URL + `/admin`
   - Configure modules and test functionality

4. **Stop When Done**
   ```bash
   php artisan dev:webhook stop
   ```

## 📋 Post-Deployment Checklist

### Essential Checks

- [ ] **Bot Responds**: Send `/start` to test basic functionality
- [ ] **Admin Panel**: Access and login to admin interface
- [ ] **Database**: Verify all tables are created
- [ ] **Webhooks**: Confirm webhook is receiving updates
- [ ] **Modules**: Check all modules are working
- [ ] **Logs**: Review error logs for issues

### Performance Checks

```bash
# Check overall bot status
php artisan bot:status --detailed

# Monitor system resources
php artisan system:info

# Test specific functionality
php artisan bot:test
```

### Security Verification

- [ ] **Environment File**: `.env` file is not web-accessible
- [ ] **Debug Mode**: Disabled in production (`APP_DEBUG=false`)
- [ ] **HTTPS**: All URLs use HTTPS protocol
- [ ] **File Permissions**: Proper file and directory permissions
- [ ] **Admin Access**: Only authorized users have admin privileges

## 🔄 Continuous Deployment

### Auto-Deploy Script

Create `deploy.sh` for easy updates:

```bash
#!/bin/bash
cd /path/to/your/bot

# Pull latest code
git pull origin main

# Install/update dependencies
composer install --optimize-autoloader --no-dev

# Run migrations
php artisan migrate --force

# Clear and optimize caches
php artisan optimize

# Restart queue workers (if using)
php artisan queue:restart

echo "Deployment completed successfully!"
```

### Environment-Specific Configuration

#### Production Settings (.env)
```env
APP_ENV=production
APP_DEBUG=false
LOG_LEVEL=warning
SESSION_DRIVER=database
CACHE_DRIVER=file
QUEUE_CONNECTION=database
```

#### Staging Settings (.env.staging)
```env
APP_ENV=staging
APP_DEBUG=true
LOG_LEVEL=debug
```

## 🛠️ Troubleshooting

### Common Issues

#### 1. Webhook Not Working
```bash
# Check webhook status
php artisan telegram:info

# Verify URL accessibility
curl -I https://yourdomain.com/api/telegram/webhook

# Check server logs
tail -f storage/logs/laravel.log
```

#### 2. Database Connection Issues
```bash
# Test database connection
php artisan tinker
>>> DB::connection()->getPdo();

# Check .env database settings
cat .env | grep DB_
```

#### 3. Permission Errors
```bash
# Fix storage permissions
chmod -R 755 storage/
chown -R www-data:www-data storage/

# Fix bootstrap cache permissions
chmod -R 755 bootstrap/cache/
```

#### 4. Composer/Dependencies Issues
```bash
# Clear composer cache
composer clear-cache

# Reinstall dependencies
rm -rf vendor/
composer install --optimize-autoloader --no-dev
```

### Debug Mode

Enable debug mode temporarily for troubleshooting:

```bash
# Enable debug mode
php artisan down --secret="debug-token"
# Set APP_DEBUG=true in .env
# Test functionality
# Set APP_DEBUG=false in .env
php artisan up
```

### Log Analysis

Monitor application logs:

```bash
# Real-time log monitoring
tail -f storage/logs/laravel.log

# Search for specific errors
grep "ERROR" storage/logs/laravel-$(date +%Y-%m-%d).log

# Check webhook-specific logs
grep "telegram" storage/logs/laravel.log
```

## 📈 Monitoring & Maintenance

### Health Checks

Set up automated health checks:

```bash
# Add to crontab for regular health checks
*/5 * * * * /path/to/your/bot/artisan bot:status > /dev/null 2>&1
```

### Backup Strategy

```bash
# Database backup
mysqldump -u username -p database_name > backup_$(date +%Y%m%d).sql

# File backup
tar -czf bot_backup_$(date +%Y%m%d).tar.gz /path/to/your/bot
```

### Performance Optimization

```bash
# Optimize application
php artisan optimize

# Cache configuration
php artisan config:cache

# Cache routes
php artisan route:cache

# Cache views
php artisan view:cache
```

## 🎯 Quick Reference Commands

### Setup & Installation
```bash
php artisan bot:setup --interactive  # Complete setup wizard
php artisan migrate --force          # Run database migrations
php artisan optimize                 # Optimize application
```

### Telegram Management
```bash
php artisan telegram:set-webhook     # Set production webhook
php artisan telegram:info            # Get bot information
php artisan dev:webhook start        # Start development webhook
```

### Status & Monitoring
```bash
php artisan bot:status               # Check bot status
php artisan system:info              # System information
php artisan queue:work               # Start queue processing
```

### Development Tools
```bash
php artisan make:module ModuleName   # Create new module
php artisan bot:test                 # Run bot tests
php artisan tinker                   # Interactive console
```

This deployment guide ensures your Telegram bot is properly set up, secure, and ready for production use while providing excellent development experience with local webhook testing capabilities.