# Invoice Search and Cook Feature - POS Screen

## Overview
This feature adds a search field to the POS screen that allows staff to quickly search for orders by invoice number and automatically mark them as cooked. This is particularly useful for kitchen staff who need to quickly update order statuses without navigating to the kitchen display.

## Features

### 1. **Search & Cook Button**
- **Location**: POS Form Actions (right side, near recent transactions button)
- **Functionality**: Opens modal for invoice search and cooking
- **Style**: Green rounded button with white text and search icon, following POS button design
- **Text**: "Search & Cook"
- **Tooltip**: "Search Invoice and Mark as Cooked"
- **Responsive**: Full width on mobile devices

### 2. **Search Modal**
- **Trigger**: Click "Search & Cook" button
- **Size**: Large modal (modal-lg) for better visibility
- **Content**: Invoice search field and processing interface
- **Features**: Real-time search, order details display, status updates

### 3. **Search Field**
- **Location**: Inside the modal
- **Functionality**: Real-time search as you type
- **Input Type**: Text field with label
- **Placeholder**: "Start typing invoice number or customer name..."
- **Search Trigger**: Starts searching after 2 characters
- **Search Delay**: 300ms debounce to avoid excessive requests

### 4. **Cook Button**
- **Style**: Green success button with check icon
- **Function**: Triggers the search and cook process
- **Text**: "Search & Cook"
- **Location**: Inside modal, next to search field

### 5. **Search Results Display**
- **Location**: Inside the modal
- **Content**: Shows real-time search results as you type
- **Format**: Panel layout with organized invoice listings
- **Information Displayed**:
  - Invoice number
  - Customer name
  - Table name
  - Creation date
  - Individual "Mark as Cooked" buttons for each result
- **Limit**: Maximum 10 results for performance
- **Ordering**: Most recent invoices first

### 6. **Order Details Display**
- **Location**: Inside the modal
- **Content**: Shows order information after successful processing
- **Format**: Panel layout with organized information
- **Information Displayed**:
  - Invoice number
  - Customer name
  - Table name
  - Items processed count
  - Status confirmation

### 7. **Keyboard Shortcut**
- **Key**: Enter key
- **Action**: Automatically searches and cooks the order
- **Behavior**: Same as clicking the Search & Cook button

## How It Works

### **Search Process:**
1. **Open Modal**: Staff clicks "Search & Cook" button in POS form actions area
2. **Real-time Search**: Staff starts typing invoice number or customer name
3. **Live Results**: System shows matching invoices as they type (after 2+ characters)
4. **Select Order**: Staff clicks "Mark as Cooked" button on desired result
5. **Processing**: System marks all pending kitchen items as "cooked"
6. **Feedback**: Shows success message and order details in modal
7. **Cleanup**: Clears search field and resets modal state

### **Real-time Search Features:**
- **Instant Results**: Search starts after typing 2 characters
- **Debounced Input**: 300ms delay to prevent excessive API calls
- **Multiple Search Fields**: Searches both invoice number and customer name
- **Performance Optimized**: Limited to 10 results, ordered by date
- **Interactive Results**: Each result has its own "Mark as Cooked" button

### **Business Logic:**
- **Invoice Validation**: Ensures invoice exists and is a final sale
- **Kitchen Items Check**: Only processes orders with kitchen products
- **Status Validation**: Prevents processing already completed items
- **Batch Update**: Updates all pending kitchen items simultaneously

### **Error Handling:**
- **Invalid Invoice**: Shows "Invoice not found or invalid"
- **No Kitchen Items**: Shows "This invoice has no kitchen items to cook"
- **Already Completed**: Shows "All kitchen items are already cooked or completed"
- **System Errors**: Shows generic error message with logging

## Technical Implementation

### **Files Modified:**

#### **1. POS Form Actions:**
- `resources/views/sale_pos/partials/pos_form_actions.blade.php` - Added "Search & Cook" button following POS button style

#### **2. JavaScript Functionality:**
- `resources/views/sale_pos/create.blade.php` - Added modal functionality and search/cook JavaScript functions

#### **3. Backend Controller:**
- `app/Http/Controllers/Restaurant/KitchenController.php` - Added `searchAndCookInvoice()` method

#### **4. Routes:**
- `routes/web.php` - Added `/kitchen/search-and-cook` and `/kitchen/search-invoices` routes

#### **5. Styling:**
- `resources/views/sale_pos/create.blade.php` - Added CSS for modal styling and search field appearance

### **New Routes:**
```php
Route::post('/kitchen/search-and-cook', [Restaurant\KitchenController::class, 'searchAndCookInvoice']);
Route::post('/kitchen/search-invoices', [Restaurant\KitchenController::class, 'searchInvoices']);
```

### **Controller Methods:**
```php
public function searchAndCookInvoice(Request $request)
{
    // 1. Validate invoice number
    // 2. Find transaction
    // 3. Check for kitchen items
    // 4. Mark items as cooked
    // 5. Return success with order details
}

public function searchInvoices(Request $request)
{
    // 1. Validate search query (minimum 2 characters)
    // 2. Search invoices and customer names
    // 3. Filter for kitchen products only
    // 4. Return formatted results (max 10)
}
```

## User Experience

### **For POS Staff:**
1. **Quick Access**: "Search & Cook" button in POS form actions area (right side)
2. **Modal Interface**: Clean, focused search interface
3. **Fast Processing**: Enter invoice and press Enter or click button
4. **Visual Feedback**: Clear success/error messages in modal
5. **Order Details**: See what was processed in organized panel
6. **Auto-focus**: Search field automatically focuses when modal opens
7. **Consistent Design**: Button follows same style as other POS action buttons

### **For Kitchen Staff:**
1. **Efficient Updates**: Quick order status updates
2. **Batch Processing**: Multiple items updated at once
3. **Status Tracking**: Clear confirmation of actions
4. **Error Prevention**: Validation prevents duplicate processing

## Benefits

### **Operational Efficiency:**
1. **Time Savings**: No need to navigate to kitchen display
2. **Quick Updates**: Instant order status changes
3. **Batch Processing**: Multiple items updated simultaneously
4. **Error Reduction**: Validation prevents invalid operations

### **User Experience:**
1. **Intuitive Interface**: Simple search and click process
2. **Keyboard Friendly**: Enter key support for power users
3. **Visual Feedback**: Clear success/error indicators
4. **Responsive Design**: Smooth animations and transitions

### **Business Process:**
1. **Streamlined Workflow**: Faster order processing
2. **Better Tracking**: Clear audit trail of actions
3. **Reduced Errors**: Validation prevents mistakes
4. **Improved Communication**: Clear status updates

## Usage Instructions

### **Basic Usage:**
1. **Locate Search Field**: Find the search field next to kitchen order checkbox
2. **Enter Invoice**: Type the invoice number
3. **Process Order**: Press Enter or click Cook button
4. **View Results**: See success message and order details

### **Advanced Usage:**
1. **Keyboard Shortcut**: Use Enter key for faster processing
2. **Batch Operations**: Process multiple orders quickly
3. **Status Verification**: Check order details after processing
4. **Error Handling**: Understand and resolve any issues

### **Best Practices:**
1. **Verify Invoice**: Double-check invoice number before processing
2. **Check Status**: Review order details after processing
3. **Handle Errors**: Read error messages for troubleshooting
4. **Maintain Focus**: Keep search field focused for efficiency

## Configuration

### **Automatic Features:**
- **No Setup Required**: Feature works out of the box
- **Conditional Display**: Only shows when kitchen module is enabled
- **Auto-focus**: Search field automatically focuses
- **Auto-clear**: Field clears after successful processing

### **Customization Options:**
- **Update Frequency**: Modify auto-hide timing (currently 10 seconds)
- **Field Styling**: Customize colors and animations via CSS
- **Validation Logic**: Adjust business rules in controller
- **Error Messages**: Modify user-facing messages

## Troubleshooting

### **Common Issues:**

#### **Search Field Not Visible:**
1. Check if kitchen module is enabled
2. Verify user has proper permissions
3. Check browser console for JavaScript errors
4. Ensure proper file modifications

#### **Search Not Working:**
1. Verify invoice number format
2. Check browser console for AJAX errors
3. Confirm route `/kitchen/search-and-cook` exists
4. Verify database permissions

#### **Orders Not Marking as Cooked:**
1. Check if invoice has kitchen products
2. Verify order status is not already completed
3. Review controller method logic
4. Check database for transaction status

### **Debug Information:**
- **JavaScript Console**: Check for AJAX errors and responses
- **Network Tab**: Monitor API calls and responses
- **Database Logs**: Check for query execution issues
- **Laravel Logs**: Review application error logs

## Future Enhancements

### **Potential Improvements:**
1. **Barcode Scanning**: Support for barcode invoice scanning
2. **Voice Input**: Voice recognition for invoice numbers
3. **Recent Searches**: Dropdown of recently processed invoices
4. **Batch Processing**: Process multiple invoices at once
5. **Advanced Filtering**: Search by customer, table, or date

### **Integration Possibilities:**
1. **POS Integration**: Real-time updates when orders are placed
2. **Kitchen Display**: Synchronized status updates
3. **Order Management**: Advanced order workflow management
4. **Reporting**: Track cooking times and patterns

## Conclusion

This invoice search and cook feature significantly improves the POS workflow by:
- **Providing quick access** to order processing functionality
- **Streamlining the cooking process** with instant status updates
- **Improving user experience** with intuitive search and feedback
- **Enhancing operational efficiency** for both POS and kitchen staff

The feature integrates seamlessly with the existing POS system and provides a modern, efficient way to manage kitchen order statuses without leaving the POS interface.
