# Wellness Scoring System Implementation

## Overview
The wellness scoring system provides a comprehensive, data-driven assessment of user wellness across six key categories, with scores persisted to the database and visualized on the user dashboard.

## Architecture

### Database Table: `wellness_scores`
```sql
CREATE TABLE wellness_scores (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    overall_score INT,
    sleep_score INT,
    activity_score INT,
    health_score INT,
    stress_score INT,
    appointment_score INT,
    wellness_engagement_score INT,
    score_breakdown JSON,
    calculated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    KEY (user_id, calculated_at)
)
```

## Scoring Model

### 1. Sleep Quality (0-20 points)
- **Data Source**: `health_metrics.sleep_hours` (last 7 days average)
- **Calculation**:
  - Ideal: 7-9 hours = 20 points
  - 6-7 or 9-10 hours = 15 points
  - 5-6 or 10-11 hours = 10 points
  - Less than 5 or more than 11 = 5 points

### 2. Physical Activity (0-20 points)
- **Data Sources**: 
  - Coaching appointments (last 30 days)
  - Exercise frequency from latest intake form
- **Calculation**:
  - 4+ sessions last 30 days = 12 points base
  - Regular exercise (3+ times/week) = +8 points
  - Maximum: 20 points

### 3. Health Metrics (0-20 points)
- **Data Sources**: `health_metrics` (blood pressure, heart rate, weight)
- **Calculation**:
  - Blood Pressure (ideal <130/80):
    - Within range = 5 points
    - Elevated = 3 points
    - High = 1 point
  - Heart Rate (ideal 60-100 bpm):
    - Within range = 5 points
    - Elevated = 3 points
  - Weight Stability (no significant changes in 30 days):
    - Stable = 5 points
    - Changing = 3 points
  - BMI categories = 5 points base
  - Maximum: 20 points

### 4. Stress Management (0-20 points)
- **Data Source**: Latest intake form `stressLevel` field (1-10 scale)
- **Calculation**:
  - 1-3 (Low) = 20 points
  - 4-5 (Moderate) = 15 points
  - 6-7 (High) = 10 points
  - 8-10 (Very High) = 5 points

### 5. Appointments & Sessions (0-10 points)
- **Data Source**: `appointments` table
- **Calculation**:
  - Completed sessions (last 30 days) = 6 points
  - Upcoming scheduled sessions = 4 points
  - Maximum: 10 points

### 6. Wellness Engagement (0-10 points)
- **Data Sources**: Multiple wellness activities
- **Calculation**:
  - Health logs (last 30 days): Up to 3 points
  - Store purchases (lifetime): Up to 3 points
  - Medical/health documents: Up to 2 points
  - Holistic wellness engagement bonus: Up to 2 points
  - Maximum: 10 points

## Total Score: 100 Points Maximum

### Score Interpretation
- **70-100**: Excellent wellness (Green)
- **40-70**: Moderate wellness (Amber)
- **0-40**: Low wellness (Red)

## API Endpoints

### 1. Calculate Wellness Score
**Endpoint**: `GET /api/wellness/calculate.php`

**Authentication**: Required (client)

**Response**:
```json
{
  "success": true,
  "overall_score": 75,
  "breakdown": {
    "sleep": 18,
    "activity": 16,
    "health": 14,
    "stress": 15,
    "appointments": 8,
    "engagement": 8
  },
  "recommendations": [
    "Maintain your excellent sleep schedule",
    "Keep up with regular exercise..."
  ]
}
```

### 2. Get Wellness History
**Endpoint**: `GET /api/wellness/history.php?days=30`

**Authentication**: Required (client)

**Parameters**:
- `days` (optional): Number of days to look back (default: 30)

**Response**:
```json
{
  "success": true,
  "current_score": {
    "id": 123,
    "overall_score": 75,
    "sleep_score": 18,
    "activity_score": 16,
    "health_score": 14,
    "stress_score": 15,
    "appointment_score": 8,
    "wellness_engagement_score": 8,
    "score_breakdown": {
      "sleep": 18,
      "activity": 16,
      "health": 14,
      "stress": 15,
      "appointments": 8,
      "engagement": 8
    },
    "calculated_at": "2024-01-15 10:30:00"
  },
  "trends": {
    "sleep": 2,
    "activity": -1,
    "health": 0,
    "stress": 3,
    "appointments": 0,
    "engagement": 1
  },
  "history": [
    { "overall_score": 75, "calculated_at": "2024-01-15" },
    { "overall_score": 72, "calculated_at": "2024-01-14" },
    ...
  ]
}
```

## Frontend Integration

### Dashboard Display (dashboard/user/index.php)

1. **Wellness Score Stat Card**:
   - Shows current overall score with color coding
   - Spinner loading state during fetch
   - Links to full breakdown section

2. **Wellness Breakdown Section**:
   - Six category cards (Sleep, Activity, Health, Stress, Appointments, Engagement)
   - Visual progress bars for each category
   - Category icons and color-coded bars
   - Scores displayed as fractions (e.g., "18/20")

### JavaScript Functions

**loadWellnessScore()**:
- Fetches `/api/wellness/history.php`
- Updates wellness score display with color coding
- Calls `renderWellnessBreakdown()` to populate breakdown section

**renderWellnessBreakdown(scoreData)**:
- Takes wellness score object
- Renders 6 category cards with progress bars
- Color codes bars based on percentage (green: 75+%, amber: 50-75%, red: <50%)

## Data Flow

1. User logs in → Dashboard loads
2. JavaScript calls `loadWellnessScore()` on page load
3. Fetches from `/api/wellness/history.php`
4. API queries `wellness_scores` table for latest entry
5. If no score exists, returns null
6. Dashboard displays current score + breakdown
7. User can trigger recalculation via calculate.php endpoint

## Manual Score Calculation

To manually trigger a new wellness score calculation:

```bash
curl -X GET http://localhost/herbal-wellness/api/wellness/calculate.php \
  -H "Content-Type: application/json"
```

(Requires authentication cookie)

## Data Retention

- Wellness scores are stored indefinitely
- Historical data supports trend analysis
- Default history view shows 30 days of data

## Future Enhancements

1. **Automated Calculation**: Cron job to calculate scores daily
2. **Wellness Trends Chart**: Line graph showing score over time
3. **Category-Specific Recommendations**: More detailed guidance based on low scores
4. **Wellness Goals**: Allow users to set targets for each category
5. **Comparison**: Show progress vs previous week/month/year
6. **Wellness Tips**: Context-aware tips based on category scores
7. **Export**: PDF reports of wellness trends

## Testing Checklist

- [ ] Create test health metrics (sleep, BP, HR, weight)
- [ ] Submit test intake form with stress level
- [ ] Create test appointments
- [ ] Make test purchases in store
- [ ] Upload test medical documents
- [ ] Call `/api/wellness/calculate.php` and verify score
- [ ] Call `/api/wellness/history.php` and verify history
- [ ] Load dashboard and verify score displays
- [ ] Verify breakdown section renders correctly
- [ ] Test color coding (green 70+, amber 40-70, red <40)
- [ ] Verify trend calculations work
- [ ] Test with multiple users to ensure data isolation

## Common Issues & Solutions

**Issue**: Score shows "No data yet"
- **Cause**: No wellness score calculated yet
- **Solution**: Create some health data and call `/api/wellness/calculate.php`

**Issue**: Breakdown section not rendering
- **Cause**: JavaScript error or missing `wellness-breakdown` element
- **Solution**: Check browser console for errors; verify HTML element exists

**Issue**: Score not updating
- **Cause**: Browser cache or stale API response
- **Solution**: Clear browser cache or wait for auto-refresh (every dashboard load)

**Issue**: Incorrect score calculations
- **Cause**: Missing health data or database table issues
- **Solution**: Verify health_metrics and appointments tables have recent data
