# API Documentation - Travel Booking System

## Base Configuration

### Base URL
```
http://your-domain.com/api
```

### Authentication
All protected endpoints require Bearer token authentication in the Authorization header:
```
Authorization: Bearer {your_token_here}
```

### Tenant ID
All tenant-specific routes require the tenant ID in the URL path:
```
/tenant/{tenant_id}/...
```

---

## Dashboard API

### Get Dashboard Statistics

**Endpoint:** `GET /tenant/{tenant}/dashboard`

**Description:** Returns comprehensive statistics for travel bookings, users, and quotations.

**Authentication:** Required (Bearer Token)

**Request:**
```http
GET /api/tenant/1/dashboard
Authorization: Bearer {token}
```

**Response (200 OK):**
```json
{
  "success": true,
  "data": {
    "travel_bookings": {
      "total": 100,
      "assigned": 75,
      "unassigned": 25,
      "by_status": {
        "pending": 30,
        "in_progress": 40,
        "completed": 25,
        "cancelled": 5
      },
      "recent": 10,
      "upcoming": 15
    },
    "users": {
      "total": 35,
      "role_3": 35,
      "active": 30,
      "inactive": 5
    },
    "quotations": {
      "total": 80,
      "active": 60,
      "inactive": 20,
      "recent": 8
    }
  }
}
```

**Error Response (401 Unauthorized):**
```json
{
  "success": false,
  "message": "Unauthorized"
}
```

**Error Response (500 Internal Server Error):**
```json
{
  "success": false,
  "message": "Failed to fetch dashboard statistics",
  "error": "Error message details"
}
```

---

## Frontend Integration Examples

### JavaScript/TypeScript Example

```typescript
// API Configuration
const API_BASE_URL = 'http://your-domain.com/api';
const TENANT_ID = '1'; // Replace with actual tenant ID

// API Service Class
class TravelBookingAPI {
  private baseURL: string;
  private tenantId: string;
  private token: string | null = null;

  constructor(baseURL: string, tenantId: string) {
    this.baseURL = baseURL;
    this.tenantId = tenantId;
    // Get token from localStorage or auth context
    this.token = localStorage.getItem('auth_token');
  }

  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<T> {
    const url = `${this.baseURL}/tenant/${this.tenantId}${endpoint}`;
    
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      ...(this.token && { Authorization: `Bearer ${this.token}` }),
      ...options.headers,
    };

    const response = await fetch(url, {
      ...options,
      headers,
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || 'API request failed');
    }

    return response.json();
  }

  // Dashboard API
  async getDashboard(): Promise<DashboardResponse> {
    return this.request<DashboardResponse>('/dashboard');
  }
}

// Type Definitions
interface DashboardResponse {
  success: boolean;
  data: {
    travel_bookings: {
      total: number;
      assigned: number;
      unassigned: number;
      by_status: {
        pending: number;
        in_progress: number;
        completed: number;
        cancelled: number;
      };
      recent: number;
      upcoming: number;
    };
    users: {
      total: number;
      role_3: number;
      active: number;
      inactive: number;
    };
    quotations: {
      total: number;
      active: number;
      inactive: number;
      recent: number;
    };
  };
}

// Usage Example
const api = new TravelBookingAPI(API_BASE_URL, TENANT_ID);

// Fetch dashboard data
try {
  const dashboardData = await api.getDashboard();
  console.log('Dashboard Stats:', dashboardData.data);
} catch (error) {
  console.error('Error fetching dashboard:', error);
}
```

### React Hook Example

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

interface DashboardData {
  travel_bookings: {
    total: number;
    assigned: number;
    unassigned: number;
    by_status: {
      pending: number;
      in_progress: number;
      completed: number;
      cancelled: number;
    };
    recent: number;
    upcoming: number;
  };
  users: {
    total: number;
    role_3: number;
    active: number;
    inactive: number;
  };
  quotations: {
    total: number;
    active: number;
    inactive: number;
    recent: number;
  };
}

const useDashboard = (tenantId: string) => {
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchDashboard = async () => {
      try {
        setLoading(true);
        const token = localStorage.getItem('auth_token');
        
        const response = await fetch(
          `/api/tenant/${tenantId}/dashboard`,
          {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json',
            },
          }
        );

        if (!response.ok) {
          throw new Error('Failed to fetch dashboard data');
        }

        const result = await response.json();
        if (result.success) {
          setData(result.data);
        } else {
          throw new Error(result.message);
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setLoading(false);
      }
    };

    fetchDashboard();
  }, [tenantId]);

  return { data, loading, error };
};

// Component Usage
const DashboardComponent = ({ tenantId }: { tenantId: string }) => {
  const { data, loading, error } = useDashboard(tenantId);

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  if (!data) return <div>No data available</div>;

  return (
    <div>
      <h2>Dashboard Statistics</h2>
      
      <div>
        <h3>Travel Bookings</h3>
        <p>Total: {data.travel_bookings.total}</p>
        <p>Assigned: {data.travel_bookings.assigned}</p>
        <p>Unassigned: {data.travel_bookings.unassigned}</p>
        <p>Pending: {data.travel_bookings.by_status.pending}</p>
        <p>In Progress: {data.travel_bookings.by_status.in_progress}</p>
        <p>Completed: {data.travel_bookings.by_status.completed}</p>
        <p>Cancelled: {data.travel_bookings.by_status.cancelled}</p>
      </div>

      <div>
        <h3>Users</h3>
        <p>Total: {data.users.total}</p>
        <p>Role 3: {data.users.role_3}</p>
        <p>Active: {data.users.active}</p>
        <p>Inactive: {data.users.inactive}</p>
      </div>

      <div>
        <h3>Quotations</h3>
        <p>Total: {data.quotations.total}</p>
        <p>Active: {data.quotations.active}</p>
        <p>Inactive: {data.quotations.inactive}</p>
        <p>Recent: {data.quotations.recent}</p>
      </div>
    </div>
  );
};
```

### Axios Example

```typescript
import axios from 'axios';

// Create axios instance
const apiClient = axios.create({
  baseURL: 'http://your-domain.com/api',
  headers: {
    'Content-Type': 'application/json',
  },
});

// Add token interceptor
apiClient.interceptors.request.use((config) => {
  const token = localStorage.getItem('auth_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Dashboard API function
export const getDashboard = async (tenantId: string) => {
  try {
    const response = await apiClient.get(`/tenant/${tenantId}/dashboard`);
    return response.data;
  } catch (error) {
    if (axios.isAxiosError(error)) {
      throw new Error(error.response?.data?.message || 'API Error');
    }
    throw error;
  }
};

// Usage
const fetchDashboardData = async () => {
  try {
    const result = await getDashboard('1');
    if (result.success) {
      console.log('Dashboard Data:', result.data);
    }
  } catch (error) {
    console.error('Error:', error);
  }
};
```

### Vue.js Example

```javascript
// api/dashboard.js
import axios from 'axios';

const API_BASE_URL = 'http://your-domain.com/api';

export const dashboardService = {
  async getDashboard(tenantId) {
    try {
      const token = localStorage.getItem('auth_token');
      const response = await axios.get(
        `${API_BASE_URL}/tenant/${tenantId}/dashboard`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
        }
      );
      return response.data;
    } catch (error) {
      throw new Error(
        error.response?.data?.message || 'Failed to fetch dashboard data'
      );
    }
  },
};

// Component Usage
// Dashboard.vue
<template>
  <div v-if="loading">Loading...</div>
  <div v-else-if="error">{{ error }}</div>
  <div v-else>
    <h2>Dashboard Statistics</h2>
    <div>
      <h3>Travel Bookings</h3>
      <p>Total: {{ dashboardData?.travel_bookings?.total }}</p>
      <p>Assigned: {{ dashboardData?.travel_bookings?.assigned }}</p>
      <!-- More stats -->
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { dashboardService } from '@/api/dashboard';

export default {
  setup() {
    const dashboardData = ref(null);
    const loading = ref(true);
    const error = ref(null);
    const tenantId = '1'; // Get from route or store

    onMounted(async () => {
      try {
        const result = await dashboardService.getDashboard(tenantId);
        if (result.success) {
          dashboardData.value = result.data;
        }
      } catch (err) {
        error.value = err.message;
      } finally {
        loading.value = false;
      }
    });

    return {
      dashboardData,
      loading,
      error,
    };
  },
};
</script>
```

---

## Response Data Structure

### Dashboard Data Fields

#### Travel Bookings
- `total` (number): Total number of travel bookings
- `assigned` (number): Number of bookings with assigned user
- `unassigned` (number): Number of bookings without assigned user
- `by_status` (object): Bookings grouped by status
  - `pending` (number): Pending bookings
  - `in_progress` (number): In progress bookings
  - `completed` (number): Completed bookings
  - `cancelled` (number): Cancelled bookings
- `recent` (number): Bookings created in last 7 days
- `upcoming` (number): Bookings with future starting date

#### Users
- `total` (number): Total number of users with role_id = 3
- `role_3` (number): Users with role_id = 3 (same as total)
- `active` (number): Active users with role_id = 3 (status = 1)
- `inactive` (number): Inactive users with role_id = 3 (status = 0)

**Note:** All user statistics are filtered to only include users with `role_id = 3`.

#### Quotations
- `total` (number): Total number of quotations
- `active` (number): Active quotations (status = 1)
- `inactive` (number): Inactive quotations (status = 0)
- `recent` (number): Quotations created in last 7 days

---

## Error Handling

### Common HTTP Status Codes

- `200 OK`: Request successful
- `401 Unauthorized`: Authentication required or token invalid
- `404 Not Found`: Resource not found
- `422 Validation Error`: Request validation failed
- `500 Internal Server Error`: Server error

### Error Response Format

```json
{
  "success": false,
  "message": "Error message",
  "error": "Detailed error information (in development)"
}
```

---

## Testing with cURL

```bash
# Get Dashboard Statistics
curl -X GET "http://your-domain.com/api/tenant/1/dashboard" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json"
```

---

## Notes

1. **Tenant ID**: Replace `{tenant}` in URLs with actual tenant ID
2. **Token**: Store authentication token securely (localStorage, sessionStorage, or secure cookie)
3. **CORS**: Ensure CORS is properly configured on the backend
4. **Rate Limiting**: Be aware of any rate limiting on the API
5. **Error Handling**: Always handle errors gracefully in your frontend application

---

## Additional Resources

For other API endpoints, refer to:
- Travel Bookings: `/api/tenant/{tenant}/travel_booking`
- Quotations: `/api/tenant/{tenant}/quotations`
- Users: `/api/tenant/{tenant}/users`

