# Staff Dashboard Real-Time - Quick Reference Guide

## 🚀 Access URLs

### Main Dashboard
**URL:** `http://localhost/nexthm/dashboards/staff-dashboard-realtime.php`

**Requirements:**
- ✅ Login as staff user (role = 'staff')
- ✅ Session must be active
- ✅ Database connected

---

## 📊 API Endpoints

### 🔍 GET Endpoints (Data Retrieval)

#### Get Pending Inquiries
```
GET /api/staff/get-pending-inquiries.php
```
**Returns:** All inquiries with all statuses (pending, responded, approved, declined)
**Response:** JSON array of inquiry objects
**Real-Time:** No (called by dashboard every 5s)

#### Get Scheduled Appointments
```
GET /api/staff/get-scheduled-visits.php
```
**Returns:** All appointment requests with all statuses
**Response:** JSON array of appointment objects  
**Real-Time:** No (called by dashboard every 5s)

#### Get Statistics
```
GET /api/staff/get-stats.php
```
**Returns:** Dashboard statistics (pending counts, totals)
**Response:** JSON with stats object
**Real-Time:** No (called by dashboard every 5s)

#### Real-Time Server (Long-Polling)
```
GET /api/staff/realtime-server.php?lastCheck=TIMESTAMP&type=all
```
**Purpose:** Long-polling server for push updates
**Parameters:**
- `lastCheck` - Unix timestamp of last check
- `type` - 'inquiries', 'appointments', or 'all'

---

### 📝 POST Endpoints (Actions)

#### Approve/Decline Inquiry (REAL-TIME)
```
POST /api/staff/realtime-approve-inquiry.php
Content-Type: application/json

{
  "inquiry_id": 1,
  "action": "approve"  // or "decline"
}
```
**Response:**
```json
{
  "success": true,
  "message": "Inquiry approved successfully",
  "inquiry_id": 1,
  "status": "approved",
  "realtime": true
}
```

#### Approve/Decline Appointment (REAL-TIME)
```
POST /api/staff/realtime-approve-appointment.php
Content-Type: application/json

{
  "appointment_id": 1,
  "action": "approve"  // or "decline"
}
```
**Response:**
```json
{
  "success": true,
  "message": "Appointment approved successfully",
  "appointment_id": 1,
  "status": "approved",
  "realtime": true
}
```

#### Respond to Inquiry
```
POST /api/staff/respond-inquiry.php
Content-Type: application/json

{
  "inquiry_id": 1,
  "response": "Thank you for your interest..."
}
```

#### Update Visit Status
```
POST /api/staff/update-visit-status.php
Content-Type: application/json

{
  "appointment_id": 1,
  "status": "scheduled"  // or "completed"
}
```

---

## 📂 File Structure

```
nexthm/
├── dashboards/
│   ├── staff-dashboard-realtime.php (438 lines) ⭐
│   └── admin-dashboard.php (existing)
│
├── api/staff/
│   ├── realtime-approve-inquiry.php ⭐ (NEW)
│   ├── realtime-approve-appointment.php ⭐ (NEW)
│   ├── realtime-server.php ⭐ (NEW)
│   ├── get-pending-inquiries.php (existing)
│   ├── get-scheduled-visits.php (existing)
│   ├── get-stats.php (existing)
│   ├── respond-inquiry.php (existing)
│   ├── update-visit-status.php (existing)
│   └── update-property-info.php (existing)
│
├── STAFF_REALTIME_IMPLEMENTATION.md ⭐ (NEW)
├── STAFF_REALTIME_QUICKSTART.md ⭐ (NEW)
├── STAFF_REALTIME_INTEGRATION.php ⭐ (NEW)
├── STAFF_REALTIME_COMPLETE.md ⭐ (NEW)
└── config.php (existing - handles DB)

⭐ = New or Updated for Real-Time System
```

---

## 🔄 Real-Time Update Cycle

### Client-Side Loop (Every 5 Seconds)
```javascript
1. fetch('api/staff/get-pending-inquiries.php')
2. fetch('api/staff/get-scheduled-visits.php')
3. fetch('api/staff/get-stats.php')
4. Compare with previous data
5. Update UI only if changed
6. Wait 5 seconds
7. Repeat
```

### Action Flow (When Staff Clicks Approve/Decline)
```
1. Click Button
   ↓
2. POST to realtime-approve-inquiry.php
   ↓
3. Database: UPDATE inquiries SET status='approved'
   ↓
4. Broadcast: INSERT INTO realtime_updates
   ↓
5. Return: {"success": true, "realtime": true}
   ↓
6. Client: Show alert + auto-load after 500ms
   ↓
7. Next polling cycle (within 5s): Picks up changes
   ↓
8. All tabs see update: Within 5 seconds
```

---

## 🎯 Dashboard Sections

### Section 1: Real-Time Statistics
```
Shows 4 live stats:
- 💬 Pending Inquiries (count)
- 🏠 Properties (count)
- 📅 Upcoming Appointments (count)
- 👥 Total Customers (count)

Updates every 5 seconds
```

### Section 2: Customer Inquiries
```
Organized by status:
- ⏳ PENDING (Orange) - Needs action
- 💬 RESPONDED (Blue) - You responded
- ✓ APPROVED (Green) - Approved
- ✕ DECLINED (Red) - Declined

For each inquiry:
- Property title
- Customer name & email & phone
- Message text
- Related buttons: Approve, Decline, Email
```

### Section 3: Scheduled Appointments
```
Organized by status:
- ⏳ PENDING (Orange) - Needs action
- ✓ APPROVED (Green) - Approved
- ✕ DECLINED (Red) - Declined

For each appointment:
- Property title
- Customer details
- Date, time, location
- Customer message/notes
- Related buttons: Approve, Decline, Email
```

---

## 🔘 Button Actions & Status Flow

### Inquiry Button Actions
```
Button: ✓ Approve
→ Status changes: pending → approved
→ POST to realtime-approve-inquiry.php
→ Inquiry moves to approved section
→ No longer shows in pending

Button: ✕ Decline  
→ Status changes: pending → declined
→ POST to realtime-approve-inquiry.php
→ Inquiry moves to declined section
→ No longer shows in pending

Button: 📧 Email
→ Opens email client
→ Pre-fills customer email
→ Manual compose & send
```

### Appointment Button Actions
```
Button: ✓ Approve
→ Status changes: pending → approved
→ POST to realtime-approve-appointment.php
→ Appointment moves to approved section
→ Stats update

Button: ✕ Decline
→ Status changes: pending → declined
→ POST to realtime-approve-appointment.php
→ Appointment moves to declined section
→ Stats update

Button: 📧 Email
→ Opens email client
→ Pre-fills customer email
```

---

## 📊 Status Values

### Inquiry Statuses
```
pending    → New inquiry, awaiting staff response
responded  → Staff has responded, awaiting approval
approved   → ✓ Approved and accepted
declined   → ✕ Declined and rejected
```

### Appointment Statuses
```
pending    → New request, awaiting approval
approved   → ✓ Approved by staff
declined   → ✕ Declined by staff
scheduled  → Confirmed and scheduled
completed  → Visit completed
```

---

## 🗄️ Database Tables

### inquiries table
```sql
id                INT PRIMARY KEY
customer_id       INT
property_id       INT
status            VARCHAR(50) - pending|responded|approved|declined
message           TEXT
response          TEXT
created_at        TIMESTAMP
updated_at        TIMESTAMP
```

### appointments table
```sql
id                INT PRIMARY KEY
user_id           INT
property_id       INT
appointment_date  DATE
appointment_time  TIME
status            VARCHAR(50) - pending|approved|declined|scheduled|completed
message           TEXT
created_at        TIMESTAMP
updated_at        TIMESTAMP
```

### realtime_updates table (auto-created)
```sql
id            INT PRIMARY KEY
update_type   VARCHAR(50)
entity_id     INT
entity_type   VARCHAR(50)
action        VARCHAR(50)
data          JSON
created_at    TIMESTAMP
```

---

## 🔐 Security

### Authentication Check
```php
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'staff') {
    header('Location: ../staff-login.php');
    exit;
}
```

### Data Protection
- ✅ Prepared statements on all queries
- ✅ Parameter binding prevents SQL injection
- ✅ Input validation on all endpoints
- ✅ Session verification on every request
- ✅ Error messages don't expose system details

---

## 🧪 Testing URLs

### Test Inquiry API
```
GET http://localhost/nexthm/api/staff/get-pending-inquiries.php
```
Response: JSON with all inquiries

### Test Appointment API  
```
GET http://localhost/nexthm/api/staff/get-scheduled-visits.php
```
Response: JSON with all appointments

### Test Stats API
```
GET http://localhost/nexthm/api/staff/get-stats.php
```
Response: JSON with statistics

### Test Approve Inquiry
```
POST http://localhost/nexthm/api/staff/realtime-approve-inquiry.php
Body: {"inquiry_id": 1, "action": "approve"}
```
Response: Success if inquiry with id=1 exists

---

## ⚙️ Configuration

### Polling Interval
```javascript
const POLLING_INTERVAL = 5000; // 5 seconds
```
Edit in staff-dashboard-realtime.php to change

### Update Check Interval
```php
// In realtime-server.php
set_time_limit(35); // Max 35 second wait
```

### Database Connection
```php
// In config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'nexthm_db');
```

---

## 📱 Responsive Breakpoints

```
Desktop   : > 1024px - Full layout
Tablet    : 768px - 1024px - Adjusted grid
Mobile    : < 768px - Single column
```

All working and tested!

---

## 🛠️ Quick Debugging

### Check Real-Time Status
```javascript
// In browser console:
console.log('Real-Time Staff Dashboard Started');
// Should appear on dashboard load
```

### Monitor API Calls
```
Browser: F12 > Network tab
Look for:
- get-pending-inquiries.php - Should return 200
- get-scheduled-visits.php - Should return 200
- get-stats.php - Should return 200
- realtime-approve-*.php - Should return 200 after action
```

### Check Database
```
phpMyAdmin > nexthm_db
Tables: inquiries, appointments, realtime_updates
Data: Should have records
```

### View Console Errors
```
Browser: F12 > Console tab
Should show NO red errors
Should show update logs
```

---

## 📞 Support

- 📖 Full docs: `STAFF_REALTIME_IMPLEMENTATION.md`
- 🚀 Quick start: `STAFF_REALTIME_QUICKSTART.md`
- 🔧 Integration: `STAFF_REALTIME_INTEGRATION.php`
- ✅ Complete info: `STAFF_REALTIME_COMPLETE.md`

---

**Version:** 1.0.0  
**Status:** ✅ Production Ready  
**Real-Time:** 5-second polling  
**Updated:** February 14, 2026
