# WhatsApp Chatbot using Twilio + PHP Laravel

## Overview
This project describes how to build a **production-ready WhatsApp chatbot** using **Twilio WhatsApp API** and **PHP Laravel**, including a **friendly admin UI** for managing conversations and bot flows.

The system is designed to be **scalable, secure, and extensible**, with the ability to integrate AI (OpenAI / LLMs) in the future.

---

## Tech Stack

- **Backend:** PHP 8.2+, Laravel 10+
- **Messaging:** Twilio WhatsApp API
- **Frontend (Admin UI):** Blade + Tailwind CSS
- **Database:** MySQL / PostgreSQL
- **Queue:** Laravel Queue (Redis / Database)
- **Optional AI:** OpenAI (future-ready)

---

## Functional Requirements

### 1. Backend (Laravel)

- Webhook endpoint to receive WhatsApp messages from Twilio
- Validate Twilio request signature
- Service layer for Twilio communication
- Conversation session handling per phone number
- Support:
  - Text messages
  - Menu-style replies
  - Keyword-based intent detection
- Message logging (incoming & outgoing)
- Queue-based message sending
- Environment-based configuration

---

### 2. Twilio Integration

- WhatsApp Sandbox & production support
- Incoming message webhook
- Status callback handling (sent, delivered, read)
- Error handling & retries

---

### 3. Database Schema

#### Tables

##### `whatsapp_contacts`
- id
- phone_number
- name
- created_at

##### `chat_sessions`
- id
- contact_id
- status (active / closed)
- current_step
- created_at
- updated_at

##### `chat_messages`
- id
- session_id
- direction (in / out)
- message
- payload (json)
- created_at

##### `chat_flows`
- id
- name
- is_active
- created_at

##### `chat_flow_steps`
- id
- flow_id
- step_key
- message
- expected_input
- next_step
- created_at

---

### 4. Admin UI (Friendly Dashboard)

- Login-protected admin panel
- Features:
  - Live chat viewer
  - Conversation history
  - Flow builder (step-based)
  - Bot enable/disable toggle
  - Manual reply option
- UI:
  - WhatsApp-like layout
  - Responsive
  - Clean & modern (Tailwind)

---

### 5. Security

- Twilio webhook signature verification
- Rate limiting on webhooks
- CSRF protection (admin panel)
- Validation on all inputs
- Secure `.env` usage

---

## Bot Logic Design

### Bot Engine
- Central `BotEngine` service
- Rule-based intent detection
- Step-based flow execution
- Fallback handling
- Stateless controller, state handled via DB

### Example Flow
1. User says "Hi"
2. Bot replies:
