# WABA SAAS API Documentation

Dokumentasi lengkap untuk WABA SAAS - WhatsApp Business API Management Platform.

## Base URL

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

## Authentication

### Admin/User Authentication (Bearer Token)
```http
Authorization: Bearer {sanctum_token}
```

### Client API Authentication (API Key)
```http
X-Api-Key: {client_api_key}
```

---

## 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
| Code | Description |
|------|-------------|
| `POOL_NOT_FOUND` | WABA Pool tidak ditemukan |
| `MESSAGE_NOT_FOUND` | Message tidak ditemukan |
| `VALIDATION_ERROR` | Data input tidak valid |
| `TOKEN_EXPIRED` | Token sudah expired |
| `INSUFFICIENT_BALANCE` | Saldo tidak mencukupi |

---

## 1. Webhook Endpoints

### GET /api/webhook/waba - Verify Webhook

Meta akan mengirim request ini untuk verifikasi webhook.

**Query Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| hub.mode | string | Harus "subscribe" |
| hub.verify_token | string | Token verifikasi |
| hub.challenge | string | Challenge string |

**Response:** Returns `hub.challenge` value

**Setup di Meta:**
1. Buka Meta Developer Console
2. WhatsApp → Configuration → Webhook
3. Callback URL: `https://your-domain.com/api/webhook/waba`
4. Verify Token: sama dengan `WABA_WEBHOOK_VERIFY_TOKEN` di .env

---

### POST /api/webhook/waba - Receive Messages

Meta mengirim pesan masuk ke endpoint ini.

**Payload dari Meta:**
```json
{
  "object": "whatsapp_business_account",
  "entry": [{
    "id": "WABA_ID",
    "changes": [{
      "value": {
        "messaging_product": "whatsapp",
        "metadata": {
          "display_phone_number": "628123456789",
          "phone_number_id": "123456789"
        },
        "messages": [{
          "from": "628987654321",
          "id": "wamid.xxx",
          "timestamp": "1702200000",
          "type": "text",
          "text": { "body": "Hello!" }
        }]
      },
      "field": "messages"
    }]
  }]
}
```

**Response:** `200 OK`

---

## 2. Token Management

### POST /api/admin/waba-pool/{id}/generate-token

Generate atau simpan permanent token.

**Headers:**
```http
Authorization: Bearer {token}
Content-Type: application/json
```

**Request Body (Option 1 - Exchange Token):**
```json
{
  "short_lived_token": "EAAxxxx..."
}
```

**Request Body (Option 2 - Store Permanent):**
```json
{
  "permanent_token": "EAAxxxx...",
  "skip_exchange": true
}
```

**Response:**
```json
{
  "status": true,
  "message": "Token generated successfully",
  "data": {
    "token_stored": true,
    "generated_at": "2025-12-10T10:00:00Z",
    "expires_at": "2026-02-08T10:00:00Z"
  }
}
```

**cURL Example:**
```bash
curl -X POST "https://domain.com/api/admin/waba-pool/1/generate-token" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"short_lived_token": "EAAxxxx..."}'
```

**PHP Example:**
```php
$response = Http::withToken($adminToken)
    ->post('https://domain.com/api/admin/waba-pool/1/generate-token', [
        'short_lived_token' => 'EAAxxxx...'
    ]);

$data = $response->json();
```

**JavaScript Example:**
```javascript
const response = await fetch('https://domain.com/api/admin/waba-pool/1/generate-token', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${adminToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    short_lived_token: 'EAAxxxx...'
  })
});

const data = await response.json();
```

---

### GET /api/admin/waba-pool/{id}/token-status

Cek status token saat ini.

**Response:**
```json
{
  "status": true,
  "message": "Token status retrieved",
  "data": {
    "has_token": true,
    "token_status": "valid",
    "generated_at": "2025-12-10T10:00:00Z",
    "expires_at": "2026-02-08T10:00:00Z",
    "days_until_expiry": 60
  }
}
```

---

## 3. Inbox Messages API

### GET /api/admin/waba-pool/{id}/messages

Mendapatkan pesan masuk.

**Query Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| date_from | date | Filter dari tanggal (YYYY-MM-DD) |
| date_to | date | Filter sampai tanggal |
| from_number | string | Filter nomor pengirim |
| type | string | Filter tipe (text, image, etc) |
| unread_only | boolean | Hanya unread |
| per_page | integer | Items per page (max 100) |

**Response:**
```json
{
  "status": true,
  "message": "Inbox messages retrieved",
  "data": {
    "waba_pool": {
      "id": 1,
      "phone_number": "628123456789",
      "account_name": "My Business"
    },
    "messages": [
      {
        "id": 1,
        "wa_message_id": "wamid.xxx",
        "from_number": "628987654321",
        "to_number": "628123456789",
        "message_type": "text",
        "message_body": "Hello!",
        "is_read": false,
        "message_timestamp": "2025-12-10T10:00:00Z",
        "created_at": "2025-12-10T10:00:01Z"
      }
    ],
    "pagination": {
      "current_page": 1,
      "per_page": 50,
      "total": 100,
      "last_page": 2
    }
  }
}
```

**cURL Example:**
```bash
curl -X GET "https://domain.com/api/admin/waba-pool/1/messages?unread_only=true" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

---

### GET /api/admin/waba-pool/{id}/messages/stats

Statistik inbox.

**Response:**
```json
{
  "status": true,
  "message": "Inbox stats retrieved",
  "data": {
    "total_messages": 1500,
    "unread_messages": 25,
    "unique_senders": 350,
    "today_messages": 45
  }
}
```

---

### GET /api/admin/waba-pool/{id}/messages/conversations

Daftar percakapan (grouped by sender).

**Response:**
```json
{
  "status": true,
  "message": "Conversations retrieved",
  "data": {
    "conversations": [
      {
        "from_number": "628987654321",
        "message_count": 25,
        "unread_count": 3,
        "last_message_at": "2025-12-10T10:00:00Z"
      }
    ],
    "pagination": { ... }
  }
}
```

---

### GET /api/admin/waba-pool/{id}/messages/conversation/{phoneNumber}

Pesan dari pengirim tertentu.

**Response:**
```json
{
  "status": true,
  "message": "Conversation messages retrieved",
  "data": {
    "phone_number": "628987654321",
    "messages": [ ... ],
    "pagination": { ... }
  }
}
```

---

### POST /api/admin/waba-pool/{id}/messages/{messageId}/read

Tandai pesan sebagai dibaca.

**Response:**
```json
{
  "status": true,
  "message": "Message marked as read",
  "data": null
}
```

---

### POST /api/admin/waba-pool/{id}/messages/read-all

Tandai semua pesan sebagai dibaca.

**Response:**
```json
{
  "status": true,
  "message": "50 messages marked as read",
  "data": {
    "updated_count": 50
  }
}
```

---

## 4. Send Message API

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

Kirim pesan WhatsApp.

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

**Request Body (Text Message):**
```json
{
  "to": "628987654321",
  "type": "text",
  "message": "Hello World!"
}
```

**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" }
      ]
    }
  ]
}
```

**Response:**
```json
{
  "status": true,
  "message": "Message sent successfully",
  "data": {
    "message_id": "123",
    "wamid": "wamid.xxx"
  }
}
```

**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' => $apiKey
])->post('https://domain.com/api/v1/message/send', [
    'to' => '628987654321',
    'type' => 'text',
    'message' => 'Hello World!'
]);
```

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

---

## Flow Diagrams

### Webhook Flow

```
┌─────────┐     GET /webhook/waba        ┌─────────────┐
│  Meta   │ ──────────────────────────▶  │   Server    │
│         │ ◀────────────────────────── │             │
│         │      return challenge        │             │
└─────────┘                              └─────────────┘

┌─────────┐     POST /webhook/waba       ┌─────────────┐     ┌──────────┐
│  Meta   │ ──────────────────────────▶  │   Server    │ ──▶ │ Database │
│         │      (incoming message)      │             │     │          │
│         │ ◀────────────────────────── │             │     └──────────┘
│         │          200 OK              │             │
└─────────┘                              └─────────────┘
```

### Token Generation Flow

```
┌─────────┐                              ┌─────────────┐     ┌──────────┐
│  Admin  │                              │   Server    │     │   Meta   │
│         │                              │             │     │   API    │
└────┬────┘                              └──────┬──────┘     └────┬─────┘
     │                                          │                  │
     │ POST /generate-token                     │                  │
     │ {short_lived_token}                      │                  │
     │ ────────────────────────────────────────▶│                  │
     │                                          │                  │
     │                                          │ Exchange token   │
     │                                          │ ────────────────▶│
     │                                          │                  │
     │                                          │  Long-lived      │
     │                                          │ ◀────────────────│
     │                                          │                  │
     │                                          │ Save to DB       │
     │                                          │ ────────┐        │
     │                                          │         │        │
     │                                          │ ◀───────┘        │
     │                                          │                  │
     │ Response: token_stored                   │                  │
     │ ◀────────────────────────────────────────│                  │
     │                                          │                  │
```

---

## Environment Variables

```env
# Meta Graph API
META_GRAPH_BASE_URL=https://graph.facebook.com/v19.0

# Webhook
WABA_WEBHOOK_VERIFY_TOKEN=your_secret_verify_token

# Database
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=waba_saas
DB_USERNAME=root
DB_PASSWORD=
```

---

## OpenAPI Specification

File OpenAPI tersedia di: `docs/openapi.yaml`

Untuk Swagger UI, kunjungi: `https://your-domain.com/api/documentation`
