# 🚀 Monrita Smart PO API - Integration Guide

Welcome to the **Monrita Smart Purchase Order API**. This API is designed to be **self-guiding**, **high-performance**, and **developer-friendly**. It doesn't just return data; it understands your intent and helps you fix integration issues in real-time.

---

## 🧠 "It Just Works" Design
We built this API to be intuitive. You don't need to memorize strict codes.

*   **Smart Corrections**: If you misspell a supplier's name, the API will suggest the closest match ("Did you mean...?").
*   **Context Awareness**: If you ask for a supplier in the wrong region, the API explains the mismatch instead of returning an empty list.
*   **Auto-Normalization**: "rice", "Rice", and "RICE" are all treated the same.
*   **Limit Enforcement**: Automatically ensures no school exceeds its quota (Max 10 schools per supplier).

---

## 🔑 Authentication
Include your API Key in the header of every request.

**Header:**
`X-API-Key: <your_api_key>`

"X-API-Key: b7808f28bf4db79388f090abfc90a859aec5381afdcaba9b3b048fd6bfe105b5"

---

## 📡 Endpoints

### 1. Get Allocations (JSON)
The core engine. Returns detailed allocation data. By default, the response is **lean** (fastest). You can request rich analytics using the `include` parameter.

**URL:** `GET /api/v1/purchase-orders/allocations`

**Parameters:**
| Parameter | Type | Description | Smart Behavior |
| :--- | :--- | :--- | :--- |
| `supplier_name` | String | Name of the supplier | **Fuzzy Search Enabled.** If not found, returns suggestions. |
| `region` | String | Target Region (e.g., "SAVANNAH") | **Auto-Detected** if supplier is unique to a region. |
| `commodity` | String | Specific item (e.g., "Rice") | **Normalized.** Matches "rice", "RICE", etc. |
| `page` | Integer | Page number (Default: 1) | **Pagination** for allocation details. |
| `per_page` | Integer | Items per page (Default: 50) | **Limit** the number of details returned. |
| `include` | String | Comma-separated flags | Options: `insights`, `meta`, `unallocated`. |

**Example Request (Lean - Default):**
```bash
curl "http://localhost/monrita-main/backend/public/api/v1/purchase-orders/allocations?supplier_name=Abel&region=SAVANNAH" \
     -H "X-API-Key: YOUR_KEY"
```

**Example Request (Rich - Analytics):**
```bash
curl "http://localhost/monrita-main/backend/public/api/v1/purchase-orders/allocations?supplier_name=Abel&include=insights,meta" \
     -H "X-API-Key: YOUR_KEY"
```

**Smart Response (Rich Mode):**
```json
{
  "purchase_orders": [ ... ],
  "allocation_details": [ ... ],
  "pagination": {
    "current_page": 1,
    "per_page": 50,
    "total_items": 100,
    "links": {
        "next": "?supplier_name=Abel&include=insights&page=2&per_page=50",
        "prev": null
    }
  },
  "insights": {
    "narrative": "Successfully allocated 603 items...",
    "key_metrics": { ... }
  },
  "meta": { ... }
}
```

**Standardized Error Response:**
```json
{
  "error": {
    "code": "DATA_NOT_FOUND",
    "message": "Supplier 'Abe' not found. Did you mean: Abel groups of company?",
    "details": ["The API tries to help! Check the spelling or use a partial name."]
  }
}
```

---

### 2. Download PDF Report
Generates a professional, printable PDF of the allocations.

**URL:** `GET /api/v1/purchase-orders/pdf`

**Parameters:** Same as `/allocations`.

**Example Request:**
```bash
curl "http://localhost/monrita-main/backend/public/api/v1/purchase-orders/pdf?supplier_name=Abel&region=SAVANNAH" \
     -H "X-API-Key: YOUR_KEY" \
     --output po_report.pdf
```

---

## ⚡ Performance & Integration Tips

The API is powered by an **O(1) Smart Allocator Engine**, capable of processing thousands of schools in milliseconds. Here is how to keep your integration fast:

### 1. Trust the "Smart" Defaults
You don't need to pre-validate everything.
*   **Don't** fetch all suppliers to check spelling. Just query. If it's wrong, the API tells you the right name.
*   **Don't** calculate school limits on your end. The API enforces them (Max 10 schools/supplier) automatically.

### 2. Intelligent Caching
The API uses a sophisticated file-based caching mechanism.
*   **First Request**: May take a moment to parse the massive supplier database and build optimized indices.
*   **Subsequent Requests**: **Instant**. The API loads pre-computed indices directly from disk, bypassing heavy parsing logic.
*   **Header**: Check `X-Response-Time` in the response headers to see the execution time (often < 50ms).

### 3. Pagination is Key
For large datasets, always use `page` and `per_page`. The API defaults to 50 items to ensure the UI remains snappy.

### 4. Handling "Zero Allocations"
If `purchase_orders` is empty, check the `message` field.
*   The API will explicitly tell you: *"Supplier X is in Region Y, but you asked for Region Z."*
*   Display this message directly to your user—it is written in plain English.

### 5. Logistics Optimization (New!)

The API now includes "Sophisticated Logistics Logic":

*   **Consolidation**: If a supplier is already delivering Rice to School A, the API will try to assign them Maize as well. This reduces the number of trucks visiting a school.
*   **Load Balancing**: The API automatically rotates suppliers to ensure no one is overloaded, using a "Least-Loaded First" algorithm.
*   **Headers**: Check `X-Allocation-Strategy` in the response to see which logic was applied.

---

## 🛠 Troubleshooting

| Issue | API Response | Solution |
| :--- | :--- | :--- |
| **Typo in Name** | `Did you mean: ...?` | Use the suggested name in your next query. |
| **Wrong Region** | `Supplier is in X, you asked for Y` | Update your `region` parameter to match the supplier. |
| **No Auth** | `401 Unauthorized` | Check your `X-API-Key` header. |

---
*Powered by Monrita Smart Allocator Engine*
