#!/bin/bash

# ═══════════════════════════════════════════════════════════════
# SMTP API Service - Auto Installer for easy-orders.co.uk
# ═══════════════════════════════════════════════════════════════

set -e

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

# Configuration
DOMAIN="easy-orders.co.uk"
PROJECT_DIR="/opt/smtp-api-service"
EMAIL="admin@easy-orders.co.uk"

print_status() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }

# Check root
if [ "$EUID" -ne 0 ]; then
    print_error "هذا السكريبت يجب تشغيله كـ root"
    exit 1
fi

clear
echo "═══════════════════════════════════════════════════════════════"
echo "    SMTP API Service - Auto Installer"
echo "    Domain: https://easy-orders.co.uk"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# ═══════════════════════════════════════════════════════════════
# Step 1: Update System
# ═══════════════════════════════════════════════════════════════
print_status "تحديث النظام..."
apt update -qq && apt upgrade -y -qq
print_success "تم تحديث النظام"

# ═══════════════════════════════════════════════════════════════
# Step 2: Install Dependencies
# ═══════════════════════════════════════════════════════════════
print_status "تثبيت المتطلبات..."
apt install -y -qq python3 python3-pip python3-venv nginx git curl wget unzip certbot python3-certbot-nginx ufw
print_success "تم تثبيت المتطلبات"

# ═══════════════════════════════════════════════════════════════
# Step 3: Create Project Directory
# ═══════════════════════════════════════════════════════════════
print_status "إعداد مجلد المشروع..."
mkdir -p $PROJECT_DIR
cd $PROJECT_DIR

# ═══════════════════════════════════════════════════════════════
# Step 4: Create Backend Files
# ═══════════════════════════════════════════════════════════════
print_status "إنشاء ملفات Backend..."
mkdir -p backend/data

# Create requirements.txt
cat > backend/requirements.txt << 'EOF'
fastapi==0.109.0
uvicorn[standard]==0.27.0
sqlalchemy==2.0.25
pydantic==2.5.3
pydantic-settings==2.1.0
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.6
email-validator==2.1.0
EOF

# Create .env
cat > backend/.env << EOF
APP_NAME="SMTP API Service"
APP_VERSION="1.0.0"
DEBUG=False
SECRET_KEY="$(openssl rand -base64 32)"
ALGORITHM="HS256"
ACCESS_TOKEN_EXPIRE_MINUTES=30
DATABASE_URL="sqlite:///./data/smtp_api.db"
DOMAIN="$DOMAIN"
BASE_URL="https://$DOMAIN"
EOF

print_success "تم إنشاء ملفات Backend"

# ═══════════════════════════════════════════════════════════════
# Step 5: Copy Backend Source Files
# ═══════════════════════════════════════════════════════════════
print_status "نسخ ملفات Backend..."

# Note: Backend Python files should be copied from the project
# For now, we'll create a minimal version

cat > backend/main.py << 'PYEOF'
from fastapi import FastAPI, Depends, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
import uvicorn

from database import create_tables, get_db, User
from auth import authenticate_user, create_access_token, get_password_hash, get_current_active_user
from api_key_service import create_api_key, get_user_api_keys, validate_api_key
from email_service import EmailService

app = FastAPI(
    title="SMTP API Service",
    description="Send emails via REST API",
    version="1.0.0",
    docs_url="/docs"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://easy-orders.co.uk", "https://www.easy-orders.co.uk"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.on_event("startup")
async def startup():
    create_tables()

@app.get("/")
async def root():
    return {"name": "SMTP API Service", "version": "1.0.0", "domain": "easy-orders.co.uk"}

@app.get("/health")
async def health():
    return {"status": "healthy"}

# Auth endpoints
@app.post("/api/v1/auth/register")
async def register(data, db: Session = Depends(get_db)):
    user = User(email=data.email, username=data.username, 
                hashed_password=get_password_hash(data.password), is_active=True)
    db.add(user)
    db.commit()
    return user

@app.post("/api/v1/auth/login")
async def login(data, db: Session = Depends(get_db)):
    user = authenticate_user(db, data.username, data.password)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    token = create_access_token({"sub": user.username})
    return {"access_token": token, "token_type": "bearer"}

@app.get("/api/v1/auth/me")
async def me(current_user: User = Depends(get_current_active_user)):
    return current_user

# API Keys
@app.post("/api/v1/api-keys")
async def create_key(data, current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    return create_api_key(db, current_user.id, data.name)

@app.get("/api/v1/api-keys")
async def list_keys(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    return get_user_api_keys(db, current_user.id)

# SMTP Configs
@app.get("/api/v1/smtp-configs")
async def list_smtp(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    service = EmailService(db)
    return service.get_all_user_smtp_configs(current_user.id)

# Email
@app.post("/api/v1/emails/send")
async def send_email(data, current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    service = EmailService(db)
    return service.send_email(current_user.id, data)

# Public API
@app.post("/api/v1/public/send-email")
async def public_send(data, db: Session = Depends(get_db)):
    key = validate_api_key(db, data.api_key)
    if not key:
        raise HTTPException(status_code=401, detail="Invalid API key")
    service = EmailService(db)
    return service.send_email_with_api_key(key, data.dict(exclude={'api_key'}))

# Dashboard
@app.get("/api/v1/dashboard/stats")
async def stats(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    service = EmailService(db)
    email_stats = service.get_email_stats(current_user.id)
    return {
        "total_emails_sent": email_stats["total_sent"],
        "emails_sent_today": email_stats["today_sent"],
        "active_api_keys": len([k for k in current_user.api_keys if k.is_active]),
        "smtp_configs": len(current_user.smtp_configs),
        "recent_emails": service.get_email_logs(current_user.id, 10)
    }

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, workers=4)
PYEOF

# Create other backend files
cat > backend/database.py << 'DBEOF'
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, Text, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime

engine = create_engine("sqlite:///./data/smtp_api.db", connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True)
    username = Column(String, unique=True)
    hashed_password = Column(String)
    full_name = Column(String)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    api_keys = relationship("ApiKey", back_populates="user")
    smtp_configs = relationship("SMTPConfig", back_populates="user")
    email_logs = relationship("EmailLog", back_populates="user")

class ApiKey(Base):
    __tablename__ = "api_keys"
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    key_name = Column(String)
    api_key = Column(String, unique=True)
    is_active = Column(Boolean, default=True)
    usage_count = Column(Integer, default=0)
    user = relationship("User", back_populates="api_keys")

class SMTPConfig(Base):
    __tablename__ = "smtp_configs"
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    name = Column(String)
    host = Column(String)
    port = Column(Integer)
    username = Column(String)
    password = Column(String)
    use_tls = Column(Boolean, default=True)
    is_default = Column(Boolean, default=False)
    user = relationship("User", back_populates="smtp_configs")

class EmailLog(Base):
    __tablename__ = "email_logs"
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    to_email = Column(String)
    subject = Column(String)
    status = Column(String)
    sent_at = Column(DateTime, default=datetime.utcnow)
    user = relationship("User", back_populates="email_logs")

def create_tables():
    Base.metadata.create_all(bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
DBEOF

cat > backend/auth.py << 'ATHEOF'
from datetime import datetime, timedelta
from jose import jwt
from passlib.context import CryptContext
from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer
from sqlalchemy.orm import Session
from database import get_db, User

SECRET_KEY = "change-this-in-production"
ALGORITHM = "HS256"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
security = HTTPBearer()

def verify_password(plain, hashed):
    return pwd_context.verify(plain, hashed)

def get_password_hash(password):
    return pwd_context.hash(password)

def create_access_token(data):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=30)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

def decode_token(token):
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except:
        return None

async def get_current_user(credentials, db: Session = Depends(get_db)):
    payload = decode_token(credentials.credentials)
    if not payload:
        raise HTTPException(status_code=401, detail="Invalid token")
    user = db.query(User).filter(User.username == payload.get("sub")).first()
    if not user:
        raise HTTPException(status_code=401, detail="User not found")
    return user

async def get_current_active_user(current_user: User = Depends(get_current_user)):
    if not current_user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user

def authenticate_user(db, username, password):
    user = db.query(User).filter(User.username == username).first()
    if not user or not verify_password(password, user.hashed_password):
        return None
    return user
ATHEOF

cat > backend/api_key_service.py << 'KEYEOF'
import secrets, string
from sqlalchemy.orm import Session
from database import ApiKey
from datetime import datetime

def generate_api_key():
    alphabet = string.ascii_letters + string.digits
    return "smtp_" + "".join(secrets.choice(alphabet) for _ in range(32))

def create_api_key(db: Session, user_id: int, name: str):
    key = ApiKey(user_id=user_id, key_name=name, api_key=generate_api_key())
    db.add(key)
    db.commit()
    db.refresh(key)
    return key

def get_user_api_keys(db: Session, user_id: int):
    return db.query(ApiKey).filter(ApiKey.user_id == user_id).all()

def validate_api_key(db: Session, api_key: str):
    key = db.query(ApiKey).filter(ApiKey.api_key == api_key, ApiKey.is_active == True).first()
    if key:
        key.usage_count += 1
        db.commit()
    return key
KEYEOF

cat > backend/email_service.py << 'MAILEOF'
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from sqlalchemy.orm import Session
from database import SMTPConfig, EmailLog
from datetime import datetime

class EmailService:
    def __init__(self, db: Session):
        self.db = db
    
    def get_user_smtp_config(self, user_id: int):
        return self.db.query(SMTPConfig).filter(
            SMTPConfig.user_id == user_id,
            SMTPConfig.is_default == True
        ).first()
    
    def get_all_user_smtp_configs(self, user_id: int):
        return self.db.query(SMTPConfig).filter(SMTPConfig.user_id == user_id).all()
    
    def send_email(self, user_id: int, email_data):
        smtp = self.get_user_smtp_config(user_id)
        if not smtp:
            return {"success": False, "message": "No SMTP config"}
        
        try:
            msg = MIMEMultipart()
            msg['Subject'] = email_data.subject
            msg['From'] = smtp.username
            msg['To'] = email_data.to_email
            msg.attach(MIMEText(email_data.body, 'plain', 'utf-8'))
            
            with smtplib.SMTP(smtp.host, smtp.port) as server:
                server.starttls(context=ssl.create_default_context())
                server.login(smtp.username, smtp.password)
                server.send_message(msg)
            
            log = EmailLog(user_id=user_id, to_email=email_data.to_email, 
                          subject=email_data.subject, status="sent")
            self.db.add(log)
            self.db.commit()
            return {"success": True, "message": "Email sent"}
        except Exception as e:
            return {"success": False, "message": str(e)}
    
    def send_email_with_api_key(self, key, data):
        return self.send_email(key.user_id, type('obj', (object,), data)())
    
    def get_email_logs(self, user_id: int, limit: int = 50):
        return self.db.query(EmailLog).filter(EmailLog.user_id == user_id).order_by(EmailLog.sent_at.desc()).limit(limit).all()
    
    def get_email_stats(self, user_id: int):
        sent = self.db.query(EmailLog).filter(EmailLog.user_id == user_id, EmailLog.status == "sent").count()
        today = datetime.utcnow().replace(hour=0, minute=0, second=0)
        today_sent = self.db.query(EmailLog).filter(EmailLog.user_id == user_id, EmailLog.status == "sent", EmailLog.sent_at >= today).count()
        return {"total_sent": sent, "today_sent": today_sent}
MAILEOF

print_success "تم نسخ ملفات Backend"

# ═══════════════════════════════════════════════════════════════
# Step 6: Setup Python Environment
# ═══════════════════════════════════════════════════════════════
print_status "إعداد البيئة الافتراضية..."
cd $PROJECT_DIR/backend
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip -q
pip install -r requirements.txt -q
print_success "تم تثبيت المتطلبات"

# ═══════════════════════════════════════════════════════════════
# Step 7: Setup Frontend
# ═══════════════════════════════════════════════════════════════
print_status "إعداد Frontend..."
mkdir -p /var/www/easy-orders

# Create a simple frontend
cat > /var/www/easy-orders/index.html << 'HTMLEOF'
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMTP API Service - easy-orders.co.uk</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap'); body { font-family: 'Cairo', sans-serif; }</style>
</head>
<body class="bg-gray-100">
    <div id="app"></div>
    <script>
        const API_BASE_URL = 'https://easy-orders.co.uk/api/v1';
        let token = localStorage.getItem('token');
        
        async function apiRequest(endpoint, options = {}) {
            const res = await fetch(API_BASE_URL + endpoint, {
                headers: { 'Content-Type': 'application/json', ...(token && { 'Authorization': 'Bearer ' + token }) },
                ...options,
                body: options.body ? JSON.stringify(options.body) : undefined
            });
            const data = await res.json();
            if (!res.ok) throw new Error(data.detail || 'Error');
            return data;
        }
        
        function showLogin() {
            document.getElementById('app').innerHTML = `
                <div class="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-500 to-purple-600 p-4">
                    <div class="bg-white rounded-2xl shadow-2xl p-8 w-full max-w-md">
                        <div class="text-center mb-8">
                            <div class="w-20 h-20 bg-blue-600 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-envelope text-3xl text-white"></i>
                            </div>
                            <h1 class="text-3xl font-bold text-gray-800">SMTP API Service</h1>
                            <p class="text-gray-500">easy-orders.co.uk</p>
                        </div>
                        <form id="loginForm" class="space-y-4">
                            <input type="text" id="username" placeholder="Username" class="w-full p-3 border rounded-lg" required>
                            <input type="password" id="password" placeholder="Password" class="w-full p-3 border rounded-lg" required>
                            <button type="submit" class="w-full bg-blue-600 text-white py-3 rounded-lg font-semibold">Login</button>
                        </form>
                        <div class="mt-4 text-center">
                            <a href="#/register" class="text-blue-600">Create account</a>
                        </div>
                    </div>
                </div>`;
            
            document.getElementById('loginForm').addEventListener('submit', async (e) => {
                e.preventDefault();
                try {
                    const data = await apiRequest('/auth/login', { method: 'POST', body: { username: document.getElementById('username').value, password: document.getElementById('password').value } });
                    token = data.access_token;
                    localStorage.setItem('token', token);
                    window.location.hash = '/dashboard';
                } catch (err) {
                    alert(err.message);
                }
            });
        }
        
        async function showDashboard() {
            const stats = await apiRequest('/dashboard/stats');
            document.getElementById('app').innerHTML = `
                <div class="min-h-screen">
                    <header class="bg-white shadow p-4 flex justify-between items-center">
                        <div class="flex items-center gap-2">
                            <i class="fas fa-envelope text-blue-600 text-xl"></i>
                            <span class="font-bold">SMTP API Service</span>
                        </div>
                        <button onclick="logout()" class="text-gray-600"><i class="fas fa-sign-out-alt"></i></button>
                    </header>
                    <div class="p-8">
                        <div class="grid grid-cols-4 gap-4 mb-8">
                            <div class="bg-white p-6 rounded-xl shadow">
                                <p class="text-gray-500">Emails Sent</p>
                                <p class="text-3xl font-bold text-blue-600">${stats.total_emails_sent || 0}</p>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow">
                                <p class="text-gray-500">Today</p>
                                <p class="text-3xl font-bold text-green-600">${stats.emails_sent_today || 0}</p>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow">
                                <p class="text-gray-500">API Keys</p>
                                <p class="text-3xl font-bold text-purple-600">${stats.active_api_keys || 0}</p>
                            </div>
                            <div class="bg-white p-6 rounded-xl shadow">
                                <p class="text-gray-500">SMTP Configs</p>
                                <p class="text-3xl font-bold text-orange-600">${stats.smtp_configs || 0}</p>
                            </div>
                        </div>
                        <div class="bg-white p-6 rounded-xl shadow">
                            <h3 class="text-xl font-bold mb-4">Quick Actions</h3>
                            <div class="flex gap-4">
                                <button onclick="alert('Coming soon')" class="px-4 py-2 bg-blue-600 text-white rounded">Send Email</button>
                                <button onclick="alert('Coming soon')" class="px-4 py-2 bg-purple-600 text-white rounded">API Keys</button>
                                <button onclick="alert('Coming soon')" class="px-4 py-2 bg-orange-600 text-white rounded">SMTP Settings</button>
                            </div>
                        </div>
                    </div>
                </div>`;
        }
        
        function logout() { token = null; localStorage.removeItem('token'); window.location.hash = '/'; }
        
        function router() {
            const path = window.location.hash.slice(1) || '/';
            if (!token && path !== '/register') showLogin();
            else if (path === '/dashboard' || path === '/') showDashboard();
            else showLogin();
        }
        
        window.logout = logout;
        window.addEventListener('hashchange', router);
        window.addEventListener('load', router);
    </script>
</body>
</html>
HTMLEOF

print_success "تم إعداد Frontend"

# ═══════════════════════════════════════════════════════════════
# Step 8: Setup Nginx
# ═══════════════════════════════════════════════════════════════
print_status "إعداد Nginx..."

mkdir -p /etc/nginx/sites-available

cat > /etc/nginx/sites-available/easy-orders << 'NGINXCONF'
server {
    listen 80;
    server_name easy-orders.co.uk www.easy-orders.co.uk;
    
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }
    
    location / {
        return 301 https://$server_name$request_uri;
    }
}

server {
    listen 443 ssl http2;
    server_name easy-orders.co.uk www.easy-orders.co.uk;
    
    ssl_certificate /etc/letsencrypt/live/easy-orders.co.uk/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/easy-orders.co.uk/privkey.pem;
    
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    
    location / {
        root /var/www/easy-orders;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
    
    location /api/ {
        proxy_pass http://127.0.0.1:8000/api/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    location /docs {
        proxy_pass http://127.0.0.1:8000/docs;
        proxy_set_header Host $host;
    }
}
NGINXCONF

ln -sf /etc/nginx/sites-available/easy-orders /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl restart nginx
print_success "تم إعداد Nginx"

# ═══════════════════════════════════════════════════════════════
# Step 9: Setup SSL
# ═══════════════════════════════════════════════════════════════
print_status "إعداد SSL..."
mkdir -p /var/www/certbot

print_warning "سنحصل على شهادة SSL الآن. تأكد من أن النطاق يشير لهذا السيرفر."
print_status "جاري الحصول على شهادة SSL من Let's Encrypt..."

certbot --nginx -d easy-orders.co.uk -d www.easy-orders.co.uk --non-interactive --agree-tos -m admin@easy-orders.co.uk --redirect 2>/dev/null || {
    print_warning "تعذر الحصول على SSL تلقائياً. قم بتشغيل: certbot --nginx -d easy-orders.co.uk"
}

# ═══════════════════════════════════════════════════════════════
# Step 10: Setup Systemd Service
# ═══════════════════════════════════════════════════════════════
print_status "إعداد خدمة systemd..."

cat > /etc/systemd/system/smtp-api.service << SERVICEEOF
[Unit]
Description=SMTP API Service for easy-orders.co.uk
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$PROJECT_DIR/backend
Environment="PATH=$PROJECT_DIR/backend/venv/bin"
ExecStart=$PROJECT_DIR/backend/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 4
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
SERVICEEOF

systemctl daemon-reload
systemctl enable smtp-api
systemctl start smtp-api
print_success "تم إعداد الخدمة"

# ═══════════════════════════════════════════════════════════════
# Step 11: Setup Firewall
# ═══════════════════════════════════════════════════════════════
print_status "إعداد جدار الحماية..."
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable
print_success "تم إعداد جدار الحماية"

# ═══════════════════════════════════════════════════════════════
# Done
# ═══════════════════════════════════════════════════════════════
echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "           ✅ تم التثبيت بنجاح!"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "📌 روابط مهمة:"
echo "   • الموقع: https://easy-orders.co.uk"
echo "   • API Docs: https://easy-orders.co.uk/docs"
echo ""
echo "📌 أوامر مفيدة:"
echo "   • عرض السجلات: sudo journalctl -u smtp-api -f"
echo "   • إعادة تشغيل: sudo systemctl restart smtp-api"
echo "   • حالة الخدمة: sudo systemctl status smtp-api"
echo ""
echo "═══════════════════════════════════════════════════════════════"
