# Dashboard API Documentation

This document describes the dashboard API endpoints for retrieving charts and cards data for the Treelogy project dashboard.

## Base URL
All dashboard endpoints are prefixed with `/api/surveys/project/{treelogy_id}/dashboard/`

## Authentication
All dashboard endpoints require authentication via JWT token in the Authorization header:
```
Authorization: Bearer <jwt_token>
```

## Endpoints

### 1. Dashboard Cards
**GET** `/api/surveys/project/{treelogy_id}/dashboard/cards`

Retrieves the main dashboard cards data including total trees surveyed, verified trees, and species count.

**Response:**
```json
{
  "success": true,
  "message": "Dashboard cards data retrieved successfully",
  "data": {
    "totalTreesSurveyed": 924701,
    "totalVerified": 318221,
    "speciesCount": 236
  }
}
```

### 2. Condition Wise Donut Chart
**GET** `/api/surveys/project/{treelogy_id}/dashboard/charts/condition`

Retrieves tree condition distribution data for donut chart.

**Response:**
```json
{
  "success": true,
  "message": "Condition chart data retrieved successfully",
  "data": {
    "chartType": "condition",
    "data": [
      {
        "tree_condition": "HEALTHY",
        "count": "120"
      },
      {
        "tree_condition": "AVERAGE",
        "count": "25"
      }
    ]
  }
}
```

### 3. Remarks Wise Tree Count Chart
**GET** `/api/surveys/project/{treelogy_id}/dashboard/charts/remarks`

Retrieves remarks distribution data for chart.

**Response:**
```json
{
  "success": true,
  "message": "Remarks chart data retrieved successfully",
  "data": {
    "chartType": "remarks",
    "data": [
      {
        "remarks": "Good condition",
        "count": "150"
      },
      {
        "remarks": "Needs attention",
        "count": "30"
      }
    ]
  }
}
```

### 4. Ownership Wise Pie Chart
**GET** `/api/surveys/project/{treelogy_id}/dashboard/charts/ownership`

Retrieves tree ownership distribution data for pie chart.

**Response:**
```json
{
  "success": true,
  "message": "Ownership chart data retrieved successfully",
  "data": {
    "chartType": "ownership",
    "data": [
      {
        "tree_ownership": "PUBLIC",
        "count": "200"
      },
      {
        "tree_ownership": "PRIVATE",
        "count": "80"
      }
    ]
  }
}
```

### 5. Species Wise Tree Count (Top 15) Bar Chart
**GET** `/api/surveys/project/{treelogy_id}/dashboard/charts/species`

Retrieves top 15 species by tree count for bar chart.

**Response:**
```json
{
  "success": true,
  "message": "Species chart data retrieved successfully",
  "data": {
    "chartType": "species",
    "data": [
      {
        "local_name": "Neem",
        "count": "50"
      },
      {
        "local_name": "Banyan",
        "count": "35"
      }
    ]
  }
}
```

### 6. Economic Importance Wise Tree Count Bar Chart
**GET** `/api/surveys/project/{treelogy_id}/dashboard/charts/economic-importance`

Retrieves economic importance distribution data for bar chart.

**Response:**
```json
{
  "success": true,
  "message": "Economic importance chart data retrieved successfully",
  "data": {
    "chartType": "economic_importance",
    "data": [
      {
        "economic_importance": "MEDICINAL",
        "count": "100"
      },
      {
        "economic_importance": "TIMBER",
        "count": "75"
      }
    ]
  }
}
```

## Error Responses

All endpoints return consistent error responses:

```json
{
  "success": false,
  "message": "Error message",
  "data": "Additional error details"
}
```

Common HTTP status codes:
- 200: Success
- 401: Unauthorized (missing or invalid token)
- 404: Project not found
- 500: Internal Server Error

## Database Connection

These endpoints automatically connect to the project-specific database based on the `treelogy_id` parameter. The system:

1. Looks up the project in the main database
2. Gets the project's database name (`dbname`)
3. Connects to the project database
4. Queries the `surveys` table in the project database

## Data Filtering

All queries filter for:
- `status = 'ACTIVE'` - Only active surveys
- Non-null values for the specific field being analyzed

## Performance Considerations

- All queries use proper indexing on the `surveys` table
- Group by operations are optimized for dashboard performance
- Results are limited where appropriate (e.g., top 15 species)
- Raw SQL results are used for better performance

## Usage Examples

### Frontend Integration

```javascript
// Get dashboard cards
const cardsResponse = await fetch('/api/surveys/project/1/dashboard/cards', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});
const cardsData = await cardsResponse.json();

// Get condition chart
const conditionResponse = await fetch('/api/surveys/project/1/dashboard/charts/condition', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});
const conditionData = await conditionResponse.json();
```

### React Component Example

```jsx
import { useEffect, useState } from 'react';

function Dashboard() {
  const [cardsData, setCardsData] = useState(null);
  const [conditionData, setConditionData] = useState(null);

  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        const token = localStorage.getItem('token');
        const headers = { 'Authorization': `Bearer ${token}` };
        
        const [cardsRes, conditionRes] = await Promise.all([
          fetch('/api/surveys/project/1/dashboard/cards', { headers }),
          fetch('/api/surveys/project/1/dashboard/charts/condition', { headers })
        ]);
        
        const cards = await cardsRes.json();
        const condition = await conditionRes.json();
        
        setCardsData(cards.data);
        setConditionData(condition.data);
      } catch (error) {
        console.error('Error fetching dashboard data:', error);
      }
    };

    fetchDashboardData();
  }, []);

  return (
    <div>
      {/* Render dashboard cards and charts */}
    </div>
  );
}
```
