# 📱 راهنمای یکپارچه‌سازی اپلیکیشن اندروید با پنل

## 🎯 معماری کلی

اپلیکیشن اندروید با استفاده از **Retrofit** به APIهای پنل متصل می‌شود و تمام قابلیت‌های پنل را در اختیار کاربر قرار می‌دهد.

```
┌─────────────────┐         ┌──────────────────┐         ┌─────────────────┐
│   Android App   │ <-----> │   Backend API    │ <-----> │   Database      │
│   (Java/Kotlin) │  HTTPS  │   (PHP/MySQL)    │         │   (MySQL)       │
└─────────────────┘         └──────────────────┘         └─────────────────┘
```

---

## 📋 APIهای موجود برای اپلیکیشن

### 1️⃣ **احراز هویت**

#### Login
```http
POST /backend/api/auth/login.php
Content-Type: application/json

{
  "username": "user@example.com",
  "password": "password123"
}

Response:
{
  "success": true,
  "message": "ورود موفقیت‌آمیز بود",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "user": {
      "id": 1,
      "username": "user@example.com",
      "email": "user@example.com",
      "full_name": "علی احمدی"
    }
  }
}
```

#### Register
```http
POST /backend/api/auth/register.php
Content-Type: application/json

{
  "username": "newuser",
  "email": "newuser@example.com",
  "password": "password123",
  "full_name": "کاربر جدید",
  "referral_code": "ABC123"
}
```

---

### 2️⃣ **داشبورد اپ (تمام اطلاعات در یک درخواست)**

```http
GET /backend/api/app/dashboard.php
Authorization: Bearer {token}

Response:
{
  "success": true,
  "data": {
    "user": { ... },
    "subscription": {
      "id": 5,
      "plan_name": "حرفه‌ای",
      "expiry_date": "2024-04-20",
      "traffic_limit": 107374182400,
      "traffic_used": 21474836480,
      "status": "active"
    },
    "servers": [
      {
        "id": 1,
        "name": "US East 1",
        "location": "نیویورک",
        "ip_address": "192.168.1.100",
        "status": "active",
        "current_users": 234,
        "max_users": 500,
        "configs": [
          {
            "id": 1,
            "protocol": "v2ray",
            "config": "vmess://eyJhZGQiOi...",
            "remarks": "کانفیگ اصلی"
          }
        ]
      }
    ],
    "stats": {
      "total_traffic": 21474836480,
      "connection_days": 15,
      "last_connection": "2024-03-20 14:30:00"
    },
    "plans": [ ... ],
    "tickets": [ ... ]
  }
}
```

---

### 3️⃣ **اتصال به VPN**

#### Connect
```http
POST /backend/api/app/connect.php
Authorization: Bearer {token}
Content-Type: application/json

{
  "server_id": 1,
  "config_id": 2  // اختیاری - برای کانفیگ دستی
}

Response:
{
  "success": true,
  "data": {
    "config": "vmess://eyJhZGQiOiIxOTIuMTY4LjEuMTAwIiwicG9ydCI6NDQzfQ==",
    "protocol": "v2ray",
    "server_info": {
      "id": 1,
      "name": "US East 1",
      "location": "نیویورک",
      "ip": "192.168.1.100",
      "port": 443
    }
  }
}
```

#### Disconnect
```http
POST /backend/api/app/disconnect.php
Authorization: Bearer {token}
Content-Type: application/json

{
  "server_id": 1,
  "connection_id": 123
}

Response:
{
  "success": true,
  "data": {
    "duration_seconds": 3600
  }
}
```

---

### 4️⃣ **مدیریت اشتراک**

#### Get My Subscriptions
```http
GET /backend/api/subscriptions/my-subscriptions.php
Authorization: Bearer {token}
```

#### Get Available Plans
```http
GET /backend/api/plans/list.php
```

#### Purchase Plan (پرداخت)
```http
POST /backend/api/payment/zarinpal.php
Authorization: Bearer {token}
Content-Type: application/json

{
  "plan_id": 2,
  "payment_method": "zarinpal",
  "callback_url": "vpnpanel://payment/callback"
}

Response:
{
  "success": true,
  "data": {
    "payment_url": "https://zarinpal.com/pg/StartPay/A00000000000000000000000000123456789",
    "authority": "A00000000000000000000000000123456789"
  }
}
```

---

### 5️⃣ **پروفایل کاربر**

```http
GET /backend/api/users/profile.php
Authorization: Bearer {token}

PUT /backend/api/users/profile.php
Authorization: Bearer {token}
Content-Type: application/json

{
  "full_name": "علی احمدی",
  "email": "ali@example.com",
  "phone": "09123456789"
}
```

---

### 6️⃣ **تیکت‌ها**

#### Create Ticket
```http
POST /backend/api/tickets/create.php
Authorization: Bearer {token}
Content-Type: application/json

{
  "subject": "مشکل در اتصال",
  "message": "نمی‌تونم به سرور آمریکا وصل بشم",
  "category": "technical",
  "priority": "high"
}
```

#### Get My Tickets
```http
GET /backend/api/tickets/list.php?status=open
Authorization: Bearer {token}
```

#### Reply to Ticket
```http
POST /backend/api/tickets/reply.php
Authorization: Bearer {token}
Content-Type: application/json

{
  "ticket_id": 5,
  "message": "مشکل حل شد، ممنون"
}
```

---

## 🛠️ نحوه استفاده در اپلیکیشن Android

### 1. تنظیمات اولیه

```java
// در Application class یا MainActivity.onCreate()
ApiClient.init(this);
```

### 2. لاگین کاربر

```java
ApiService apiService = ApiClient.getClient().create(ApiService.class);

LoginRequest request = new LoginRequest("user@example.com", "password123");
apiService.login(request).enqueue(new Callback<LoginResponse>() {
    @Override
    public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            String token = response.body().token;
            
            // ذخیره توکن
            SharedPreferences prefs = getSharedPreferences("VPNPanel", MODE_PRIVATE);
            prefs.edit().putString("token", token).apply();
            
            // رفتن به صفحه اصلی
            startActivity(new Intent(this, MainActivity.class));
        }
    }
    
    @Override
    public void onFailure(Call<LoginResponse> call, Throwable t) {
        Toast.makeText(this, "خطا در اتصال", Toast.LENGTH_SHORT).show();
    }
});
```

### 3. دریافت اطلاعات داشبورد

```java
apiService.getDashboard().enqueue(new Callback<DashboardResponse>() {
    @Override
    public void onResponse(Call<DashboardResponse> call, Response<DashboardResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            DashboardResponse data = response.body();
            
            // نمایش اطلاعات اشتراک
            if (data.subscription != null) {
                tvPlanName.setText(data.subscription.plan_name);
                tvExpiry.setText(data.subscription.expiry_date);
                
                long usedGB = data.subscription.traffic_used / (1024 * 1024 * 1024);
                long totalGB = data.subscription.traffic_limit / (1024 * 1024 * 1024);
                tvTraffic.setText(usedGB + " / " + totalGB + " GB");
            }
            
            // نمایش سرورها
            serverAdapter.updateServers(data.servers);
        }
    }
    
    @Override
    public void onFailure(Call<DashboardResponse> call, Throwable t) {
        // Handle error
    }
});
```

### 4. اتصال به VPN

```java
// انتخاب سرور + کانفیگ دستی (اختیاری)
ConnectRequest request = new ConnectRequest(serverId, configId);

apiService.connect(request).enqueue(new Callback<ConnectResponse>() {
    @Override
    public void onResponse(Call<ConnectResponse> call, Response<ConnectResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            String config = response.body().config;
            String protocol = response.body().protocol;
            
            // اتصال به VPN با استفاده از کانفیگ
            vpnManager.connect(config, protocol, new VPNCallback() {
                @Override
                public void onConnected() {
                    Toast.makeText(this, "متصل شد", Toast.LENGTH_SHORT).show();
                }
                
                @Override
                public void onError(String error) {
                    Toast.makeText(this, "خطا: " + error, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    
    @Override
    public void onFailure(Call<ConnectResponse> call, Throwable t) {
        // Handle error
    }
});
```

---

## 🔐 امنیت

### توکن احراز هویت
- تمام APIها به جز `login` و `register` نیاز به توکن دارند
- توکن در هدر `Authorization: Bearer {token}` ارسال می‌شود
- توکن را در `SharedPreferences` ذخیره کنید (رمزنگاری شده)

### HTTPS
- حتماً از HTTPS استفاده کنید
- گواهی SSL را بررسی کنید

---

## 📊 مدیریت خطاها

```java
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
    if (response.isSuccessful()) {
        if (response.body().success) {
            // موفق
        } else {
            // خطای سرور
            String errorMessage = response.body().message;
        }
    } else {
        // HTTP Error (401, 403, 500, ...)
        if (response.code() == 401) {
            // Unauthorized - توکن منقضی شده
            // کاربر را به صفحه لاگین ببر
        }
    }
}

@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
    // خطای شبکه
    if (t instanceof IOException) {
        // مشکل اتصال
    }
}
```

---

## 🎉 تمام!

اپلیکیشن اندروید شما الان می‌تونه:

✅ کاربر لاگین/رجیستر کنه  
✅ اشتراک‌ها رو ببینه و بخره  
✅ به سرورها با کانفیگ دستی وصل بشه  
✅ ترافیک مصرفی رو ببینه  
✅ تیکت باز کنه و پیگیری کنه  
✅ پروفایل رو ویرایش کنه  

🚀 **همه چیز آماده‌ست!**
