# Restaurant PlayStation Controller Documentation

**File**: `/controllers/restaurantplaystation.php`  
**Purpose**: Manages PlayStation gaming stations, hourly gaming services, and integrated table-gaming operations  
**Last Updated**: December 19, 2024  
**Total Functions**: 8  
**Lines of Code**: 524

---

## 📋 Overview

The Restaurant PlayStation Controller manages gaming station operations within the restaurant environment. It handles:
- Creating and configuring PlayStation gaming stations
- Setting up hourly pricing for gaming services
- Managing device identification and sub-device configurations
- Automatic product/service creation for gaming time
- Integration with restaurant tables for combined dining-gaming
- Daily gaming session reports and analytics
- Session tracking with start/end times and billing integration

### Primary Functions
- [x] Create new PlayStation stations with pricing
- [x] Edit existing station configurations
- [x] Delete stations with cleanup
- [x] Automatic service product creation
- [x] Device identification management
- [x] Table integration for dining-gaming
- [x] Daily session reports with duration tracking
- [x] Multi-user pricing tiers (single/multi-player)

### Related Controllers
- [sellbillController.php](sellbillController.md) - Gaming session billing
- [restauranthall.php](restauranthall.md) - Hall management
- [restauranttable.php](restauranttable.md) - Table integration
- [productController.php](productController.md) - Auto-created gaming services
- [productCatController.php](productCatController.md) - Gaming category management
- [restaurantKitchenPrinter.php](restaurantKitchenPrinter.md) - Order printing

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **restaurantplaystation** | Gaming station config | id, name, hourPrice, hourPriceMulti, beingUsed, tableId, serviceId, deviceIdentification, subDeviceIdentification, useSubIdentification |
| **restaurantplaystationplay** | Gaming sessions | id, playstationid, startsysDate, endsysDate, allMovesUnitedSellBillId, moveStartSysDate, finished, oldPsPlayid |

### Integration Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **restauranttable** | Optional table link | restaurantplaystation.tableId → restauranttable.id |
| **restauranthall** | Hall assignment | Through table relationship |
| **product** | Auto-created service | restaurantplaystation.serviceId → product.productid |
| **productcat** | Gaming category | Auto-created "بلاي ستيشن" category |
| **sellbill** | Gaming session billing | restaurantplaystationplay.allMovesUnitedSellBillId |

### Reference Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **youtubelink** | Entertainment links | Display integration |
| **productunit** | Service units | For gaming service products |
| **user** | System users | Creator and access tracking |

### Table Structure Details
**restaurantplaystation** columns:
- `id` - Primary key, auto-increment
- `name` - Station name/identifier
- `hourPrice` - Single player hourly rate (DECIMAL)
- `hourPriceMulti` - Multi-player hourly rate (DECIMAL)
- `beingUsed` - Current usage status (0=available, 1=in use)
- `tableId` - Optional linked table ID (0 if standalone)
- `serviceId` - Auto-created product/service ID
- `deviceIdentification` - Device MAC/serial (VARCHAR)
- `subDeviceIdentification` - Secondary device ID
- `useSubIdentification` - Enable sub-device (0/1)
- `userId` - Creator user ID
- `sysdate` - Creation timestamp
- `del` - Soft delete flag

**restaurantplaystationplay** columns:
- `playstationid` - Foreign key to station
- `startsysDate` - Session start time
- `endsysDate` - Session end time
- `allMovesUnitedSellBillId` - Billing reference
- `moveStartSysDate` - Actual usage start
- `finished` - Session completion flag
- `oldPsPlayid` - Legacy session reference

---

## 🔧 Key Functions

### 1. add()
**Purpose**: Create new PlayStation station with auto-service creation  
**Called By**: Form submission with `?do=add`  
**Line**: 216-264

**Parameters** (via $_POST):
- `name` - Station name
- `hallid` - Hall assignment (for table creation)
- `hasTable` - Create linked table (0/1)
- `hourPrice` - Single player hourly rate
- `hourPriceMulti` - Multi-player hourly rate
- `deviceIdentification` - Device ID
- `subDeviceIdentification` - Sub-device ID
- `useSubIdentification` - Enable sub-device (0/1)

**Process Flow**:
```
┌─ Create Gaming Category ──┐
│ Auto-create "بلاي ستيشن"   │
│ product category          │
└───────────────────────────┘
         │
         ▼
┌─ Create Gaming Service ───┐
│ Auto-create product for   │
│ gaming time billing       │
└───────────────────────────┘
         │
         ▼
┌─ Create Table (Optional) ─┐
│ If hasTable=1, create     │
│ linked restaurant table   │
└───────────────────────────┘
         │
         ▼
┌─ Create PlayStation ──────┐
│ Station configuration     │
│ with all references       │
└───────────────────────────┘
```

**Code Example**:
```php
// Auto-create service category and product
$catId = addTheCategory();  // Creates "بلاي ستيشن" category
$serviceId = addService($catId, $name);  // Creates gaming service

// Optional table creation
if ($hasTable == 1) {
    $restaurantTable->name = (count($check) > 0) ? $name . "_ps" : $name;
    $tableId = $restaurantTableDAO->insert($restaurantTable);
}
```

### 2. update()
**Purpose**: Update station configuration with complex table management  
**Called By**: Form submission with `?do=update`  
**Line**: 266-351

**Parameters** (via $_POST):
- `id` - Station ID to update
- `oldhallid` - Previous hall ID
- `name` - Updated station name
- `hallid` - New hall assignment
- `hasTable` - Table requirement (0/1)
- `hourPrice` - Updated single player rate
- `hourPriceMulti` - Updated multi-player rate
- Device identification fields

**Process Flow**:
```
┌─ Update Service Product ──┐
│ Keep same serviceId but   │
│ update product details    │
└───────────────────────────┘
         │
         ▼
┌─ Complex Table Logic ─────┐
│ 4 scenarios:              │
│ 1. No table → Table       │
│ 2. Table → Table (update) │
│ 3. No table → No table    │
│ 4. Table → No table (del) │
└───────────────────────────┘
         │
         ▼
┌─ Update PlayStation ──────┐
│ Station configuration     │
│ with preserved status     │
└───────────────────────────┘
```

### 3. delete()
**Purpose**: Soft delete station with table cleanup  
**Called By**: `?do=delete&id=X`  
**Line**: 353-374

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

**Process Flow**:
```
┌─ Load PlayStation ────┐
│ Get current config    │
└───────────────────────┘
         │
         ▼
┌─ Soft Delete Station ─┐
│ Set del = 1           │
└───────────────────────┘
         │
         ▼
┌─ Delete Linked Table ─┐
│ If tableId > 0,       │
│ soft delete table too │
└───────────────────────┘
```

### 4. addTheCategory()
**Purpose**: Auto-create or find PlayStation product category  
**Line**: 376-405

**Returns**: Category ID for gaming products

**Process Flow**:
```
┌─ Check Existing ──────┐
│ Look for "بلاي ستيشن"  │
│ category              │
└───────────────────────┘
         │
         ▼ Not found
┌─ Create Category ─────┐
│ Use CURL to product   │
│ category controller   │
└───────────────────────┘
```

### 5. addService()
**Purpose**: Create gaming service product  
**Line**: 407-442

**Parameters**:
- `catId` - Gaming category ID
- `name` - Service name (station name)

**Returns**: Product ID for gaming service

**Process Flow**:
```
┌─ Prepare Product Data ┐
│ Gaming service config: │
│ - isservice = 1        │
│ - No inventory         │
│ - Zero prices (set via │
│   station pricing)     │
└────────────────────────┘
         │
         ▼
┌─ CURL to Product ─────┐
│ Controller for        │
│ service creation      │
└───────────────────────┘
```

### 6. updateService()
**Purpose**: Update existing gaming service product  
**Line**: 444-485

**Parameters**:
- `catId` - Category ID
- `name` - Updated service name
- `serviceId` - Existing service ID

### 7. dayReport()
**Purpose**: Generate daily gaming session reports  
**Called By**: `?do=dayReport`  
**Line**: 153-196

**Parameters** (via $_POST):
- `datefrom` - Report start date
- `dateto` - Report end date
- `restaurantplaystationId` - Specific station filter

**Process Flow**:
```
┌─ Build Query Filters ─┐
│ Date range, station    │
│ Default: today only    │
└────────────────────────┘
         │
         ▼
┌─ Get Session Data ────┐
│ Finished sessions with│
│ billing references    │
└────────────────────────┘
         │
         ▼
┌─ Calculate Durations ─┐
│ Start/end times       │
│ Format H:i display    │
└────────────────────────┘
```

**Code Example**:
```php
foreach ($result as $sellbilldetail) {
    $sellbilldetail->startTime = date('H:i', strtotime($sellbilldetail->moveStartSysDate));
    $sellbilldetail->endTime = date('H:i', strtotime($sellbilldetail->endsysDate));
    
    $datetime1 = new DateTime($sellbilldetail->moveStartSysDate);
    $datetime2 = new DateTime($sellbilldetail->endsysDate);
    $interval = $datetime1->diff($datetime2);
    $sellbilldetail->duration = $interval->format('%h') . ":" . $interval->format('%i');
}
```

### 8. CURL_IT2()
**Purpose**: Internal CURL helper for cross-controller calls  
**Line**: 487-523

**Parameters**:
- `data_arr` - Data array for POST
- `url` - Target controller endpoint

**Purpose**: Enables calling product/category controllers for service creation

---

## 🔄 Business Logic Flow

### Station Creation with Service Integration
```
User Station Setup
       │
       ▼
┌─────────────────────────────┐
│ Auto Product Management     │
│ ┌─────────────────────────┐ │
│ │ 1. Create/Find Category │ │
│ │    "بلاي ستيشن"         │ │
│ │ 2. Create Gaming Service│ │
│ │    Product (isservice=1)│ │
│ └─────────────────────────┘ │
└─────────────────────────────┘
       │
       ▼
┌─────────────────────────────┐    ┌──────────────────┐
│ Optional Table Management   │───▶│ Station Creation │
│ ┌─────────────────────────┐ │    │ - Link serviceId │
│ │ If hasTable=1:          │ │    │ - Set pricing    │
│ │ 1. Check name conflicts │ │    │ - Device config  │
│ │ 2. Create table         │ │    │ - Default status │
│ │ 3. Link to station      │ │    │                  │
│ └─────────────────────────┘ │    └──────────────────┘
└─────────────────────────────┘
```

### Gaming Session Workflow
```
Station Available (beingUsed=0)
       │
       ▼
┌─────────────────┐    ┌─────────────────┐
│ Session Start   │───▶│ Create Session  │
│ (External POS)  │    │ Record in       │
│                 │    │ playstationplay │
└─────────────────┘    └─────────────────┘
       │                        │
       ▼                        ▼
┌─────────────────┐    ┌─────────────────┐
│ Mark Station    │    │ Track Time      │
│ beingUsed=1     │    │ Start/End       │
│                 │    │ Duration        │
└─────────────────┘    └─────────────────┘
       │                        │
       ▼                        ▼
┌─────────────────────────────────────────┐
│ Gaming Session End                      │
│ 1. Calculate total time                 │
│ 2. Generate sell bill (via serviceId)  │
│ 3. Apply hourly pricing                 │
│ 4. Mark station available               │
│ 5. Set finished=1 in session record    │
└─────────────────────────────────────────┘
```

### Table-Gaming Integration
```
Station with Table (hasTable=1)
       │
       ▼
┌─────────────────┐    ┌─────────────────┐
│ Combined Order  │───▶│ Table Service   │
│ - Gaming time   │    │ - Food/drinks   │
│ - Food service  │    │ - Same location │
└─────────────────┘    └─────────────────┘
       │                        │
       ▼                        ▼
┌─────────────────────────────────────────┐
│ Unified Billing                         │
│ - Gaming charges (hourly)               │
│ - Food/drink charges                    │
│ - Single sell bill                      │
└─────────────────────────────────────────┘
```

---

## ⚠️ Common Issues

### 1. Service Product Creation
**Issue**: Gaming stations require auto-created service products for billing
**Solution**: addTheCategory() and addService() handle automatic product setup

### 2. Table Management Complexity
**Issue**: 4 different table scenarios in update logic
**Solution**: Comprehensive if-else logic handles all transitions

### 3. Device Identification
**Issue**: Multiple device tracking for complex gaming setups
**Solution**: Primary and sub-device identification fields

### 4. Session Billing Integration
**Issue**: Gaming time must integrate with restaurant billing system
**Solution**: serviceId links to product system for automatic pricing

### 5. Arabic Text in Category
**Issue**: Auto-created category uses Arabic text "بلاي ستيشن"
**Solution**: Ensure UTF-8 database 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
- `RestaurantplaystationMySqlDAO` - Station operations
- `RestaurantplaystationMySqlExtDAO` - Extended operations
- `RestaurantplaystationplayMySqlDAO` - Session tracking
- `RestauranttableMySqlDAO` - Table integration
- `RestauranthallMySqlDAO` - Hall data
- `ProductcatMySqlDAO` - Category management
- `ProductunitMySqlExtDAO` - Unit operations

### Model Classes
- `Restaurantplaystation.class.php` - Station entity
- `Restaurantplaystationplay.class.php` - Session entity
- `Restauranttable.class.php` - Table entity
- `Productcat.class.php` - Category entity

### External Integrations
- `productController.php` - Auto-service creation
- `productCatController.php` - Auto-category creation
- CURL integration for cross-controller operations

### Templates
- `restaurantplaystationview/add.html` - Add station form
- `restaurantplaystationview/show.html` - Station listing
- `restaurantplaystationview/edit.html` - Edit station form
- `restaurantplaystationview/dayReport.html` - Session reports
- Standard layout templates

---

**Integration Notes**:
- Gaming stations create billable services automatically
- Optional table integration enables dining-gaming combinations
- Session tracking provides detailed usage analytics
- Device identification supports complex gaming setups
- Hourly pricing model with single/multi-player rates
- Seamless integration with restaurant billing system via sell bills