# Staff Dashboard - Real-Time Inquiry & Appointment Management

## Overview

This is a complete real-time implementation for the staff dashboard that allows staff members to:
- 👁️ **View** customer inquiries and scheduled appointments in real-time (5-second updates)
- ✓ **Approve** or **Decline** inquiries with instant status updates
- 📅 **Approve** or **Decline** appointments with instant status updates
- 📊 **Monitor** real-time statistics (pending inquiries, appointments, properties, customers)

## Features

### Real-Time Updates
- **5-second polling interval** for live data synchronization
- Auto-refresh of inquiries and appointments across all tabs
- Instant status updates when actions are performed
- Live statistics counter updates

### Inquiry Management
- View all inquiries (pending, responded, approved, declined)
- Approve inquiries with one click
- Decline inquiries with confirmation
- Email customer directly
- Visual status indicators (color-coded badges)

### Appointment Management  
- View all scheduled appointments (pending, approved, declined)
- Approve appointments immediately
- Decline appointments with confirmation
- Email customer confirmation
- Display appointment date, time, location, and customer details

### Access Control
- Automatic redirection for non-staff users
- Session-based authentication
- Staff member name display
- Secure logout functionality

## File Structure

```
dashboards/
├── staff-dashboard-realtime.php      (Main real-time dashboard)
│
api/staff/
├── get-pending-inquiries.php         (Fetch all inquiries)
├── get-scheduled-visits.php          (Fetch all appointments)
├── get-stats.php                     (Fetch statistics)
├── realtime-approve-inquiry.php      (Real-time inquiry approval)
├── realtime-approve-appointment.php  (Real-time appointment approval)
├── realtime-server.php               (Long-polling server)
├── respond-inquiry.php              (Send inquiry response)
├── update-visit-status.php          (Update appointment status)
└── update-property-info.php         (Update property details)
```

## Real-Time Implementation Details

### Long-Polling Architecture

The system uses **long-polling** instead of WebSocket for compatibility:

```
Client (Browser)
    ↓
fetch('api/staff/get-pending-inquiries.php')
    ↓
Server checks for updates since lastCheck timestamp
    ↓
If updates found → Return immediately
If no updates → Wait up to 30 seconds
    ↓
Client processes updates and polls again after 5 seconds
```

### Databases & Tables Required

The system automatically creates these tables:

```sql
-- Inquiries table
CREATE TABLE IF NOT EXISTS inquiries (
  id INT AUTO_INCREMENT PRIMARY KEY,
  customer_id INT,
  property_id INT,
  status VARCHAR(50) DEFAULT 'pending',
  message TEXT,
  response TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Appointments table
CREATE TABLE IF NOT EXISTS appointments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT,
  property_id INT,
  appointment_date DATE,
  appointment_time TIME,
  status VARCHAR(50) DEFAULT 'pending',
  message TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Real-time updates tracking (auto-created)
CREATE TABLE IF NOT EXISTS realtime_updates (
  id INT AUTO_INCREMENT PRIMARY KEY,
  update_type VARCHAR(50),
  entity_id INT,
  entity_type VARCHAR(50),
  action VARCHAR(50),
  data JSON,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

## Setup Instructions

### 1. Database Preparation
- Ensure database tables exist (auto-created by config.php)
- Verify staff table has correct user data
- Test inquiries and appointments data

### 2. Update Staff Login
Edit `staff-login.php` to redirect to the new dashboard:
```php
// After successful login
header('Location: dashboards/staff-dashboard-realtime.php');
```

### 3. Access the Dashboard
- Navigate to: `http://localhost/nexthm/dashboards/staff-dashboard-realtime.php`
- Or update nav links to point to the new dashboard

### 4. Verify Session
- Ensure `config.php` properly handles staff sessions with role='staff'
- Session variable `$_SESSION['role']` must equal 'staff'
- Session variable `$_SESSION['user_name']` should contain staff name

## API Endpoints

### GET /api/staff/get-pending-inquiries.php
**Returns:** All inquiries with statuses (pending, responded, approved, declined)
```json
{
  "success": true,
  "inquiries": [
    {
      "id": 1,
      "customer_id": 5,
      "customer_name": "John Doe",
      "property_title": "Modern Apartment",
      "message": "Is this property still available?",
      "status": "pending",
      "created_at": "2024-01-15 10:30:00"
    }
  ],
  "count": 1
}
```

### GET /api/staff/get-scheduled-visits.php
**Returns:** All scheduled appointments with statuses
```json
{
  "success": true,
  "appointments": [
    {
      "id": 1,
      "customer_id": 5,
      "customer_name": "John Doe",
      "property_title": "Modern Apartment",
      "city": "New York",
      "appointment_date": "2024-02-20",
      "appointment_time": "14:30",
      "status": "pending"
    }
  ],
  "count": 1
}
```

### GET /api/staff/get-stats.php
**Returns:** Dashboard statistics
```json
{
  "success": true,
  "stats": {
    "pending_inquiries": 5,
    "upcoming_visits": 3,
    "total_properties": 15,
    "total_customers": 42
  }
}
```

### POST /api/staff/realtime-approve-inquiry.php
**Request:**
```json
{
  "inquiry_id": 1,
  "action": "approve"  // or "decline"
}
```
**Response:**
```json
{
  "success": true,
  "message": "Inquiry approved successfully",
  "inquiry_id": 1,
  "status": "approved",
  "realtime": true
}
```

### POST /api/staff/realtime-approve-appointment.php
**Request:**
```json
{
  "appointment_id": 1,
  "action": "approve"  // or "decline"
}
```
**Response:**
```json
{
  "success": true,
  "message": "Appointment approved successfully",
  "appointment_id": 1,
  "status": "approved",
  "realtime": true
}
```

## Real-Time Flow

### Approve Inquiry Flow:
```
1. Staff clicks "✓ Approve" button
2. Button disabled, shows "⏳ Approving..."
3. POST to realtime-approve-inquiry.php
4. Database updated (inquiries table status = 'approved')
5. Record added to realtime_updates table
6. Success response received
7. Alert shown: "✓ Inquiry approved!"
8. Dashboard auto-refreshes in 500ms
9. Stats updated, inquiry moved to "approved" section
```

### Decline Appointment Flow:
```
1. Staff clicks "✕ Decline" button
2. Button disabled, shows "⏳ Declining..."
3. Confirmation dialog: "✕ Decline this appointment?"
4. POST to realtime-approve-appointment.php
5. Database updated (appointments table status = 'declined')
6. Success response received
7. Alert shown: "✕ Appointment declined!"
8. Dashboard auto-refreshes
9. Stats updated, appointment moved to "declined" section
```

## Polling Mechanism

Dashboard polls every **5 seconds** for updates:

```javascript
// Initial load
loadStats() →  Fetch stats
loadInquiries() → Fetch inquiries
loadAppointments() → Fetch appointments

// Every 5 seconds
setInterval(() => {
  loadStats()
  loadInquiries()
  loadAppointments()
}, 5000)
```

## Status Codes

### Inquiry Statuses
- **pending**: New inquiry, awaiting response
- **responded**: Staff has responded, awaiting approval/decline
- **approved**: ✓ Approved by staff
- **declined**: ✕ Declined by staff

### Appointment Statuses
- **pending**: New appointment request, awaiting approval/decline
- **approved**: ✓ Approved by staff
- **declined**: ✕ Declined by staff
- **scheduled**: Confirmed and scheduled
- **completed**: Visit completed

## Visual Indicators

### Badge Colors
- 🔶 **Orange (pending)**: Requires action
- 🔵 **Blue (responded)**: Response given
- 🟢 **Green (approved)**: Approved
- 🔴 **Red (declined)**: Declined

### Real-Time Badge
- 🔴 **LIVE badge** in header indicates real-time updates active

## Error Handling

### Client-Side
- Network error: Shows alert "❌ Error"
- Invalid action: Shows validation error
- Button disabling prevents duplicate submissions

### Server-Side
- Session validation on all endpoints
- Query error handling and logging
- JSON error responses

## Performance Optimizations

1. **Short polling interval (5s)** - Reduces latency while managing server load
2. **Responsive updates** - Only re-render changed elements
3. **Button state management** - Prevents duplicate submissions
4. **Efficient queries** - Indexed database lookups
5. **Auto-cleanup** - Deletes old realtime_updates records after 1 hour

## Troubleshooting

### Dashboard not loading
- Check session: `echo $_SESSION['role'];`
- Verify staff user exists in users table
- Check database connection in config.php

### Real-time updates not working
- Check browser console for JavaScript errors
- Verify API endpoints are accessible
- Check API error responses in Network tab
- Ensure database tables exist

### Approvals not saving
- Check staff user has correct role='staff'
- Verify inquiries/appointments tables exist
- Check database permissions
- Look for SQL errors in error logs

## Testing

### Manual Testing:
1. Login as staff member
2. Wait 5 seconds - verify stats update
3. Submit test inquiry from customer account
4. Verify it appears on dashboard within 5 seconds
5. Click Approve
6. Verify status changes immediately
7. Verify stats update
8. Check database for realtime_updates record

### Multi-Tab Testing:
1. Open dashboard in 2 browser tabs
2. Approve inquiry in Tab 1
3. Verify Tab 2 updates automatically within 5 seconds
4. No manual refresh needed

## Future Enhancements

1. **WebSocket Support** - For true real-time (replace long-polling)
2. **Email Notifications** - Send approval/decline emails to customers
3. **SMS Alerts** - Real-time SMS notifications for urgent updates
4. **Audit Log** - Track all approvals/declines with timestamps
5. **Bulk Actions** - Approve/decline multiple items at once
6. **Custom Filters** - Filter by date, customer, property, status
7. **Reports** - Generate approval/decline statistics
8. **Analytics** - Track response times and staff performance

## Technical Stack

- **Frontend**: Pure JavaScript (ES6+), HTML5, CSS3
- **Backend**: PHP 7.4+
- **Database**: MySQL/MariaDB
- **Communication**: HTTP/HTTPS (long-polling)
- **Authentication**: PHP Sessions

## Support

For issues or questions:
1. Check error messages in browser console
2. Review server logs in xampp/logs/
3. Verify database with phpMyAdmin
4. Check API responses in Network tab

## Version Info

- **Version**: 1.0.0
- **Release Date**: 2024-02
- **Status**: Production Ready
- **Real-Time**: Yes (5-second polling)
