# Education Enquiry Issue Investigation

## Problem Summary
- **Local behavior**: Enquiries are being saved to the database, but sometimes not appearing in "my enquiries"
- **Live behavior**: Enquiries are NOT being saved/added at all

## Root Cause Analysis

### Issue #1: Authentication Status During Submission (PRIMARY ISSUE)

**Route Definition** (`routes/api.php`):
- Endpoint: `POST /api/v1/education/enquire`
- Middleware: `auth.sanctum.optional` (allows requests WITH or WITHOUT authentication)

**The Problem in the Backend** (`EducationEnquiryController.php` line 44):
```php
'user_id' => $request->user()?->id,  // Returns NULL if user is NOT authenticated
```

**Flow:**
1. Mobile app sends enquiry WITHOUT valid Bearer token (or without authentication)
2. `$request->user()` returns NULL
3. Lead is saved to database with **`user_id = NULL`**
4. Lead email is sent to admin ✓
5. Mobile app shows "Enquiry submitted. We will contact you soon." ✓
6. BUT when user later logs in and checks `/api/v1/me/leads`, the query filters:
   ```php
   ->where('user_id', $authenticated_user_id)
   ```
7. **Result**: Lead with `user_id = NULL` is NOT returned ❌

### Issue #2: Guest Lead Linking (May Not Be Triggered)

There IS a `linkGuestLeadsForUser()` function (`LeadService.php` line 40) that's supposed to:
- Find all leads with `user_id = NULL` where `mobile` matches the authenticated user
- Link them to the authenticated user

**Where it's called:**
- `Api/AuthController.php` - `verifyOtp()` (line 39)
- `Api/AuthController.php` - `loginWithPassword()` (line 74)

**Potential issues:**
- This linking relies on mobile number matching between:
  - The guest lead: `mobile` (normalized to digits only)
  - The authenticated user: `user.mobile` (may have formatting)
  
- Normalization function (`LeadService.php` line 105):
  ```php
  preg_replace('/\D+/', '', $mobile)  // Removes all non-digits
  ```

**Why it might fail in LIVE:**
- If `user.mobile` is stored with country code (`+91...`) or spaces, normalization should work
- BUT if there's any other formatting issue or if the linking is not being triggered for some reason, leads won't be linked

### Issue #3: Different Endpoint for Education Enquiries

**For module enquiries** (jobs, properties, services):
- Uses: `POST /api/v1/leads`
- Controller: `LeadController::store()`
- Saves with: `lead_category = 'module_enquiry'`

**For education enquiries**:
- Uses: `POST /api/v1/education/enquire` 
- Controller: `EducationEnquiryController::store()`
- Saves with: `lead_category = 'education_enquiry'`

Both endpoints have `auth.sanctum.optional` middleware and both save `user_id = $request->user()?->id`

## Why Local Works But Live Doesn't

**Possible reasons:**
1. In local, you might have been testing with active authentication token
2. In local, leads might have been manually linked or user logged in after submission
3. In live:
   - Bearer token might be expiring before submission
   - Mobile app might not be sending Bearer token correctly
   - CORS or authentication headers might be misconfigured
   - Network timing issues causing token validation to fail

## Investigation Checklist

1. **Check mobile app network requests**: 
   - Is the Bearer token being sent with the `/api/v1/education/enquire` request in live?
   - Check `education_enquiry_screen.dart` line 57 - is it sending auth headers?

2. **Check database**:
   - Run: `SELECT id, user_id, mobile, lead_category, created_at FROM leads WHERE lead_category = 'education_enquiry' ORDER BY created_at DESC LIMIT 20;`
   - Are the `user_id` values NULL or have an ID?
   - If NULL, the guest lead linking didn't work

3. **Check logs**:
   - Check Laravel logs in `storage/logs/laravel.log`
   - Look for any auth token validation failures
   - Check if `linkGuestLeadsForUser()` is being called

4. **Check live environment configuration**:
   - Is Sanctum properly configured?
   - Are API tokens being generated correctly?
   - Is the token expiry time too short?

## Affected Endpoints
- `POST /api/v1/education/enquire` (EducationEnquiryController::store)
- `POST /api/v1/leads` (LeadController::store) - Same issue, same root cause
- `GET /api/v1/me/leads` - Won't show unlinked leads

## Files Involved
- `/app/Http/Controllers/Api/EducationEnquiryController.php` (line 44)
- `/app/Http/Controllers/Api/LeadController.php` (lines 69-77)
- `/app/Services/LeadService.php` (line 40)
- `/app/Services/Auth/OtpAuthService.php` (line 93)
- `/routes/api.php` (line 57)
