# WABA SAAS - Client API Documentation

Dokumentasi API lengkap untuk **Client** pada sistem WABA SAAS.

---

## Overview

API ini digunakan oleh **Client** untuk:
- Mengirim pesan WhatsApp
- Mengelola dedicated number milik sendiri
- Request assign/ganti nama dedicated number
- Melihat statistik penggunaan dan saldo

**Base URL:**
```
Production:  https://your-domain.com/api
Development: http://localhost:8001/api
```

---

## Authentication

Client menggunakan **API Key** yang dikirim via header:

```http
X-Api-Key: {your_client_api_key}
```

> ⚠️ **Penting:** Jangan pernah share API Key Anda. API Key dapat di-regenerate di panel client.

---

## Response Format

### Success Response
```json
{
  "status": true,
  "message": "Operation successful",
  "data": { ... }
}
```

### Error Response
```json
{
  "status": false,
  "message": "Error description",
  "error_code": "ERROR_CODE"
}
```

### Error Codes (Client)
| Code | Description |
|------|-------------|
| `INVALID_API_KEY` | API Key tidak valid |
| `INSUFFICIENT_BALANCE` | Saldo tidak mencukupi |
| `NUMBER_NOT_AVAILABLE` | Nomor dedicated tidak tersedia |
| `REQUEST_PENDING` | Sudah ada request yang pending |
| `VALIDATION_ERROR` | Data input tidak valid |
| `RATE_LIMIT_EXCEEDED` | Terlalu banyak request |

---

## 1. Send Message API

### POST /api/v1/message/send

Mengirim pesan WhatsApp ke nomor tujuan.

**Headers:**
```http
X-Api-Key: {client_api_key}
Content-Type: application/json
```

#### Request Body - Text Message
```json
{
  "to": "628987654321",
  "type": "text",
  "message": "Hello, this is a test message!"
}
```

#### Request Body - Template Message
```json
{
  "to": "628987654321",
  "type": "template",
  "template_name": "hello_world",
  "template_language": "id",
  "template_components": [
    {
      "type": "body",
      "parameters": [
        { "type": "text", "text": "John Doe" }
      ]
    }
  ]
}
```

#### Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| to | string | ✅ | Nomor tujuan (format internasional tanpa +) |
| type | string | ❌ | Tipe pesan: `text` atau `template` (default: text) |
| message | string | ✅* | Isi pesan (wajib jika type=text) |
| template_name | string | ✅* | Nama template (wajib jika type=template) |
| template_language | string | ❌ | Bahasa template (default: id) |
| template_components | array | ❌ | Components template |

#### Response Success
```json
{
  "status": true,
  "message": "Message sent successfully",
  "data": {
    "message_id": "12345",
    "wamid": "wamid.HBgNNjI4MTIzNDU2Nzg5FQ...",
    "to": "628987654321",
    "cost": 350
  }
}
```

#### cURL Example
```bash
curl -X POST "https://domain.com/api/v1/message/send" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "628987654321",
    "type": "text",
    "message": "Hello World!"
  }'
```

#### PHP Example
```php
$response = Http::withHeaders([
    'X-Api-Key' => 'YOUR_API_KEY'
])->post('https://domain.com/api/v1/message/send', [
    'to' => '628987654321',
    'type' => 'text',
    'message' => 'Hello World!'
]);

$result = $response->json();
if ($result['status']) {
    echo "Message sent! ID: " . $result['data']['message_id'];
}
```

#### JavaScript Example
```javascript
const response = await fetch('https://domain.com/api/v1/message/send', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    to: '628987654321',
    type: 'text',
    message: 'Hello World!'
  })
});

const result = await response.json();
console.log(result);
```

---

## 2. Dedicated Number API

### GET /api/client/dedicated-numbers/available

Melihat daftar nomor dedicated yang tersedia untuk di-request.

**Headers:**
```http
X-Api-Key: {client_api_key}
```

#### Response
```json
{
  "status": true,
  "message": "Available numbers retrieved",
  "data": [
    {
      "id": 1,
      "phone_number": "628123456789",
      "account_name": "Business Account 1",
      "base_price": 500000,
      "margin": 50000,
      "total_price": 550000,
      "formatted_price": "Rp 550.000"
    },
    {
      "id": 2,
      "phone_number": "628123456790",
      "account_name": "Business Account 2",
      "base_price": 750000,
      "margin": 75000,
      "total_price": 825000,
      "formatted_price": "Rp 825.000"
    }
  ]
}
```

> 💡 **Catatan:** Harga yang ditampilkan sudah termasuk margin reseller (jika ada).

---

### GET /api/client/dedicated-numbers/my-numbers

Melihat daftar nomor dedicated milik Anda yang sudah aktif.

**Headers:**
```http
X-Api-Key: {client_api_key}
```

#### Response
```json
{
  "status": true,
  "message": "Your dedicated numbers",
  "data": [
    {
      "id": 1,
      "waba_pool_id": 5,
      "phone_number": "628123456789",
      "account_name": "My Business",
      "label": "Nomor CS Utama",
      "status": "active",
      "price": 550000,
      "assigned_at": "2025-12-01T10:00:00Z",
      "created_at": "2025-12-01T10:00:00Z"
    }
  ]
}
```

---

### POST /api/client/dedicated-numbers/request

Request assign nomor dedicated baru. **Saldo akan dikurangi otomatis** saat request disetujui admin.

**Headers:**
```http
X-Api-Key: {client_api_key}
Content-Type: application/json
```

#### Request Body
```json
{
  "waba_pool_id": 1,
  "label": "Nomor CS Utama"
}
```

#### Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| waba_pool_id | integer | ✅ | ID nomor WABA yang ingin di-request |
| label | string | ❌ | Label/nama untuk nomor ini (max 100 karakter) |

#### Response Success
```json
{
  "status": true,
  "message": "Request berhasil dikirim. Menunggu persetujuan admin.",
  "data": {
    "request_id": 15,
    "waba_pool_id": 1,
    "phone_number": "628123456789",
    "status": "pending",
    "base_price": 500000,
    "margin": 50000,
    "total_price": 550000,
    "requested_at": "2025-12-10T10:00:00Z"
  }
}
```

#### Error: Saldo Tidak Cukup
```json
{
  "status": false,
  "message": "Saldo tidak mencukupi. Dibutuhkan Rp 550.000, saldo Anda Rp 200.000",
  "error_code": "INSUFFICIENT_BALANCE"
}
```

#### Error: Sudah Ada Request Pending
```json
{
  "status": false,
  "message": "Anda sudah memiliki request pending untuk nomor ini",
  "error_code": "REQUEST_PENDING"
}
```

#### cURL Example
```bash
curl -X POST "https://domain.com/api/client/dedicated-numbers/request" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "waba_pool_id": 1,
    "label": "Nomor CS Utama"
  }'
```

---

### GET /api/client/dedicated-numbers/pending

Melihat daftar request yang sedang pending.

**Headers:**
```http
X-Api-Key: {client_api_key}
```

#### Response
```json
{
  "status": true,
  "message": "Pending requests",
  "data": [
    {
      "id": 15,
      "waba_pool_id": 1,
      "phone_number": "628123456789",
      "status": "pending",
      "total_price": 550000,
      "requested_label": "Nomor CS Utama",
      "requested_at": "2025-12-10T10:00:00Z"
    }
  ]
}
```

---

### DELETE /api/client/dedicated-numbers/request/{id}

Membatalkan request yang masih pending.

**Headers:**
```http
X-Api-Key: {client_api_key}
```

#### Response
```json
{
  "status": true,
  "message": "Request dibatalkan",
  "data": null
}
```

---

## 3. Name Change Request API

### POST /api/client/name-requests

Request ganti nama/label nomor dedicated Anda.

**Headers:**
```http
X-Api-Key: {client_api_key}
Content-Type: application/json
```

#### Request Body
```json
{
  "dedicated_assign_id": 1,
  "new_name": "Hotline Support 24 Jam"
}
```

#### Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| dedicated_assign_id | integer | ✅ | ID assignment nomor dedicated Anda |
| new_name | string | ✅ | Nama/label baru (max 100 karakter) |

#### Response Success
```json
{
  "status": true,
  "message": "Request ganti nama berhasil dikirim. Menunggu persetujuan admin.",
  "data": {
    "id": 5,
    "dedicated_assign_id": 1,
    "current_name": "Nomor CS Utama",
    "requested_name": "Hotline Support 24 Jam",
    "status": "pending",
    "created_at": "2025-12-10T10:00:00Z"
  }
}
```

---

### GET /api/client/name-requests

Melihat daftar request ganti nama Anda.

**Headers:**
```http
X-Api-Key: {client_api_key}
```

#### Response
```json
{
  "status": true,
  "message": "Name change requests",
  "data": [
    {
      "id": 5,
      "dedicated_assign_id": 1,
      "phone_number": "628123456789",
      "current_name": "Nomor CS Utama",
      "requested_name": "Hotline Support 24 Jam",
      "status": "pending",
      "created_at": "2025-12-10T10:00:00Z"
    },
    {
      "id": 3,
      "dedicated_assign_id": 1,
      "phone_number": "628123456789",
      "current_name": "CS Support",
      "requested_name": "Nomor CS Utama",
      "status": "approved",
      "processed_at": "2025-12-05T14:30:00Z"
    }
  ]
}
```

---

### DELETE /api/client/name-requests/{id}

Membatalkan request ganti nama yang masih pending.

**Headers:**
```http
X-Api-Key: {client_api_key}
```

#### Response
```json
{
  "status": true,
  "message": "Request dibatalkan",
  "data": null
}
```

---

## 4. Balance & Usage API

### GET /api/v1/balance

Melihat saldo dan informasi akun Anda.

**Headers:**
```http
X-Api-Key: {client_api_key}
```

#### Response
```json
{
  "status": true,
  "message": "Balance retrieved",
  "data": {
    "balance": 1500000,
    "formatted_balance": "Rp 1.500.000",
    "currency": "IDR",
    "client_name": "PT Contoh Indonesia",
    "messages_today": 150,
    "messages_this_month": 4500
  }
}
```

---

## 5. Message History API

### GET /api/v1/messages

Melihat riwayat pesan yang dikirim.

**Headers:**
```http
X-Api-Key: {client_api_key}
```

#### Query Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| page | integer | Halaman (default: 1) |
| per_page | integer | Items per halaman (default: 50, max: 100) |
| status | string | Filter status: sent, delivered, read, failed |
| date_from | date | Filter dari tanggal (YYYY-MM-DD) |
| date_to | date | Filter sampai tanggal |

#### Response
```json
{
  "status": true,
  "message": "Messages retrieved",
  "data": {
    "messages": [
      {
        "id": 12345,
        "to": "628987654321",
        "type": "text",
        "message": "Hello World!",
        "status": "delivered",
        "cost": 350,
        "wamid": "wamid.xxx",
        "sent_at": "2025-12-10T10:00:00Z"
      }
    ],
    "pagination": {
      "current_page": 1,
      "per_page": 50,
      "total": 4500,
      "last_page": 90
    }
  }
}
```

---

## Billing & Harga Dedicated Number

### Alur Billing

```
┌─────────┐      Request Assign      ┌──────────┐
│ Client  │ ─────────────────────▶   │  Server  │
│         │                          │          │
│         │   [Cek Saldo Cukup?]     │          │
│         │ ◀─────────────────────   │          │
└─────────┘                          └──────────┘
                                          │
                                          ▼
                                    ┌──────────┐
                                    │  Admin   │
                                    │ Approve  │
                                    └────┬─────┘
                                         │
                    ┌────────────────────┴────────────────────┐
                    ▼                                         ▼
              ┌──────────┐                              ┌──────────┐
              │  Potong  │                              │   Ubah   │
              │  Saldo   │                              │  Status  │
              │  Client  │                              │  Active  │
              └──────────┘                              └──────────┘
```

### Struktur Harga

| Komponen | Keterangan |
|----------|------------|
| **Base Price** | Harga dasar yang ditetapkan admin per nomor |
| **Margin** | Keuntungan reseller (jika client di bawah reseller) |
| **Total Price** | Base Price + Margin = harga yang dibayar client |

### Contoh Perhitungan

```
Base Price:    Rp 500.000
Margin (10%):  Rp  50.000
─────────────────────────
Total Price:   Rp 550.000  ◀── Dipotong dari saldo client
```

---

## Notes & Restrictions

1. **Rate Limiting**: Maksimal 100 request per menit per API Key
2. **Saldo**: Pastikan saldo mencukupi sebelum request dedicated number
3. **Dedicated Number**: Setelah disetujui, saldo langsung terpotong dan tidak bisa dibatalkan
4. **Label/Nama**: Request ganti nama memerlukan approval admin
5. **API Key**: Jaga kerahasiaan API Key Anda

---

## Support

Jika mengalami kendala, hubungi reseller atau admin Anda.
