# Restaurant Table Controller Documentation

**File**: `/controllers/restauranttable.php`  
**Purpose**: Manages restaurant tables, dining arrangements, and special service types (takeaway/delivery)  
**Last Updated**: December 19, 2024  
**Total Functions**: 6  
**Lines of Code**: 223

---

## 📋 Overview

The Restaurant Table Controller manages individual table configurations within restaurant halls. It handles:
- Creating and managing restaurant tables
- Automatic takeaway and delivery table setup
- Table occupancy status tracking
- Table-hall relationships and assignments
- Special table types (-1 for takeaway, -2 for delivery)
- Integration with PlayStation gaming stations

### Primary Functions
- [x] Create new restaurant tables
- [x] Edit existing table configurations
- [x] Delete tables (hard delete)
- [x] View all tables with hall information
- [x] Automatic special table management (takeaway/delivery)
- [x] Table occupancy tracking
- [x] Hall-based table organization

### Related Controllers
- [restauranthall.php](restauranthall.md) - Hall management for table assignment
- [sellbillController.php](sellbillController.md) - Order processing for tables
- [restaurantplaystation.php](restaurantplaystation.md) - Gaming station integration
- [restaurantKitchenPrinter.php](restaurantKitchenPrinter.md) - Kitchen order printing
- [userController.php](userController.md) - User management
- [productController.php](productController.md) - Menu item management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **restauranttable** | Main table configuration | id, name, hallid, beingUsed, userId, sysdate, del |

### Related Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **restauranthall** | Hall master data | restauranttable.hallid → restauranthall.id |
| **restaurantplaystation** | Gaming stations | References table via tableId |
| **sellbill** | Order processing | Links to table for order management |
| **youtubelink** | Entertainment links | Display integration |

### Special Table IDs
| Table ID | Purpose | Hall ID | Name |
|----------|---------|---------|------|
| **-1** | Takeaway orders | -1 | 'تيك أواى' (Arabic for Takeaway) |
| **-2** | Delivery orders | -2 | 'دليفرى' (Arabic for Delivery) |

### Table Structure Details
**restauranttable** columns:
- `id` - Primary key (special IDs: -1 takeaway, -2 delivery)
- `name` - Table identifier/number
- `hallid` - Foreign key to restauranthall (or special hall IDs)
- `beingUsed` - Occupancy status (0=available, 1=occupied)
- `userId` - Creator user ID
- `sysdate` - Creation date
- `del` - Deletion flag (0=active, 1=deleted)

---

## 🔧 Key Functions

### 1. add()
**Purpose**: Create a new restaurant table with automatic special table setup  
**Called By**: Form submission with `?do=add`  
**Line**: 132-174

**Parameters** (via $_POST):
- `name` - Table name/number
- `hallid` - Hall assignment

**Process Flow**:
```
┌─ Check Special Tables ─┐
│ Takeaway (-1)         │
│ Delivery (-2)         │
└───────────────────────┘
         │
         ▼
┌─ Create Missing ──────┐
│ Special Tables        │
│ (if not exist)        │
└───────────────────────┘
         │
         ▼
┌─ Add Regular Table ───┐
│ Set hall assignment   │
│ Set default status    │
│ Insert to database    │
└───────────────────────┘
```

**Code Example**:
```php
// Auto-create takeaway table if missing
$takeAway = $restaurantTableDAO->load(-1);
if (!isset($takeAway->id) || $takeAway->id != -1) {
    $restaurantTable->id = -1;
    $restaurantTable->name = 'تيك أواى';
    $restaurantTable->hallid = -1;
    $restaurantTable->beingUsed = 0;
    $restaurantTableEX->insertWithId($restaurantTable);
}
```

### 2. show()
**Purpose**: Retrieve all restaurant tables  
**Called By**: `?do=show`  
**Line**: 176-182

**Returns**: Array of all restaurant table objects

**Process Flow**:
```
┌─ Query All Tables ─┐
│                   │
├─ Include Special ─┤
│  Tables (-1, -2)  │
│                   │
└─ Return Array ────┘
```

### 3. edit()
**Purpose**: Load table data for editing  
**Called By**: `?do=edit&id=X`  
**Line**: 184-191

**Parameters**:
- `id` (GET) - Table ID to edit

**Returns**: Table object with current configuration

**Process Flow**:
```
┌─ Get Table ID ────┐
│                  │
├─ Load Table ─────┤
│  Data            │
│                  │
└─ Return Object ──┘
```

### 4. update()
**Purpose**: Update existing table configuration  
**Called By**: Form submission with `?do=update`  
**Line**: 193-209

**Parameters** (via $_POST):
- `id` - Table ID to update
- `name` - Updated table name
- `hallid` - Updated hall assignment

**Process Flow**:
```
┌─ Get Table ID ────┐
│                  │
├─ Load Existing ──┤
│  Table Object    │
│                  │
├─ Update Fields ──┤
│  (preserve usage)│
│                  │
└─ Save Changes ───┘
```

### 5. delete()
**Purpose**: Delete a restaurant table  
**Called By**: `?do=delete&id=X`  
**Line**: 211-222

**Parameters**:
- `id` (GET) - Table ID to delete

**Process Flow**:
```
┌─ Get Table ID ────┐
│                  │
├─ Hard Delete ────┤
│  (not soft)      │
│                  │
└─ Remove Record ──┘
```

**Note**: Includes commented code for special table cleanup logic

### 6. Standard Controller Actions
**Purpose**: Handle routing and display  
**Lines**: 53-123

**Actions**:
- Default (empty do) - Show add form with halls
- `add` - Process new table creation
- `show` - Display all tables with YouTube links
- `edit` - Show edit form with hall selection
- `update` - Process table updates
- `delete` - Remove table
- `success/error` - Show result pages

---

## 🔄 Business Logic Flow

### Special Table Auto-Creation
```
Table Creation Request
       │
       ▼
┌─────────────────┐    ┌──────────────────┐
│ Check Takeaway  │───▶│ Check Delivery   │
│ Table (-1)      │    │ Table (-2)       │
│ Exists?         │    │ Exists?          │
└─────────────────┘    └──────────────────┘
       │                        │
       ▼ No                     ▼ No
┌─────────────────┐    ┌──────────────────┐
│ Create Takeaway │    │ Create Delivery  │
│ ID: -1          │    │ ID: -2           │
│ Hall: -1        │    │ Hall: -2         │
│ Name: تيك أواى  │    │ Name: دليفرى     │
└─────────────────┘    └──────────────────┘
       │                        │
       └────────┬─────────────────┘
               ▼
┌─────────────────────────────────┐
│ Create Regular Table            │
│ - Assign to selected hall       │
│ - Set available status          │
│ - Insert with auto-ID           │
└─────────────────────────────────┘
```

### Table Status Management
```
Table Creation
       │
       ▼
┌─────────────────┐
│ Set Default     │ ← beingUsed = 0 (available)
│ Status          │
│                 │
└─────────────────┘
       │
       ▼
┌─────────────────┐    Order Assignment
│ Available for   │◄─────────────────
│ Order           │
│ Assignment      │
└─────────────────┘
       │
       ▼ Order placed
┌─────────────────┐
│ Mark as Used    │ ← beingUsed = 1
│ (by order       │
│ system)         │
└─────────────────┘
```

### Special Table Usage
```
Order Type Selection
       │
    ┌──▼──┐
    │ POS │
    │ UI  │
    └──┬──┘
       │
  ┌────▼────┐
  │ Service │
  │ Type?   │
  └─┬─┬─┬───┘
    │ │ │
    │ │ └── Table Service ──┐
    │ │                    │
    │ └─── Delivery ───────┼── Use Table -2
    │                      │
    └──── Takeaway ────────┼── Use Table -1
                           │
                           ▼
                  ┌─────────────────┐
                  │ Process Order   │
                  │ with Special    │
                  │ Table ID        │
                  └─────────────────┘
```

---

## ⚠️ Common Issues

### 1. Special Table Management
**Issue**: Special tables (-1, -2) must exist for takeaway/delivery orders
**Solution**: Auto-creation logic ensures they exist before processing regular tables

### 2. Hall Assignment Validation
**Issue**: Tables must be assigned to valid halls
**Solution**: Form includes hall dropdown from restaurant hall table

### 3. Table Occupancy Tracking
**Issue**: beingUsed status must be properly managed by order system
**Solution**: Status is set by restaurant ordering system, not this controller

### 4. Arabic Text Encoding
**Issue**: Special table names use Arabic text
**Solution**: Database must support UTF-8 encoding for proper display

---

## 🔗 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
- `RestauranttableMySqlDAO` - Standard database operations
- `RestauranttableMySqlExtDAO` - Extended operations (insertWithId)
- `RestauranthallMySqlDAO` - Hall data access
- `YoutubeLinkMySqlDAO` - Entertainment links

### Model Classes
- `Restauranttable.class.php` - Table entity
- `Restauranthall.class.php` - Hall entity
- `YoutubeLink.class.php` - Entertainment entity

### Templates
- `restauranttableview/add.html` - Add table form
- `restauranttableview/show.html` - Table listing
- `restauranttableview/edit.html` - Edit table form
- `header.html` / `footer.html` - Layout templates
- `succes.html` / `error.html` - Result pages

### Special Methods
- `insertWithId()` - Extended DAO method for inserting with specific ID
- `queryByName()` - Check for duplicate table names (referenced in PlayStation controller)

---

**Integration Notes**:
- Tables are the primary unit for restaurant order assignment
- Special tables (-1, -2) handle off-premise orders (takeaway/delivery)
- Gaming stations (PlayStation) can be linked to specific tables
- Hall assignment enables organized restaurant layout management
- Table status (beingUsed) is managed by the ordering system for occupancy tracking