# Chat Feature Implementation Summary

## Overview
Implemented a complete chat system for recruiters to communicate with shortlisted candidates, with support for job-specific conversations and Android app compatibility.

## Key Features

### 1. Job-Specific Chat Threads
- Each conversation is tied to a specific job
- Recruiters can have multiple chat threads with the same candidate (one per job)
- Chat button appears on job detail page for shortlisted candidates

### 2. Dual User Support
- **Recruiter View**: Shows shortlisted candidates from their company
- **Candidate View**: Shows all recruiters who have messaged them

### 3. Android App Compatibility
- Messages include `job_id` field (required for Android app visibility)
- Automatically finds job_id from shortlisted applications
- Accepts job_id parameter from job detail page

## Files Modified

### 1. `/public/chat.php`
- Added job_id parameter handling
- Detects user type (recruiter vs candidate) using `user_companies` table
- Separate queries for recruiter and candidate views

### 2. `/app/views/chat.php`
- Added job_id to message send AJAX call
- Dynamic message insertion before page reload
- Auto-scroll to latest messages

### 3. `/public/ajax/send-message.php`
- Accepts optional job_id parameter
- Auto-detects job_id from shortlisted application if not provided
- Ensures all messages have valid job_id for Android app

### 4. `/app/views/job_detail.php`
- Added "Chat" button for shortlisted candidates (job_status = 2)
- Links to chat with both candidate_id and job_id parameters
- Purple button matching brand colors

### 5. `/public/debug-session.php` (Created)
- Debug utility to check session user info
- Useful for troubleshooting login issues

## Database Schema Used

### Tables
- `chat_message` - Stores all messages
- `message_read_status` - Tracks read/unread status
- `users` - User information
- `user_companies` - Links recruiters to companies
- `users_job` - Job applications with status
- `company_jobs` - Job postings

### Key Fields in `chat_message`
- `from_id` - Sender user ID
- `to_id` - Recipient user ID
- `job_id` - **CRITICAL** for Android app visibility
- `text` - Message content
- `created_date` - Timestamp

### Key Fields in `message_read_status`
- `chat_message_id` - Link to message
- `user_id` - Who read it
- `status` - Read status (1 = read, 0 = unread)

## User Flows

### Flow 1: Recruiter Initiates Chat from Job Detail
1. Recruiter views job detail page (e.g., `job_detail.php?id=895`)
2. Sees shortlisted candidates with "Chat" button
3. Clicks "Chat" → Goes to `chat.php?candidate_id=16&job_id=895`
4. Sends message → Message saved with job_id=895
5. Message appears in Android app for candidate

### Flow 2: Candidate Views Chats
1. Candidate logs into web app
2. Goes to chat.php
3. Sees all recruiters who have messaged them
4. Can reply to any recruiter
5. Messages sync with Android app

### Flow 3: Multiple Job Conversations
1. Candidate applies to Job A and Job B from same recruiter
2. Gets shortlisted for both
3. Recruiter chats from Job A detail page → Creates thread with job_id=A
4. Recruiter chats from Job B detail page → Creates thread with job_id=B
5. Two separate conversations in Android app (one per job)

## Technical Decisions

### Why job_id is Required
The Android app filters conversations based on `job_id`. Messages with `job_id = 0` are not visible in the Android app. This was discovered through testing and database analysis.

### Why Separate Recruiter/Candidate Views
- Recruiters should only see candidates they've shortlisted
- Candidates should see all recruiters who contacted them
- Different data requirements for each view

### Why Auto-Detection of job_id
- Allows chat to work from main chat list (without job context)
- Gracefully handles messages sent without explicit job_id
- Maintains backward compatibility

## Testing

### Test Scenarios Completed
1. ✅ Recruiter sends message to shortlisted candidate
2. ✅ Message appears in database with correct job_id
3. ✅ Candidate can see message when logged in
4. ✅ Message appears in Android app
5. ✅ Multiple conversations per candidate work correctly
6. ✅ Read/unread status updates correctly

### Test URLs
- Job Detail: `https://recruiter:8890/public/job_detail.php?id=895`
- Chat: `https://recruiter:8890/public/chat.php`
- Chat with Job: `https://recruiter:8890/public/chat.php?candidate_id=16&job_id=895`

## Known Issues & Future Enhancements

### Current Limitations
- Page reloads after sending message (could be improved with WebSocket/long polling)
- No message edit/delete functionality
- No file attachments (field exists but not implemented)
- No typing indicators

### Potential Enhancements
- Real-time messaging using WebSocket
- File/image attachments
- Message search
- Conversation archive
- Bulk messaging
- Message templates
- Read receipts with timestamps

## Security Considerations

### Implemented
- Session-based authentication
- SQL injection prevention (prepared statements)
- XSS prevention (htmlspecialchars on output)
- User type validation (recruiter vs candidate)

### To Consider
- Rate limiting on message sending
- Spam detection
- Inappropriate content filtering
- Message retention policy

## Database Queries Performance

### Optimizations Made
- Use of indexes on foreign keys (from_id, to_id, user_id)
- LIMIT clauses on conversation lists (100 max)
- Efficient subqueries for last message
- GROUP BY to prevent duplicates

### Potential Improvements
- Add composite index on (from_id, to_id, created_date)
- Cache conversation list
- Pagination for messages in long conversations

---

**Last Updated**: November 16, 2025
**Status**: Production Ready
**Android App Compatibility**: Verified
