# New Ingredient Request Workflow - Complete Guide

## Overview
Admins can now request **new ingredients** that aren't yet in the system. Purchase Managers review these requests and approve them to add to inventory, or reject them with a reason.

**Problem Solved**: Admin can't manually add ingredients to the system (reduces errors). Instead, they submit requests to PM who validates and adds them.

---

## Complete Workflow

### Phase 1: Admin Requests New Ingredient

**Location**: Admin Ingredients Page (`admin/ingredients.php`)

1. Admin clicks **"Request New Ingredient"** button (blue button in header)
2. Modal opens with form fields:
   - **Ingredient Name** * (required) - e.g., "Saffron", "Fresh Basil"
   - **Description** - Optional notes (e.g., "Grade A, organic")
   - **Unit** * (required) - kg, g, liter, ml, piece, dozen, box, packet
   - **Supplier** (optional) - If known
   - **Initial Quantity to Order** * (required) - How much to buy
   - **Priority** - High (urgent), Medium (soon), Low (can wait)
   - **Notes for PM** - Why needed, specifications, etc.

3. Admin clicks **"Send Request"**
4. System:
   - Validates all required fields
   - Checks if ingredient already exists (prevents duplicates)
   - Creates row in `ingredient_requests` table with `status='pending'`
   - Shows success message
   - Modal closes

---

### Phase 2: PM Reviews New Ingredient Requests

**Location**: PM New Ingredients Page (`purchase_manager/new_ingredients.php`)

1. PM navigates to **"New Ingredients"** from navbar
2. Page shows 3 tabs:
   - **Pending** (red badge shows count) - New requests awaiting review
   - **Approved** (checkmark) - Ingredients already added to system
   - **Rejected** (X) - Requests declined with reason

3. **Pending Tab** displays:
   - Ingredient name, description
   - Unit, quantity requested, supplier
   - Priority badge (color-coded: red/yellow/blue)
   - Requested date
   - Admin's notes
   - **2 action buttons**: ✓ Approve | ✗ Reject

---

### Phase 3a: PM Approves Request

1. PM reviews pending request
2. Clicks **"Approve"** button
3. Approval modal opens with form:
   - **Ingredient Name** (read-only) - Pre-filled
   - **Current Stock** - Enter starting amount (default: 0)
   - **Minimum Stock** - Reorder threshold (default: 10)
   - **Unit Cost** (₹) - Price per unit (default: 0)

4. PM fills values and clicks **"Approve & Create Ingredient"**
5. System:
   - Creates new row in `ingredients` table with:
     - name, description, unit, supplier (from request)
     - current_stock, minimum_stock, unit_cost (from form)
     - total_value = current_stock × unit_cost
   - Updates `ingredient_requests` row:
     - status = 'approved'
     - created_ingredient_id = new ingredient's ID
     - approved_by = PM user ID
     - approved_at = current timestamp
   - Shows success message with ingredient ID
   - Request moves to "Approved" tab

**After Approval**:
- Ingredient now appears in regular Ingredients page
- Admin can't request same ingredient again (duplicate check)
- PM can start tracking stock and creating purchase orders

---

### Phase 3b: PM Rejects Request

1. PM reviews pending request
2. Clicks **"Reject"** button
3. Rejection modal opens with form:
   - **Ingredient Name** (read-only) - Pre-filled
   - **Reason for Rejection** (required) - Why rejecting
     - Examples: "Already have similar item", "Budget constraints", "Quality concerns"

4. PM fills reason and clicks **"Reject Request"**
5. System:
   - Updates `ingredient_requests` row:
     - status = 'rejected'
     - rejection_reason = entered reason
     - approved_by = PM user ID (for audit trail)
     - rejected_at = current timestamp
   - Shows success message
   - Request moves to "Rejected" tab

**After Rejection**:
- Admin sees rejection reason if they check (future feature)
- Ingredient NOT added to system
- Admin can request again later with different details

---

## Database Tables

### `ingredient_requests` Table
```sql
CREATE TABLE ingredient_requests (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,               -- Requested ingredient name
    description TEXT,                         -- Optional description
    unit VARCHAR(50) NOT NULL,                -- kg, g, liter, ml, etc.
    supplier VARCHAR(255),                    -- Requested supplier
    quantity_requested DECIMAL(10,2),         -- How much admin wants
    priority ENUM('low','medium','high'),     -- Priority level
    notes TEXT,                               -- Admin's notes
    status ENUM('pending','approved','rejected') DEFAULT 'pending',
    requested_by VARCHAR(50),                 -- 'admin'
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    approved_by VARCHAR(50),                  -- PM who reviewed
    approved_at TIMESTAMP NULL,               -- When approved/rejected
    created_ingredient_id INT,                -- Link to created ingredient
    rejection_reason TEXT,                    -- Why rejected
    rejected_at TIMESTAMP NULL,               -- When rejected
    FOREIGN KEY (created_ingredient_id) REFERENCES ingredients(id)
);
```

---

## API Endpoints

### 1. Create New Ingredient Request (Admin)
```
POST /backend/admin_new_ingredient_request_api.php?action=create_request

{
  "name": "Saffron Threads",
  "description": "Premium grade saffron",
  "unit": "g",
  "supplier": "Spice Traders Inc",
  "quantity_requested": 100,
  "priority": "high",
  "notes": "For special biryani batch",
  "requested_by": "admin"
}

Response:
{
  "success": true,
  "message": "New ingredient request created successfully",
  "request_id": 42
}
```

### 2. Get New Ingredient Requests (PM)
```
GET /backend/admin_new_ingredient_request_api.php?action=get_requests&status=pending

Response:
{
  "success": true,
  "requests": [
    {
      "id": 42,
      "name": "Saffron Threads",
      "description": "Premium grade saffron",
      "unit": "g",
      "quantity_requested": "100.00",
      "priority": "high",
      "notes": "For special biryani batch",
      "requested_by": "admin",
      "created_at": "2026-03-12 10:30:00",
      "status": "pending"
    }
  ],
  "count": 1,
  "status_filter": "pending"
}
```

### 3. Approve Request (PM)
```
POST /backend/admin_new_ingredient_request_api.php?action=approve_request

{
  "request_id": 42,
  "current_stock": 0,
  "minimum_stock": 10,
  "unit_cost": 5000
}

Response:
{
  "success": true,
  "message": "Ingredient approved and created successfully",
  "ingredient_id": 156,
  "ingredient_name": "Saffron Threads"
}
```

### 4. Reject Request (PM)
```
POST /backend/admin_new_ingredient_request_api.php?action=reject_request

{
  "request_id": 42,
  "reason": "Already have 3 similar saffron suppliers"
}

Response:
{
  "success": true,
  "message": "Request rejected successfully"
}
```

---

## UI Elements

### Admin Side (`admin/ingredients.php`)

**Button**:
```html
<button class="btn btn-primary" onclick="openNewIngredientModal()">
    <i class="fas fa-plus"></i> Request New Ingredient
</button>
```

**Modal**: #newIngredientModal
- Form with 8 fields (5 required)
- Submit button: "Send Request"
- Cancel button

### PM Side (`purchase_manager/new_ingredients.php`)

**Tabs**:
- Pending [1] ← Red badge with count
- Approved
- Rejected

**Request Cards** (for each request):
- Header: Ingredient name + priority badge + status badge
- Description (if provided)
- Details grid: unit, qty, supplier, requested by, date
- Notes (if provided)
- Action buttons (for pending requests):
  - ✓ Approve
  - ✗ Reject

---

## Color Coding

**Priority Badges**:
- 🔴 **High** - Red (#fee2e2 bg, #991b1b text)
- 🟡 **Medium** - Yellow (#fef3c7 bg, #92400e text)
- 🟢 **Low** - Blue (#e0f2fe bg, #0c4a6e text)

**Status Badges**:
- **Pending** - Yellow (waiting for PM action)
- **Approved** - Green (added to inventory)
- **Rejected** - Red (not approved)

---

## Validation & Error Handling

### Admin Submission:
- ✓ Ingredient name required
- ✓ Unit required
- ✓ Quantity > 0 required
- ✓ Ingredient name must be unique (no duplicates)
- ✓ Unit must be from predefined list

### PM Approval:
- ✓ Current stock ≥ 0 (can't be negative)
- ✓ Minimum stock ≥ 0
- ✓ Unit cost ≥ 0

### Error Messages:
- "Ingredient already exists in the system" - Duplicate ingredient
- "Missing required fields" - Form validation error
- "Failed to create request" - Database error

---

## Use Cases

### Scenario 1: New Specialty Ingredient
```
1. Admin: "Chef requests Persian saffron for special menu"
2. Admin clicks Request → Fills form → Submits
3. PM: Reviews request → Sees it's specialty item
4. PM clicks Approve → Sets cost ₹5000/g
5. System: Creates ingredient, ready for purchase orders
```

### Scenario 2: Seasonal Item
```
1. Admin: "Fresh truffles only available Dec-Jan"
2. Admin requests with notes about seasonality
3. PM: Rejects because "Not aligned with current menu"
4. Admin sees rejection, can request again next season
```

### Scenario 3: Emergency Supply
```
1. Admin: "Kitchen ran out, need emergency supply"
2. Admin requests with Priority=HIGH
3. PM: Sees high priority badge, approves immediately
4. PM creates purchase order right away
5. Emergency handled quickly
```

---

## Features Included

✅ **Duplicate Prevention** - Can't request ingredient twice  
✅ **Priority Sorting** - High priority shown first  
✅ **Audit Trail** - Tracks who requested, approved, when  
✅ **Flexible Units** - Supports kg, g, liters, pieces, etc.  
✅ **Optional Fields** - Description, supplier, notes all optional  
✅ **Multi-Status Tracking** - Pending, approved, rejected tabs  
✅ **Rejection Reasons** - Feedback loop for admin  
✅ **Date Tracking** - When requested, approved, rejected  
✅ **Auto-Created Ingredients** - No manual entry needed  

---

## Future Enhancements

- Email notifications to PM when request created
- Admin can see rejection reason feedback
- Request amendment/resubmission after rejection
- Request expiry (auto-close old pending requests)
- Bulk upload for multiple new ingredients
- Ingredient categories/classifications
- Supplier rankings for new ingredients

---

## Testing Checklist

**Admin Side**:
- [ ] "Request New Ingredient" button visible and clickable
- [ ] Modal opens with all 8 form fields
- [ ] Validation prevents empty required fields
- [ ] Duplicate name shows error message
- [ ] Non-duplicate names submit successfully
- [ ] Success message displays on submit
- [ ] Modal closes after successful submit

**PM Side**:
- [ ] "New Ingredients" link visible in navbar
- [ ] Page loads with 3 tabs
- [ ] Pending tab shows request with correct data
- [ ] Priority badge shows correct color
- [ ] Approve button opens approval modal
- [ ] Approval form pre-fills ingredient name
- [ ] Approval creates ingredient in system
- [ ] Ingredient appears in regular ingredients page
- [ ] Reject button opens rejection modal
- [ ] Rejection saves reason and updates status
- [ ] Rejected request moves to Rejected tab
- [ ] Pending badge updates count

**Database**:
- [ ] ingredient_requests table auto-created
- [ ] Requests insert with correct data
- [ ] Approvals create new ingredients
- [ ] Rejections store reason and timestamp

