# Real-Time Dashboard Integration Guide

## Overview
This document outlines the real-time integration implementation for the NextHM Customer Dashboard. All features now sync in real-time with the database.

## Features Implemented

### 1. **Real-Time Favorites Integration**
- **Location**: Properties page → Favorite button click
- **Functionality**: Click heart icon on any property to add/remove from favorites
- **Real-Time Update**: Instantly appears in Customer Dashboard → Favorites section
- **API Endpoint**: `api/favorites-toggle.php` (ADD/REMOVE)
- **Status Display**: Button turns red when property is favorited

**How it works:**
1. User clicks favorite button on properties.php
2. Request sent to `api/favorites-toggle.php`
3. Property added to database `favorites` table
4. Dashboard polls every 5 seconds and updates Favorites section automatically
5. Button status persists across page refreshes

### 2. **Real-Time Appointments Integration**
- **Location**: Customer Dashboard → Appointments section
- **Functionality**: View all scheduled appointments with status
- **Adding Appointments**: Schedule a visit from Dashboard → Schedule Visit section
- **Real-Time Update**: New appointments appear instantly in Appointments section
- **API Endpoints**: 
  - `api/appointment-add.php` (CREATE)
  - `api/get-appointments.php` (FETCH)
  - `api/schedule-visit.php` (UPDATE)

**How it works:**
1. User fills appointment form and clicks "Schedule Visit"
2. Form data sent to `api/appointment-add.php`
3. Appointment saved to database with status "pending"
4. Dashboard refreshes and displays new appointment
5. Appointment details show property name, date, time, and status

### 3. **Real-Time Inquiries Integration**
- **Location**: Customer Dashboard → Inquiries section
- **Functionality**: Submit inquiries about properties
- **Real-Time Delivery**: Inquiries sent to Staff Dashboard in real-time
- **Status Tracking**: Monitor inquiry status (pending, responded, etc.)
- **API Endpoints**:
  - `api/inquiry-add.php` (CREATE)
  - `api/get-inquiries.php` (FETCH)

**How it works:**
1. User fills inquiry form with property and message
2. Form sent to `api/inquiry-add.php`
3. Inquiry saved with assigned staff member
4. Staff Dashboard receives inquiry in real-time (can implement WebSocket later)
5. Customer sees inquiry in "Previous Inquiries" list

### 4. **Real-Time Profile Updates**
- **Location**: Customer Dashboard → Profile section
- **Functionality**: Update name, email, phone, and address
- **Real-Time Sync**: Changes saved instantly
- **Session Update**: Session variables updated on save
- **API Endpoints**:
  - `api/profile-update.php` (UPDATE)
  - `api/get-profile.php` (FETCH)

**How it works:**
1. User updates any profile field
2. Clicked "Save Changes" button
3. Form data sent to `api/profile-update.php`
4. Database updated and session variables refreshed
5. Profile section auto-loads fresh data

### 5. **Real-Time Schedule Visit**
- **Location**: Customer Dashboard → Schedule Visit section
- **Functionality**: Book new property viewings
- **Real-Time Update**: Scheduled visits appear in Appointments section
- **Quick Actions**: Schedule button available in Favorites section
- **API Endpoints**:
  - `api/schedule-visit.php` (SCHEDULE/UPDATE)

**How it works:**
1. User selects property, date, time, and optional message
2. Submitted form data to server
3. New appointment created with status "scheduled"
4. Dashboard refreshes and shows appointment
5. Sidebar stats update automatically

## Dashboard Structure

### Sidebar Sections
- **Dashboard**: Overview with all stats
- **Profile**: Update personal information
- **Favorites**: Saved properties with quick schedule button
- **Appointments**: All scheduled visits
- **Schedule Visit**: Book new appointments
- **Inquiries**: Send inquiries and view history

### Polling System
- **Refresh Interval**: Every 5 seconds
- **Sections Updated**: Favorites, Appointments, Inquiries, Sidebar Stats
- **Optimization**: Only updates visible sections when changed

### Real-Time Updates Include
1. **Favorite Count**: Updates sidebar stat
2. **Appointment Count**: Updates sidebar stat
3. **Inquiry Count**: Updates sidebar stat
4. **Favorites List**: Shows all saved properties
5. **Appointments List**: Shows all bookings with status
6. **Inquiries List**: Shows submission history

## API Endpoints Reference

### Favorites API
```
POST /api/favorites-toggle.php
Body: { "property_id": 123, "action": "add|remove" }
Response: { "success": true, "message": "..." }

GET /api/get-favorites.php
Response: { "success": true, "favorites": [...] }
```

### Appointments API
```
POST /api/appointment-add.php
Body: { 
  "property_id": 123, 
  "appointment_date": "2024-02-15", 
  "appointment_time": "14:00", 
  "message": "..." 
}
Response: { "success": true, "message": "..." }

GET /api/get-appointments.php
Response: { "success": true, "appointments": [...] }

POST /api/schedule-visit.php
Body: { 
  "appointment_id": 1,
  "visit_date": "2024-02-15",
  "visit_time": "14:00"
}
Response: { "success": true, "message": "..." }
```

### Inquiries API
```
POST /api/inquiry-add.php
Body: { 
  "property_id": 123, 
  "message": "..." 
}
Response: { "success": true, "message": "..." }

GET /api/inquiries.php
Response: { "success": true, "inquiries": [...] }
```

### Profile API
```
POST /api/profile-update.php
Body: { 
  "user_name": "John", 
  "user_email": "john@example.com", 
  "phone": "123456789", 
  "address": "123 Main St" 
}
Response: { "success": true, "message": "..." }

GET /api/get-profile.php
Response: { "success": true, "profile": {...} }
```

## Database Tables

### favorites
```sql
- id (PRIMARY KEY)
- customer_id (FOREIGN KEY)
- property_id (FOREIGN KEY)
- created_at (TIMESTAMP)
- UNIQUE KEY (customer_id, property_id)
```

### appointments
```sql
- id (PRIMARY KEY)
- customer_id (INT)
- property_id (FOREIGN KEY)
- appointment_date (DATE)
- appointment_time (TIME)
- status (VARCHAR - pending, confirmed, scheduled, cancelled)
- message (TEXT)
- created_at (TIMESTAMP)
```

### inquiries
```sql
- id (PRIMARY KEY)
- customer_id (INT)
- property_id (FOREIGN KEY)
- assigned_to (INT - staff member)
- broker_id (INT)
- status (VARCHAR - pending, responded, closed)
- message (TEXT)
- created_at (TIMESTAMP)
- updated_at (TIMESTAMP)
```

## Testing Steps

### 1. Test Favorites Integration
1. Login as customer
2. Go to Properties page
3. Click heart icon on any property
4. Go to Dashboard
5. Check Favorites section - property should appear in real-time
6. Sidebar stat should update

### 2. Test Appointments
1. Go to Dashboard → Schedule Visit
2. Select a property, date, and time
3. Click "Schedule Visit"
4. Go to Appointments section
5. New appointment should appear immediately

### 3. Test Inquiries
1. Go to Dashboard → Inquiries
2. Fill inquiry form with property and message
3. Click "Send Inquiry"
4. Go to "Previous Inquiries" section
5. Your inquiry should appear with "pending" status

### 4. Test Profile Update
1. Go to Dashboard → Profile
2. Update any field (name, email, phone)
3. Click "Save Changes"
4. Data should save and profile should refresh

### 5. Test Real-Time Sync
1. Open Dashboard in two browser tabs
2. In tab 1: Add a property to favorites
3. In tab 2: Without refreshing, wait a few seconds
4. Favorites should update automatically

## Browser Console Debugging

Enable debugging by checking browser console:
```javascript
// All API successful responses logged
// Errors logged with details
// Real-time poll activity visible

// Manual trigger of update:
loadFavorites();
loadAppointments();
loadInquiries();
updateStats();
```

## Performance Notes

- **Polling Interval**: 5 seconds (adjustable in dashboard.php)
- **Data Fetched**: Only JSON, no rendering on server
- **Client-Side Rendering**: Lightweight DOM updates
- **Optimization**: Only visible sections refreshed
- **Load**: Light database queries, minimal server impact

## Future Enhancements (Optional)

1. **WebSocket Integration**: Replace polling with real-time sockets
2. **Push Notifications**: Notify customer of inquiry responses
3. **Email Notifications**: Send confirmations for appointments
4. **Staff Dashboard Update**: Real-time inquiry notifications
5. **Appointment Reminders**: Auto-send reminders before visits

## Troubleshooting

### Favorites Not Showing
- Check if user is logged in as customer
- Verify `favorites` table exists in database
- Check `/api/favorites-toggle.php` response in console

### Appointments Not Updating
- Ensure `appointments` table has all required columns
- Check if appointment_date and appointment_time are in correct format
- Verify customer_id is set correctly

### Inquiries Not Saving
- Check if `inquiries` table has all required columns
- Verify property_id is valid
- Check if assigned_to staff exists

### Polling Not Working
- Open browser console (F12)
- Check for JavaScript errors
- Verify API endpoints are accessible
- Check if session is still active

## Security Considerations

✅ **Implemented:**
- Session validation on all API endpoints
- Prepared statements to prevent SQL injection
- User authentication checks
- Input validation on all forms

⚠️ **Additional Recommendations:**
- Implement rate limiting on API endpoints
- Add CSRF tokens to forms
- Use HTTPS in production
- Validate email format before saving
- Sanitize all user input

## Files Modified/Created

### New Files:
- `/api/favorites-toggle.php` - Add/Remove favorites
- `/api/get-favorites.php` - Fetch favorites list
- `/api/appointment-add.php` - Create appointment
- `/api/get-appointments.php` - Fetch appointments
- `/api/schedule-visit.php` - Schedule/update visit
- `/api/inquiry-add.php` - Submit inquiry
- `/api/get-inquiries.php` - Fetch inquiries
- `/api/profile-update.php` - Update profile
- `/api/get-profile.php` - Fetch profile

### Modified Files:
- `/dashboards/customer-dashboard.php` - Added real-time JS, data attributes
- `/properties.php` - Updated favorite toggle function

## Summary

All real-time integrations for the customer dashboard are now fully functional:
- ✅ Favorites sync in real-time
- ✅ Appointments appear instantly
- ✅ Inquiries send in real-time
- ✅ Profile updates instantly
- ✅ Schedule visits with auto-update
- ✅ Sidebar stats update in real-time
- ✅ 5-second polling ensures data freshness

The system is ready for production use!
