# Messenger User Name & Avatar — Fetch & Display Process

This document explains the **complete flow** of how a Facebook Messenger sender's
**name** and **profile picture (avatar)** are fetched from the Meta Graph API,
stored locally, and finally shown in the chat UI.

> Instagram follows almost the same flow — differences are noted at the end.

---

## 1. Big Picture

```
Messenger user sends a message
        │
        ▼
Meta Webhook  ──► POST /webhook  ──►  MessengerWebhookController
        │
        ▼
MessengerRepository::receiveResponse()
        │
        ▼
handleIncomingMessage()
        │
        ├── getSenderName()  ──► Graph API  ──► { first_name, last_name, profile_pic }
        │
        ├── New contact?  ──► save name + download profile_pic + saveImage()
        │
        └── saveIncommingMessage()  ──► broadcast (Pusher)
                                              │
                                              ▼
                          Chat SPA (Vue) renders Contact name + avatar
```

---

## 2. Webhook Entry Point

When a user messages the connected Facebook Page, Meta sends a `POST` to the
configured webhook URL. The request reaches:

- Route → `MessengerWebhookController`
  ([app/Addons/OmniSync/Controllers/Webhook/MessengerWebhookController.php](app/Addons/OmniSync/Controllers/Webhook/MessengerWebhookController.php))
- Which calls
  [`MessengerRepository::receiveResponse()`](app/Addons/OmniSync/Repository/Webhook/MessengerRepository.php#L109)

`receiveResponse()` does:

1. Extracts `entry[0]`, `messaging[0]` (the message payload) and the **Page ID**
   (`entry[0]['id']`).
2. Resolves which **Client** owns this page (`resolveWebhookClient()`).
3. Validates: webhook verify token set, active subscription, and channel access
   (`messenger_access`).
4. If the payload has a `message`, calls **`handleIncomingMessage()`**.

---

## 3. Fetching the Sender's Name & Avatar

Inside
[`handleIncomingMessage()`](app/Addons/OmniSync/Repository/Webhook/MessengerRepository.php#L530),
the **sender id** (Page-Scoped ID / PSID) is taken from `value['sender']['id']`,
then for Messenger (not Instagram):

```php
$sender_info = $this->getSenderName($sender_contact, $client);
```

### `getSenderName()` — the Graph API call

Defined in
[app/Addons/OmniSync/Traits/MessengerTrait.php:86](app/Addons/OmniSync/Traits/MessengerTrait.php#L86):

```php
private function getSenderName($sender_contact, $client)
{
    $accessToken = getClientMessengerAccessToken($client);

    $url = $this->facebook_api . $sender_contact
         . '?fields=first_name,last_name,profile_pic&access_token=' . $accessToken;

    $response = Http::withHeaders(['Content-Type' => 'application/json'])
        ->withoutVerifying()
        ->get($url);

    return json_decode($response, true);
}
```

Key points:

- **Base URL**: `$facebook_api = 'https://graph.facebook.com/v19.0/'`
  ([MessengerTrait.php:16](app/Addons/OmniSync/Traits/MessengerTrait.php#L16)).
- **Endpoint**: `GET https://graph.facebook.com/v19.0/{PSID}?fields=first_name,last_name,profile_pic`
- **Access token**: the **Page access token**, retrieved via
  [`getClientMessengerAccessToken($client)`](app/Helpers/Helper.php#L1285),
  which reads `client->messengerSetting->access_token`.
- `withoutVerifying()` skips SSL verification (local/dev convenience).

**Response shape:**

```json
{
  "first_name": "John",
  "last_name": "Doe",
  "profile_pic": "https://platform-lookaside.fbsbx.com/.../picture",
  "id": "1234567890"
}
```

> ⚠️ The `profile_pic` URL is **temporary/signed** and expires. That is why the
> image is downloaded and stored locally instead of saving the URL.

---

## 4. Storing the Contact (Name + Avatar)

Still in `handleIncomingMessage()`, the code looks up an existing `Contact` by
`client_id` + `contact_id` (the PSID).

### New contact → create + download avatar
([MessengerRepository.php:583](app/Addons/OmniSync/Repository/Webhook/MessengerRepository.php#L583))

```php
$firstName = $sender_info['first_name'] ?? '';
$lastName  = $sender_info['last_name'] ?? '';
$contact->name = trim($firstName . ' ' . $lastName) ?: 'Messenger User';

if ($sender_info && ! empty($sender_info['profile_pic'])) {
    // 1. Download the remote image bytes
    $imageContent = file_get_contents($sender_info['profile_pic']);

    // 2. Write a temp file in public/images
    $fileName = 'fb_' . time() . '.jpg';
    file_put_contents(public_path('images/' . $fileName), $imageContent);
    $filePath = public_path('images/' . $fileName);

    // 3. Wrap as an UploadedFile and run through saveImage()
    if (file_exists($filePath)) {
        $uploadedFile = new UploadedFile(
            $filePath, basename($filePath), mime_content_type($filePath), null, true
        );
        $response = $this->saveImage($uploadedFile, '_contact_');
        $contact->images = $response['images'] ?? $contact->images;
    }
}
```

Then the rest of the contact is filled and saved:

```php
$contact->phone        = $sender_contact;
$contact->contact_id   = $sender_contact;   // the PSID
$contact->client_id    = $client->id;
$contact->type         = TypeEnum::MESSENGER;
$contact->is_verified  = 1;
$contact->bot_reply    = 1;
$contact->status       = 1;
$contact->save();
```

The contact is also attached to the **"Uncategorized"** list and **"Default"**
segment.

### `saveImage()` — the image processor
Defined in
[app/Traits/ImageTrait.php:12](app/Traits/ImageTrait.php#L12). It:

- Stores the image (disk/storage),
- Generates resized variants (e.g. `image_40x40`, etc.),
- Returns an `images` array (stored on `contact.images`, a JSON/array column)
  containing the variant paths + storage driver.

### Existing contact
If the contact already exists, the avatar is **not re-fetched**; only
conversation flags (`has_conversation`, `has_unread_conversation`,
`last_conversation_at`) are refreshed.

---

## 5. Showing the Name & Avatar in the UI

### The `profile_pic` accessor
The avatar shown in chat comes from the `Contact` model accessor
[app/Models/Contact.php:115](app/Models/Contact.php#L115):

```php
public function getProfilePicAttribute(): string
{
    return arrayCheck('image_40x40', $this->images)
        && is_file_exists($this->images['image_40x40'], $this->images['storage'])
        ? get_media($this->images['image_40x40'], $this->images['storage'])
        : static_asset('images/default/user.jpg');
}
```

- If a stored `image_40x40` variant exists → return its public URL via
  `get_media()`.
- Otherwise → fall back to the **default user avatar**
  (`images/default/user.jpg`).

### Exposed through the API resource
[app/Http/Resources/ContactResource.php:49](app/Http/Resources/ContactResource.php#L49):

```php
'name'  => $this->name,
'image' => $this->profile_pic,   // resolved by the accessor above
```

### Rendered by the Chat SPA
The Vue 3 chat front-end consumes the contact resource and binds
`contact.name` + `contact.image` into the conversation list and chat header
(`resources/views/backend/client/chat/...` + the Vue components).

---

## 6. Realtime Refresh

After saving the message, `notifyIncomingMessage()` →
`safeBroadcastReceiveUpcomingMessage($client)` fires a **Pusher** event so the
open chat window updates the contact (with the freshly fetched name & avatar)
without a page reload.

---

## 7. Instagram Variant (for reference)

Instagram uses a separate fetch method but the same idea:

- [`fetchInstagramSenderProfile()`](app/Addons/OmniSync/Repository/Webhook/MessengerRepository.php#L717)
- Endpoint: `GET https://graph.facebook.com/{version}/{IGSID}?fields=name,profile_pic`
  (note: single `name` field, not `first_name`/`last_name`).
- Uses the Instagram-linked page token (`client->instagramSetting->access_token`).
- Graph version resolved dynamically by `facebookGraphVersion()`.
- Downloaded image is prefixed `ig_` instead of `fb_`, then runs through the same
  `saveImage()`.

---

## 8. Summary Table

| Step | Where | What happens |
|------|-------|--------------|
| 1. Receive | `MessengerRepository::receiveResponse()` | Webhook validated, client resolved |
| 2. Sender id | `handleIncomingMessage()` | PSID from `sender.id` |
| 3. Fetch profile | `getSenderName()` (MessengerTrait) | Graph API `?fields=first_name,last_name,profile_pic` |
| 4. Token | `getClientMessengerAccessToken()` | Page access token from `messengerSetting` |
| 5. Save name | `handleIncomingMessage()` | `first_name + last_name` → `contact.name` |
| 6. Save avatar | `file_get_contents` + `saveImage()` | Download temp URL → store local variants in `contact.images` |
| 7. Display | `Contact::getProfilePicAttribute()` | Resolve `image_40x40` or default avatar |
| 8. API | `ContactResource` | `name` + `image` to front-end |
| 9. Realtime | `safeBroadcastReceiveUpcomingMessage()` | Pusher pushes update to Chat SPA |

---

## 9. Common Gotchas

- **Avatar empty?** The `profile_pic` from Graph requires the `pages_messaging`
  permission and a valid **Page access token**. App Review / advanced access is
  needed for `first_name`, `last_name`, `profile_pic` on real users.
- **Picture not updating?** Avatars are only downloaded on **first contact
  creation**. Existing contacts keep the original image.
- **Expired URL stored?** Never store the raw `profile_pic` URL — it is signed
  and expires. Always download & re-host (this code already does).
- **API version** is hard-coded to `v19.0` in `MessengerTrait`. Instagram path
  resolves it dynamically via `facebookGraphVersion()`.
