# 🔧 REAL-TIME CONSULTATION UPDATES - DEBUGGING GUIDE

## Issue: Status Not Showing in Real-Time

### ✅ Fixes Applied:

1. **Query Updated** - Now checks both `user_id` AND `email` fields
   - Some consultations might be stored with user_id, others with email
   - API now queries: `WHERE email = ? OR user_id = ?`

2. **Email Handling Improved** - Uses registered user email
   - Joins with users table to get registered email
   - Falls back to consultation email if user email not found
   - Ensures approval/decline emails reach registered users

3. **Polling Enhanced** - Better logging and error detection
   - Logs every API call and result
   - Shows what's being found/updated
   - Helps identify why updates might not appear

4. **Initial Fetch Added** - No longer waits 5 seconds first
   - Calls `fetchConsultationUpdates()` immediately on page load
   - Then continues polling every 5 seconds

---

## 🔍 How to Test & Debug

### Step 1: Open Browser Console (F12)
```
Press: F12 or Right-click → Inspect → Console tab
```

### Step 2: Go to Customer Dashboard
```
1. Login as customer
2. Navigate to "Your Consultations" tab
3. Keep page open
4. Watch browser console
```

### Step 3: Watch for These Logs
```
Expected logs when page loads:
✓ "Starting consultation polling..."
✓ "Consultation polling started (interval: 5000ms)"
✓ "Polling consultations..."
✓ "Consultation data received: X consultations"
```

### Step 4: Trigger Admin Approval
```
1. Open admin dashboard in another window
2. Find the consultation
3. Click "Approve"
4. Watch customer dashboard console
```

### Step 5: Look for Update Logs
```
Expected logs when admin approves:
✓ "Polling consultations..."
✓ "Consultation data received: 2 consultations"
✓ "Updating 2 consultation cards"
✓ "Consultation 123: pending → approved"
✓ "Status changed! Updating display..."
```

---

## 📊 Console Log Examples

### Success Example:
```
Starting consultation polling...
Consultation polling started (interval: 5000ms)
Polling consultations...
Consultation data received: 2 consultations
Updating 2 consultation cards
Consultation 1: pending → pending (no change)
Consultation 2: pending → pending (no change)

[Admin approves...]

Polling consultations...
Consultation data received: 2 consultations
Updating 2 consultation cards
Consultation 1: pending → pending (no change)
Consultation 2: pending → approved (CHANGED!)
Status changed! Updating display...
```

### Problem Example 1: API Not Returning Data
```
Polling consultations...
Consultation data received: 0 consultations

❌ Problem: API returning empty list
✓ Solution: Check if consultation is stored with correct email/user_id
```

### Problem Example 2: Badge Element Not Found
```
Polling consultations...
Consultation data received: 2 consultations
Updating 2 consultation cards
Badge not found for consultation ID: 1

❌ Problem: Can't find the badge element on page
✓ Solution: Reload page, check HTML structure
```

### Problem Example 3: API Error
```
Consultation polling error: Error: Failed to fetch consultations - Status: 401

❌ Problem: Unauthorized (session expired)
✓ Solution: Login again
```

---

## 🛠️ Database Verification

### Check 1: Verify Consultation Exists
```sql
SELECT id, first_name, last_name, email, user_id, status, created_at, updated_at
FROM consultations
WHERE id = 123;
```

Expected result should show:
- ✓ Valid id
- ✓ Names filled in
- ✓ Either email OR user_id (or both)
- ✓ Status field
- ✓ updated_at should change when approved

### Check 2: Verify User Email
```sql
SELECT id, email
FROM users
WHERE id = (SELECT user_id FROM consultations WHERE id = 123);
```

This shows which email the approval will be sent to.

### Check 3: Verify Status Updated
```sql
SELECT status, updated_at
FROM consultations
WHERE id = 123;
```

After admin clicks approve:
- ✓ status should be 'approved'
- ✓ updated_at should be very recent (NOW())

---

## 📧 Email Debugging

### Check 1: Was Email Sent?
Look in PHP error logs or check email inbox:
```
Location: C:\xampp\apache\logs\error.log
or
Location: C:\xampp\php\logs\php_error.log
```

Look for:
```
✓ Approval email SENT to: user@example.com
OR
✗ Approval email FAILED for: user@example.com
```

### Check 2: Email Queue
If email sending failed, it should be in the queue:
```sql
SELECT id, consultation_id, recipient_email, email_type, status, attempts
FROM email_queue
WHERE consultation_id = 123
ORDER BY created_at DESC;
```

Should show:
- ✓ Status: 'pending' (waiting to be sent)
- ✓ attempts: starting count
- ✓ email_type: 'approval'

### Check 3: Is Email Queue Running?
Check if there's a process sending queued emails, or manually resend from admin panel:
```
Admin Dashboard → Email Management → Resend All Pending
```

---

## 🔍 Network Debugging

### Check 1: API Request
```
1. Open F12 → Network tab
2. Filter by "get-consultation-status"
3. Click on the request
4. Check Response tab for JSON
```

Expected response:
```json
{
  "success": true,
  "user_id": 123,
  "user_email": "user@example.com",
  "consultations": [
    {
      "id": 1,
      "status": "approved",
      "consultation_type": "interior_design",
      ...
    }
  ],
  "count": 1
}
```

### Check 2: Approve Request
```
1. Open F12 → Network tab
2. Filter by "approve-consultation"
3. Click on the request
4. Check Request tab for POST data
5. Check Response tab for success message
```

Expected response:
```json
{
  "success": true,
  "message": "Consultation approved successfully! Approval email sent to..."
}
```

---

## ❌ Common Issues & Solutions

### Issue 1: "Badge not found for consultation ID"
**Cause**: The HTML element doesn't have the data attribute
**Solution**:
1. Check HTML has: `data-consultation-id="123"`
2. Reload page (F5)
3. Check that consultation actually loads

### Issue 2: Status shows but doesn't update
**Cause**: Polling stopped or consultation not in query results
**Solution**:
1. Check console for errors
2. Verify consultation exists in database
3. Check if email/user_id matches
4. Reload page

### Issue 3: Email not received
**Cause**: Mail server not configured or email queued
**Solution**:
1. Check error logs for mail() failures
2. Check email_queue table
3. Try resending from admin panel
4. Check spam/junk folder

### Issue 4: Polling stops after a while
**Cause**: Browser closed page, session expired, or JavaScript error
**Solution**:
1. Check console for JavaScript errors
2. Make sure page is in focus (some browsers pause background tabs)
3. Login again if session expired
4. Reload page

---

## ✅ Full Debugging Checklist

- [ ] Browser console shows "Starting consultation polling..."
- [ ] Browser console shows "Consultation data received: X consultations"
- [ ] Network tab shows GET requests to "api/get-consultation-status.php" every 5 seconds
- [ ] API response returns status 200 and valid JSON
- [ ] API response includes your consultation with status
- [ ] Admin approval shows "success: true"
- [ ] Database shows updated_at changed after approval
- [ ] Console shows "Status changed! Updating display..."
- [ ] Badge color changes on dashboard (yellow→green)
- [ ] Notification appears at top of page
- [ ] Email received in inbox or check_email_queue table

---

## 🚀 Performance Check

### Browser Console:
```javascript
// Check polling is running
setInterval
// Or
// Copy-paste in console:
console.log("Polling active:", consultationPollingInterval !== null);
```

### Network Tab:
- Requests should appear every 5 seconds
- Each request should be < 1KB
- Response time should be < 100ms

### Database:
- Query should be fast (has index on email field)
- No locks or slow queries

---

## 📞 Still Not Working?

### Step-by-Step Debug:

1. **Check console logs** (F12)
   - Are there any red errors?
   - What's the last message printed?

2. **Check network requests** (F12 → Network)
   - Are API calls being made?
   - What status codes? (200 = good, 401 = not logged in, 500 = server error)
   - What data is returned?

3. **Check database** (PhpMyAdmin)
   - Does consultation exist?
   - Does it have email or user_id?
   - Did status actually change?

4. **Check email** (Inbox or logs)
   - Was email sent?
   - Is it in spam?
   - Check error logs

5. **Hard refresh** (Ctrl+Shift+R on Windows/Cmd+Shift+R on Mac)
   - Clears cache
   - Forces reload of HTML, CSS, JavaScript

6. **Re-login**
   - Session might have expired
   - Clear browser cache
   - Close and reopen browser

---

## 📝 Troubleshooting Template

When reporting an issue, include:

```
1. What happened?
   [Describe the issue]

2. What did you expect?
   [What should have happened]

3. Console logs (F12 → Console):
   [Paste any red errors or relevant messages]

4. Network logs (F12 → Network → get-consultation-status):
   [Status code and response data]

5. Database status:
   SELECT status, updated_at FROM consultations WHERE id = 123;
   [Result]

6. Which browser?
   [Chrome/Firefox/Safari/Edge and version]

7. When did it last work?
   [Today/Yesterday/Never]
```

---

## 📚 Key Files to Check

- **customer-dashboard.php** (lines 1408+) - Polling code
- **api/get-consultation-status.php** - Status fetching
- **api/approve-consultation.php** - Approval and email
- **Browser Console** (F12) - Real-time logs
- **Browser Network** (F12 → Network tab) - API calls
- **PhpMyAdmin** - Database verification

---

**Last Updated**: December 30, 2025
**Version**: Enhanced Real-Time Updates
**Status**: Ready for Debugging
