# Chat Module API Documentation

## Overview
This chat module implements a question-answer based conversation system with predefined questions organized by categories. After every 5 questions exchanged, users are prompted to make a decision about continuing the relationship.

## Database Schema

### Tables Created:
1. **chats** - Stores chat sessions between two users
2. **chat_messages** - Stores individual messages (questions and answers)

## API Endpoints

### Base URL: `/api/v1/chat/`

---

## 1. Initialize Chat
**POST** `/api/v1/chat/initialize`

Initialize a new chat session between two users.

**Request:**
```json
{
    "user_id_1": 1,
    "user_id_2": 2,
    "connection_id": 5
}
```

**Note:** The `connection_id` is optional and refers to the `user_connections` table ID. The system stores connections as double-sided entries (both user_id → connected_user_id and vice versa), so the connection will be verified in both directions automatically.

**Response:**
```json
{
    "status": "success",
    "message": "Chat initialized successfully",
    "data": {
        "chat_id": 1,
        "status": "active"
    }
}
```

---

## 2. Get Question Categories
**GET** `/api/v1/chat/categories`

Fetch all available question categories.

**Response:**
```json
{
    "status": "success",
    "data": [
        {
            "id": 1,
            "name": "Finance",
            "name_ar": "المالية",
            "questions_count": 15
        },
        {
            "id": 2,
            "name": "Family",
            "name_ar": "العائلة",
            "questions_count": 20
        }
    ]
}
```

---

## 3. Get Questions by Category
**POST** `/api/v1/chat/questions`

Get available questions for a specific category (excludes already asked questions).

**Request:**
```json
{
    "chat_category_id": 1,
    "chat_id": 1
}
```

**Response:**
```json
{
    "status": "success",
    "data": [
        {
            "id": 1,
            "name": "What are your financial goals?",
            "name_ar": "ما هي أهدافك المالية؟",
            "chat_category_id": 1,
            "answers": [
                {
                    "id": 1,
                    "question_id": 1,
                    "name": "Save for retirement",
                    "name_ar": "الادخار للتقاعد"
                },
                {
                    "id": 2,
                    "question_id": 1,
                    "name": "Buy a house",
                    "name_ar": "شراء منزل"
                }
            ]
        }
    ]
}
```

---

## 4. Send Question
**POST** `/api/v1/chat/send-question`

Send a question to the other user.

**Request:**
```json
{
    "chat_id": 1,
    "question_id": 5,
    "sender_id": 1
}
```

**Response:**
```json
{
    "status": "success",
    "message": "Question sent successfully",
    "data": {
        "id": 10,
        "chat_id": 1,
        "sender_id": 1,
        "receiver_id": 2,
        "question_id": 5,
        "message_type": "question",
        "question": {
            "id": 5,
            "name": "What are your hobbies?",
            "name_ar": "ما هي هواياتك؟",
            "answers": [...]
        }
    }
}
```

---

## 5. Send Answer
**POST** `/api/v1/chat/send-answer`

Answer a received question.

**Request:**
```json
{
    "message_id": 10,
    "answer_id": 3,
    "sender_id": 2
}
```

**Response:**
```json
{
    "status": "success",
    "message": "Answer sent successfully",
    "data": {
        "message": {
            "id": 11,
            "chat_id": 1,
            "sender_id": 2,
            "receiver_id": 1,
            "question_id": 5,
            "answer_id": 3,
            "message_type": "answer"
        },
        "questions_exchanged": 5,
        "show_decision_prompt": true
    }
}
```

**Note:** When `show_decision_prompt` is `true`, both users should be shown the decision prompt.

---

## 6. Get Chat Messages
**POST** `/api/v1/chat/messages`

Get paginated chat messages.

**Request:**
```json
{
    "chat_id": 1,
    "user_id": 1,
    "page": 1,
    "per_page": 20
}
```

**Response:**
```json
{
    "status": "success",
    "data": {
        "chat": {
            "id": 1,
            "status": "active",
            "questions_exchanged": 5,
            "show_decision_prompt": true
        },
        "messages": {
            "current_page": 1,
            "data": [...],
            "total": 10
        }
    }
}
```

---

## 7. Submit Decision
**POST** `/api/v1/chat/submit-decision`

Submit decision after 5 questions are exchanged.

**Request:**
```json
{
    "chat_id": 1,
    "user_id": 1,
    "decision": "yes"
}
```

**Decision Options:**
- `yes` - Wants to proceed with the relationship
- `no` - Wants to disconnect
- `need_more_time` - Needs 7 more days to decide

**Response (Both users agreed):**
```json
{
    "status": "success",
    "message": "Congratulations! Admin will contact both parties to proceed with this relation.",
    "data": {
        "chat_status": "completed",
        "both_decided": true,
        "decision_deadline": null
    }
}
```

**Response (Need more time):**
```json
{
    "status": "success",
    "message": "You have 7 days to make a decision.",
    "data": {
        "chat_status": "need_more_time",
        "both_decided": false,
        "decision_deadline": "2024-11-21T10:30:00.000000Z"
    }
}
```

---

## 8. Get User Chats
**POST** `/api/v1/chat/user-chats`

Get all active chats for a user.

**Request:**
```json
{
    "user_id": 1
}
```

**Response:**
```json
{
    "status": "success",
    "data": [
        {
            "chat_id": 1,
            "other_user": {
                "id": 2,
                "name": "John Doe",
                "email": "john@example.com"
            },
            "status": "active",
            "questions_exchanged": 3,
            "unread_count": 2,
            "updated_at": "2024-11-14T10:30:00.000000Z",
            "show_decision_prompt": false
        }
    ]
}
```

---

## 9. Get Chat Stats
**POST** `/api/v1/chat/stats`

Get statistics for a specific chat.

**Request:**
```json
{
    "chat_id": 1,
    "user_id": 1
}
```

**Response:**
```json
{
    "status": "success",
    "data": {
        "questions_exchanged": 7,
        "next_milestone": 10,
        "questions_until_decision": 3,
        "status": "active",
        "show_decision_prompt": false,
        "decision_deadline": null,
        "days_remaining": null
    }
}
```

---

## 10. Send Decision Reminders (Cron Job)
**POST** `/api/v1/chat/send-reminders`

Sends reminders to users on day 6 of the 7-day decision period.

**Response:**
```json
{
    "status": "success",
    "message": "Sent 5 reminders"
}
```

---

## 11. Auto Disconnect Expired Chats (Cron Job)
**POST** `/api/v1/chat/auto-disconnect`

Automatically disconnects chats where the 7-day decision period has expired.

**Response:**
```json
{
    "status": "success",
    "message": "Disconnected 3 expired chats"
}
```

---

## Chat Flow

### Step 1: Initialize Chat
When a connection is accepted, initialize a chat session.

### Step 2: Browse Categories
Users see available categories (Finance, Family, Hobby, etc.)

### Step 3: Select Question
User selects a category and chooses a question to ask.

### Step 4: Send Question
Question is sent to the other user with 4 answer options.

### Step 5: Answer Question
Receiver selects one of the 4 answer options.

### Step 6: Continue Conversation
Repeat steps 2-5 until 5 questions are exchanged.

### Step 7: Decision Prompt
After every 5 questions, both users are shown:
"Do you still want to continue with the questions or have you made a decision?"

**Options:**
- **Yes** → If both agree: Show congratulations message and notify admin
- **No** → Profiles are disconnected
- **Need More Time** → 7-day timer starts

### Step 8: Reminder (Day 6)
If "Need More Time" was selected, on day 6 both users receive:
"Have you made a decision for this proposal?"

### Step 9: Auto Disconnect
If 7 days pass without a decision, profiles are automatically disconnected.

---

## Optimization Features

1. **Indexed Queries** - All database tables have proper indexes for fast retrieval
2. **Eager Loading** - Relationships are pre-loaded to reduce queries
3. **Pagination** - Messages are paginated to reduce payload size
4. **Selective Loading** - Only necessary fields are selected
5. **Exclusion Logic** - Already asked questions are excluded from query
6. **Status Tracking** - Chat status prevents unnecessary processing

---

## Cron Job Setup

Add to `app/Console/Kernel.php`:

```php
protected function schedule(Schedule $schedule)
{
    // Send reminders daily at 9 AM
    $schedule->call(function () {
        Http::post(config('app.url') . '/api/v1/chat/send-reminders');
    })->dailyAt('09:00');

    // Auto-disconnect expired chats daily at 10 AM
    $schedule->call(function () {
        Http::post(config('app.url') . '/api/v1/chat/auto-disconnect');
    })->dailyAt('10:00');
}
```

---

## Error Handling

All endpoints return consistent error responses:

```json
{
    "status": "error",
    "message": "Error description",
    "errors": {
        "field_name": ["Error message"]
    }
}
```

## Status Codes

- `200` - Success
- `400` - Bad Request
- `403` - Forbidden
- `404` - Not Found
- `422` - Validation Error
- `500` - Server Error
