# Connecting e-mail, WhatsApp, Telegram and AI

This guide explains how to connect the outside services yourself. Each step says **where** the
value goes (the `.env` file on the server, or a screen inside the system) and **how to test it**.

> **Security rules**
> - Never send keys or passwords by e-mail or chat. Paste them only into `.env` or the system screens.
> - Screens never show a saved key again. Leave the field empty to keep it; type a new one to replace it.
> - After changing `.env`, restart the app: `docker compose restart` (or `php artisan config:clear` and
>   restart the queue workers on a normal server).
> - When everything is connected, check **System → System health**. Every line should be green.

---

## 1. E-mail (required)

**Where:** the `.env` file on the server. The sender name and address can also be set in
**System → Settings Center → Email sender**.

Get these values from your e-mail provider (Microsoft 365, Google Workspace, your hosting company,
or a sending service like Amazon SES, Mailgun or SendGrid):

```env
MAIL_MAILER=smtp
MAIL_HOST=smtp.office365.com        # example for Microsoft 365
MAIL_PORT=587
MAIL_SCHEME=null                    # STARTTLS on 587; use "smtps" for port 465
MAIL_USERNAME=contracts@almasa.ae
MAIL_PASSWORD=your-app-password
MAIL_FROM_ADDRESS=contracts@almasa.ae
MAIL_FROM_NAME="Almasa Contracts"
```

Common providers:

| Provider | Host | Port | Notes |
|---|---|---|---|
| Microsoft 365 | `smtp.office365.com` | 587 | The mailbox must have "Authenticated SMTP" turned on (Microsoft 365 admin → user → Mail). |
| Google Workspace | `smtp.gmail.com` | 587 | Create an **App password** (Google account → Security → 2-Step Verification → App passwords). |
| Amazon SES | `email-smtp.<region>.amazonaws.com` | 587 | Use SES SMTP credentials, not your AWS login. Verify the domain first. |

**Tips:**
- Use a dedicated mailbox such as `contracts@…`, not a personal one.
- Ask whoever manages your domain to set up **SPF and DKIM**. Without them, reminders often land in spam.

**Test:** go to **Notifications → Delivery channels → Test — Email**, enter your address, and check that the
message arrives.

---

## 2. WhatsApp (optional)

**Where:** **Notifications → Delivery channels → WhatsApp**. Each user's number goes in their profile under
**Users → WhatsApp number**; if that's empty, their mobile number is used. UAE numbers like `050…` are
converted automatically.

Pick **one** provider.

### Option A — Meta WhatsApp Cloud API (direct from Meta, usually cheapest)
1. Create a Meta Business account at <https://business.facebook.com> and verify the business.
2. Create an app at <https://developers.facebook.com> → *Business* type → add the **WhatsApp** product.
3. Add and verify the company phone number. It must not already be used in the WhatsApp mobile app.
4. Create a **System User** (Business settings → Users → System users). Give it the WhatsApp app, and
   generate a **permanent token** with the `whatsapp_business_messaging` permission.
5. Copy the **Phone number ID** (WhatsApp → API setup). It is not the phone number itself.
6. Create a **message template** (WhatsApp Manager → Message templates):
   - Category **Utility**, language **Arabic** (`ar`), body with exactly one variable, for example:
     `تنبيه من نظام عقود الماسة: {{1}}`
   - Wait for Meta to approve it, which usually takes minutes to hours.
7. In the system, fill in:
   - Provider: **Meta WhatsApp Cloud API**
   - Token
   - Phone number ID
   - Template name (exactly as created)
   - Template language `ar`

> Why a template? WhatsApp only allows free-text messages within 24 hours of the person writing to you.
> Reminders are sent proactively, so they must use an approved template.

### Option B — Twilio
1. Sign up at <https://www.twilio.com>, then register a WhatsApp sender (Messaging → Senders → WhatsApp).
2. Copy the **Account SID** and **Auth Token** from the Twilio console.
3. In the system, fill in:
   - Provider: **Twilio**
   - Token: the Auth Token
   - Twilio Account SID
   - From number, e.g. `+9715…`

### Option C — 360dialog
1. Sign up at <https://www.360dialog.com> and connect your number.
2. Generate an **API key** in the 360dialog hub.
3. In the system, fill in:
   - Provider: **360dialog**
   - Token: the API key

**Test:** **Test — WhatsApp** on the same screen, with your own number.

**Turning it off:** **System → Settings Center → Features → WhatsApp notifications**. Your rules and
settings stay saved.

---

## 3. Telegram (optional, free)

**Where:** **Notifications → Delivery channels → Telegram**. Each user's chat ID goes in their profile under
**Users → Telegram chat ID**.

1. In Telegram, open **@BotFather** → send `/newbot` → choose a name, e.g. *Almasa Contracts*, and a
   username ending in `bot`.
2. BotFather replies with a **bot token** like `123456789:AA…`. Paste it into **Bot token** and save.
3. For each user:
   1. They open your bot in Telegram and press **Start**. Bots can't message people who haven't done this.
   2. They message **@userinfobot**, which replies with their numeric ID.
   3. You enter that number in their user profile as the **Telegram chat ID**.
4. Optional: for a team group, add the bot to the group, get the group ID (it starts with `-`), and enter it
   as the **Default chat ID**. Alerts for users without their own chat ID then go to that group.

**Test:** **Test — Telegram** with your chat ID.

---

## 4. AI contract extraction (optional)

Without an AI key, the system still reads contracts with built-in rules (rule-based extraction). With a key,
it fills in many more fields from the uploaded PDF, and every value still goes through the review screen
before it's saved.

**Where:** **System → Settings Center → OCR & AI**. Only a **Super Admin** can change these settings. You can
put the key in `.env` instead (`AI_PROVIDER=anthropic` and `ANTHROPIC_API_KEY=…`).

### Option A — Anthropic Claude (recommended, strongest with Arabic contracts)
1. Create an account at <https://console.anthropic.com>.
2. Add a payment method and set a **monthly spend limit** (Settings → Limits).
3. Create a key: **API keys → Create key**, named e.g. *almasa-cms*.
4. In the system: AI extraction provider **Anthropic Claude**, then paste the key into **Anthropic API key**.

### Option B — OpenAI
1. Create an account at <https://platform.openai.com>, add billing and set a usage limit.
2. Create a key under **API keys**.
3. In the system: provider **OpenAI**, then paste the key into **OpenAI API key**.

> **Privacy:** with AI turned on, the contract file or its text is sent to the provider for analysis.
> Both providers state that API data isn't used to train their models by default; check that this meets your
> policy. To keep every document on your server, switch **Features → AI extraction** off.

**Test:** upload a sample contract under **Contracts → Contract import & analysis**. The review screen should show the
fields filled in by AI. **System health → AI extraction** should be green.

### OCR (scanned PDFs)
Tesseract is already installed in the Docker image, and nothing needs to be configured. If you install
without Docker, install `tesseract-ocr` with the Arabic language pack (`tesseract-ocr-ara`) and
`poppler-utils`.

---

## 5. Company details

**System → Settings Center → Company**:
- Arabic and English names, address, phone, e-mail and website
- Trade license number and VAT registration number (TRN)
- A PNG or JPG logo for report headers

These appear on every PDF and Excel report.

## 6. Backup password (do this once)

The `.env` file contains `BACKUP_ARCHIVE_PASSWORD`. Store a copy somewhere **outside the server**, such as a
password manager or a sealed envelope in the safe. Without it, backups cannot be opened.

## Checklist

- [ ] E-mail test received
- [ ] SPF/DKIM set for the sending domain
- [ ] WhatsApp provider connected and template approved (or feature switched off)
- [ ] Telegram bot created, and users' chat IDs entered (or feature switched off)
- [ ] AI key added with a spend limit (or feature switched off)
- [ ] Company details and logo entered
- [ ] Backup password stored off the server
- [ ] **System → System health** all green
