# FAREN Chat System - Quick Start Guide

## ✅ What's Fixed

### 1. **API Response Issues**
- Fixed output buffering to prevent HTML mixed with JSON
- Proper headers set before any output
- Automatic database table creation on first run
- Clean error handling with proper JSON responses

### 2. **Database Auto-Setup**
- `chat_sessions` table - stores chat session data
- `chat_messages` table - stores conversation messages
- Tables created automatically on first API call
- Proper indexes and foreign keys

### 3. **Test Page Improvements**
- Better API URL detection
- Robust JSON parsing (text → JSON)
- Detailed error logging
- Full integration test workflow

---

## 🚀 How to Use

### Option 1: Quick Test
Visit one of these pages in your browser:

```
http://localhost/interior/chat-system-test.html
http://localhost/interior/chat-test-debug.html
```

**Test Order:**
1. Click "Check API Status" → Should show API is ready
2. Click "Start New Chat" → Should create session
3. Type message and click "Send Message"
4. Click "Run Full Test" → Runs all tests in sequence

### Option 2: Simple Setup
Visit: `http://localhost/interior/setup.html`

Buttons:
- "Setup Database Tables" → Creates tables (if needed)
- "Test API" → Quick API health check

### Option 3: Direct cURL Test
```bash
# Check API status
curl -X GET "http://localhost/interior/auth-system/api/chat-ai-v3.php?action=get_status"

# Start chat
curl -X POST "http://localhost/interior/auth-system/api/chat-ai-v3.php?action=start_chat" \
  -H "Content-Type: application/json" \
  -d '{"category":"service","user_email":"test@test.com"}'

# Send message
curl -X POST "http://localhost/interior/auth-system/api/chat-ai-v3.php?action=send_message" \
  -H "Content-Type: application/json" \
  -d '{
    "session_id":"YOUR_SESSION_ID",
    "message":"Hello",
    "category":"service",
    "user_email":"test@test.com"
  }'
```

---

## 📝 API Endpoints

### GET `/auth-system/api/chat-ai-v3.php?action=get_status`
**Response:**
```json
{
  "success": true,
  "connected": true,
  "status": "ready",
  "service": "openai",
  "timestamp": "2026-03-24 18:20:31"
}
```

### POST `/auth-system/api/chat-ai-v3.php?action=start_chat`
**Request:**
```json
{
  "category": "service",
  "user_email": "user@example.com"
}
```

**Response:**
```json
{
  "success": true,
  "session_id": "chat_xxxxx_xxxxx",
  "category": "service",
  "welcome_message": "Welcome to FAREN Services!...",
  "timestamp": "2026-03-24 18:20:31"
}
```

### POST `/auth-system/api/chat-ai-v3.php?action=send_message`
**Request:**
```json
{
  "session_id": "chat_xxxxx_xxxxx",
  "message": "Your message here",
  "category": "service",
  "user_email": "user@example.com"
}
```

**Response:**
```json
{
  "success": true,
  "session_id": "chat_xxxxx_xxxxx",
  "message": "Your message here",
  "response": "AI response here...",
  "category": "service",
  "timestamp": "2026-03-24 18:20:31"
}
```

---

## 🔧 Technical Details

### Categories
- `service` - Interior design services inquiry
- `project` - Project discussion & consultation
- `order` - Order management & support
- `contact` - General contact & information

### Features
✅ Real-time AI responses (when API key configured)
✅ Fallback responses (when API key not available)
✅ Session persistence
✅ Message history
✅ Multi-category support
✅ User tracking via email

### Database Tables

**chat_sessions**
```sql
CREATE TABLE chat_sessions (
  id INT AUTO_INCREMENT PRIMARY KEY,
  session_id VARCHAR(100) UNIQUE NOT NULL,
  category VARCHAR(50) NOT NULL,
  user_email VARCHAR(100),
  started_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  ended_at DATETIME NULL,
  is_active TINYINT DEFAULT 1
)
```

**chat_messages**
```sql
CREATE TABLE chat_messages (
  id INT AUTO_INCREMENT PRIMARY KEY,
  session_id VARCHAR(100) NOT NULL,
  sender VARCHAR(50) NOT NULL,
  message LONGTEXT NOT NULL,
  category VARCHAR(50),
  user_identifier VARCHAR(100),
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
```

---

## 📊 Testing Workflows

### Workflow 1: Verify Setup
1. Visit `chat-system-test.html`
2. Click "Check API Status"
3. Should see: "✅ API IS WORKING!"

### Workflow 2: Full Chat Test
1. Visit `chat-system-test.html`
2. Select category from dropdown
3. Click "Start New Chat"
4. Type message in text box
5. Click "Send Message"
6. View AI response and chat preview

### Workflow 3: Integrated Test
1. Visit `chat-system-test.html`
2. Click "Run Full Test"
3. Monitor all steps completing successfully

---

## 🐛 Troubleshooting

### "Unexpected token '<r'" Error
- **Cause**: HTML returned instead of JSON
- **Fix**: Check API file is readable, restart server

### "Unexpected end of JSON input" Error
- **Cause**: Empty response from server
- **Fix**: Check database connection, verify .env file exists

### "API is not working" Message
- **Cause**: API endpoint not reachable
- **Fix**: Verify Apache/PHP is running, check file permissions

### No AI Response (Fallback Only)
- **Cause**: OpenAI API key not configured
- **Status**: ✅ Normal - API returns fallback responses
- **Fix**: Add `OPENAI_API_KEY` to `.env` file

---

## ✅ Verification Checklist

- [ ] Visit `http://localhost/interior/chat-system-test.html`
- [ ] Click "Check API Status" - should show GREEN ✓
- [ ] Click "Start New Chat" - should create session
- [ ] Send test message - should get response
- [ ] Check database: `SELECT * FROM chat_sessions;`
- [ ] Check database: `SELECT * FROM chat_messages;`

---

## 📞 Support Files

| File | Purpose |
|------|---------|
| `chat-system-test.html` | Main test interface |
| `chat-test-debug.html` | Detailed debugging |
| `setup.html` | Quick setup page |
| `auth-system/api/chat-ai-v3.php` | API endpoint |
| `.env` | Environment variables |

---

**Last Updated**: March 24, 2026
**Status**: ✅ Ready for Testing
