# Restaurant Order Management Documentation (restoredController)

**File**: `/controllers/sellbillController.php` (Restaurant functions)  
**Purpose**: Restaurant order processing, table management, and POS operations integrated within the sales system  
**Last Updated**: December 19, 2024  
**Total Functions**: 15+ (restaurant-specific)  
**Lines of Code**: ~500+ (restaurant sections)

---

## 📋 Overview

The Restaurant Order Management functionality is integrated into the sellbillController.php and manages complete restaurant operations. This serves as the "restoredController" for:
- Restaurant order creation and management
- Table-based order processing (dining, takeaway, delivery)
- Kitchen order printing and workflow
- POS billing integration with restaurant services
- Multi-table order management
- Gaming station billing integration
- Restaurant-specific reporting and analytics
- User permission-based table access control

### Primary Functions
- [x] Restaurant bill creation and processing
- [x] Table-based order management
- [x] Takeaway and delivery order processing
- [x] Kitchen printer integration
- [x] Multi-payment method support
- [x] Gaming station billing
- [x] Restaurant order reporting
- [x] User permission-based access control

### Related Controllers
- [restauranthall.php](restauranthall.md) - Hall configuration and management
- [restauranttable.php](restauranttable.md) - Table setup and assignment
- [restaurantplaystation.php](restaurantplaystation.md) - Gaming station integration
- [restaurantKitchenPrinter.php](restaurantKitchenPrinter.md) - Kitchen printing
- [productController.php](productController.md) - Menu item management
- [clientController.php](clientController.md) - Customer management for delivery

---

## 🗄️ Database Tables

### Primary Tables (Restaurant Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **restaurantorder** | Main restaurant orders | id, sellBillId, tableId, totalBill, discount, netBill, rest, tax, hallPrice, finished, sysdate |
| **restaurantorderdetail** | Order line items | id, orderId, productId, quantity, price, total |
| **restaurantorderdeliverydetail** | Delivery information | orderId, customerName, phone, address, deliveryTime |
| **restaurantkitchenprint** | Kitchen print queue | Print jobs and status tracking |

### Integration Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **sellbill** | Main billing system | restaurantorder.sellBillId → sellbill.sellbillid |
| **sellbilldetail** | Bill line items | Integration with restaurant order details |
| **restauranttable** | Table management | restaurantorder.tableId → restauranttable.id |
| **restauranthall** | Hall configuration | Through table relationships |

### Special Table IDs
| Table ID | Service Type | Description |
|----------|-------------|-------------|
| **> 0** | Dining tables | Regular restaurant tables |
| **-1** | Takeaway | تيك أواى orders |
| **-2** | Delivery | دليفرى orders |

### Financial Integration
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **client** | Customer data | For delivery and takeaway orders |
| **save** | Cash registers | Payment processing |
| **savedaily** | Daily cash movements | Restaurant sales tracking |
| **dailyentry** | Accounting entries | Auto-generated from restaurant bills |

---

## 🔧 Key Functions

### 1. addresBill (Main Restaurant POS)
**Purpose**: Primary restaurant POS interface for order management  
**Called By**: `?do=addresBill`  
**Line**: 1777-1900+

**Parameters**:
- `id` (GET) - Edit existing order ID
- `tableId` (GET) - Table assignment

**Process Flow**:
```
┌─ Load Recent Orders ──┐
│ Last 20 restaurant    │
│ orders for reference  │
└───────────────────────┘
         │
         ▼
┌─ Handle Order Edit ───┐
│ If editing existing:  │
│ - Load order data     │
│ - Load client data    │
│ - Set finished=0      │
│ - Mark other orders   │
│   finished=1          │
└───────────────────────┘
         │
         ▼
┌─ User Permission ─────┐
│ Check takeaway,       │
│ delivery, hall access │
│ Build table query     │
└───────────────────────┘
         │
         ▼
┌─ Display POS ─────────┐
│ Restaurant billing    │
│ interface with tables │
└───────────────────────┘
```

**Code Example**:
```php
// Load order for editing
if ($OrdereditId) {
    $restaurantOrder = $restaurantOrderDAO->load($OrdereditId);
    $sellBilldata = $mySellbillRecord->load($restaurantOrder->sellBillId);
    $restaurantOrder->finished = 0;
    $restaurantOrderDAO->update($restaurantOrder);
    
    // Mark other table orders as finished
    R::exec("UPDATE `restaurantorder` SET `finished`= 1 WHERE id != '$OrdereditId'
        and tableId = '$tableId'");
}
```

### 2. addRestaurantBill()
**Purpose**: Convert restaurant order to sell bill with all integrations  
**Called By**: Restaurant order processing  
**Line**: 10807-11200+

**Parameters**:
- `$restaurantOrder` - Restaurant order object
- `$restaurantOrderDetails` - Array of order items

**Process Flow**:
```
┌─ Setup Bill Data ─────┐
│ billnameId = 3        │
│ Default client = 1    │
│ Handle delivery/take  │
│ away client selection │
└───────────────────────┘
         │
         ▼
┌─ Calculate Pricing ───┐
│ Hall price type       │
│ Tax calculations      │
│ Discount processing   │
└───────────────────────┘
         │
         ▼
┌─ Inventory Validation ┐
│ Check stock levels    │
│ Validate quantities   │
│ Handle size/color     │
└───────────────────────┘
         │
         ▼
┌─ Create Sell Bill ────┐
│ Generate unique serial│
│ Create bill record    │
│ Process bill details  │
└───────────────────────┘
         │
         ▼
┌─ Update Systems ──────┐
│ Update inventory      │
│ Create accounting     │
│ entries               │
│ Update client debt    │
└───────────────────────┘
```

**Key Features**:
- Automatic client selection for delivery/takeaway
- Hall-based pricing integration
- Tax calculation for restaurant orders
- Inventory validation and updates
- Accounting entry generation

### 3. Restaurant Order Workflow
**Purpose**: Handle complete restaurant order lifecycle  
**Lines**: 1920-2000 (processing section)

**Process Flow**:
```
┌─ Table Selection ─────┐
│ User selects table    │
│ or takeaway/delivery  │
└───────────────────────┘
         │
         ▼
┌─ Check Existing ──────┐
│ Look for unfinished   │
│ order on table        │
└───────────────────────┘
         │
         ▼
┌─ Order Processing ────┐
│ If existing order:    │
│ - Load details        │
│ - Add/edit items      │
│ If new order:         │
│ - Create new record   │
└───────────────────────┘
         │
         ▼
┌─ Billing Integration ─┐
│ Calculate totals      │
│ Apply discounts       │
│ Process payments      │
└───────────────────────┘
         │
         ▼
┌─ Kitchen Integration ─┐
│ Send to kitchen       │
│ printer queue         │
└───────────────────────┘
```

### 4. Table Access Control
**Purpose**: Control user access to different service types  
**Lines**: 1814-1845

**Permission Logic**:
```
User Group Permissions
       │
       ▼
┌─ Check Permissions ───┐
│ takeAway: 0/1         │
│ delivery: 0/1         │
│ hall: 0/1             │
│ seeAllHalls: 0/1      │
└───────────────────────┘
         │
         ▼
┌─ Build Query Filter ─┐
│ Based on permissions: │
│ - All tables          │
│ - Specific types only │
│ - No access (-1000)   │
└───────────────────────┘
         │
         ▼
┌─ Display Tables ──────┐
│ Show authorized       │
│ tables only           │
└───────────────────────┘
```

**Code Example**:
```php
// Permission-based table filtering
if ($Usergroupdata->takeAway == 0 && $Usergroupdata->delivery == 0 && $Usergroupdata->hall == 0) {
    $queryString = ' and restauranttable.id = -1000 ';  // No access
} else {
    $queryString = ' and ( ';
    if ($Usergroupdata->hall == 1) {
        $queryString .= ' restauranttable.id > 0 ';  // Regular tables
    }
    if ($Usergroupdata->takeAway == 1) {
        $queryString .= ' restauranttable.id = -1 ';  // Takeaway
    }
    if ($Usergroupdata->delivery == 1) {
        $queryString .= ' restauranttable.id = -2 ';  // Delivery
    }
    $queryString .= ' ) ';
}
```

### 5. Kitchen Printer Integration
**Purpose**: Send orders to kitchen printers  
**Integration**: With restaurantKitchenPrinter system

**Process Flow**:
```
Order Placed
       │
       ▼
┌─ Kitchen Print Job ───┐
│ Create print record   │
│ in kitchen queue      │
└───────────────────────┘
         │
         ▼
┌─ Kitchen Display ─────┐
│ Show order details    │
│ on kitchen screen     │
└───────────────────────┘
```

### 6. Gaming Station Integration
**Purpose**: Handle PlayStation billing through restaurant system  
**Integration**: With restaurantplaystation controller

**Process Flow**:
```
Gaming Session End
       │
       ▼
┌─ Calculate Time ──────┐
│ Session duration      │
│ Apply hourly rates    │
└───────────────────────┘
         │
         ▼
┌─ Create Service Bill ─┐
│ Use gaming service    │
│ product from station  │
└───────────────────────┘
         │
         ▼
┌─ Add to Table Order ──┐
│ If table has food     │
│ orders, combine       │
└───────────────────────┘
```

---

## 🔄 Business Logic Flow

### Complete Restaurant Order Workflow
```
Customer Arrival
       │
       ▼
┌─────────────────────────────┐
│ Service Type Selection      │
│ ┌─────────────────────────┐ │
│ │ Dining (Table > 0)      │ │
│ │ Takeaway (Table -1)     │ │
│ │ Delivery (Table -2)     │ │
│ └─────────────────────────┘ │
└─────────────────────────────┘
       │
       ▼
┌─────────────────────────────┐
│ Table Assignment            │
│ ┌─────────────────────────┐ │
│ │ Check table status      │ │
│ │ Look for existing order │ │
│ │ Set table as in use     │ │
│ └─────────────────────────┘ │
└─────────────────────────────┘
       │
       ▼
┌─────────────────────────────┐    ┌──────────────────┐
│ Order Management            │───▶│ Kitchen Workflow │
│ ┌─────────────────────────┐ │    │ - Print orders   │
│ │ Add menu items          │ │    │ - Track status   │
│ │ Calculate pricing       │ │    │ - Update queue   │
│ │ Apply discounts         │ │    │                  │
│ │ Handle modifications    │ │    └──────────────────┘
│ └─────────────────────────┘ │
└─────────────────────────────┘
       │
       ▼
┌─────────────────────────────┐
│ Billing & Payment           │
│ ┌─────────────────────────┐ │
│ │ Generate sell bill      │ │
│ │ Process payments        │ │
│ │ Update inventory        │ │
│ │ Create accounting       │ │
│ │ Print receipts          │ │
│ └─────────────────────────┘ │
└─────────────────────────────┘
```

### Service Type Handling
```
Order Creation
       │
    ┌──▼───┐
    │ Type │
    │Check │
    └──┬───┘
       │
  ┌────▼──────┐
  │  Service  │
  │   Type    │
  └─┬─┬─┬─────┘
    │ │ │
    │ │ └── Delivery ─────┐
    │ │                  │
    │ └── Takeaway ──────┼── Client Selection Required
    │                    │   Address/Phone for Delivery
    └── Dining ──────────┼── Table Service
                         │   Gaming Integration
                         │
                         ▼
                ┌─────────────────┐
                │ Order Processing│
                │ - Hall pricing  │
                │ - Kitchen print │
                │ - Table status  │
                └─────────────────┘
```

---

## ⚠️ Common Issues

### 1. Table State Management
**Issue**: Tables can have conflicting order states
**Solution**: finished flag ensures only one active order per table

### 2. Client Assignment for Delivery/Takeaway
**Issue**: Delivery orders require customer information
**Solution**: clientShowTawla setting controls client selection display

### 3. Inventory Integration
**Issue**: Restaurant orders must update inventory correctly
**Solution**: Integrated with standard sell bill inventory management

### 4. Kitchen Printer Queue
**Issue**: Orders must reach kitchen systems reliably
**Solution**: Kitchen print job queue with status tracking

### 5. Gaming Station Billing
**Issue**: Combined gaming and food orders need proper calculation
**Solution**: Service products integration through restaurant billing

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Configuration
- `../public/include_dao.php` - Database access objects
- `../public/authentication.php` - User authentication

### DAO Classes (Restaurant-specific)
- `RestaurantorderMySqlDAO` - Order operations
- `RestaurantorderMySqlExtDAO` - Extended order operations
- `RestaurantorderdetailsMySqlDAO` - Order details
- `RestauranttableMySqlDAO` - Table management
- `RestaurantkitchenprintMySqlDAO` - Kitchen printing

### Model Classes
- `Restaurantorder.class.php` - Order entity
- `Restaurantorderdetail.class.php` - Order detail entity
- `Restaurantorderdeliverydetail.class.php` - Delivery info entity
- `Restaurantkitchenprint.class.php` - Kitchen print entity

### Integration Dependencies
- Standard sell bill system (sellbillController main functions)
- Product management system for menu items
- Client management for delivery orders
- Inventory management for stock updates
- Accounting system for financial entries

### Templates
- `resturant/bill.html` - Main restaurant POS interface
- Kitchen printer templates for order display
- Standard sell bill templates for receipts

### Permission System
- User group settings for service type access
- Hall-specific user permissions
- Table access control based on user groups

---

**Integration Notes**:
- Restaurant functionality is fully integrated into the main sell bill system
- Orders flow through standard billing processes with restaurant-specific enhancements
- Kitchen integration provides real-time order communication
- Gaming station billing seamlessly integrates with food service
- Multi-service type support (dining, takeaway, delivery) with proper workflow management
- Complete audit trail through standard accounting integration