# BuyerKiosk Mock Data Generator

Comprehensive mock data generation system for simulating realistic business day activity in BuyerKiosk resale stores.

## Overview

The `MockDataGenerator` class provides a sophisticated system for generating realistic test data that simulates a full business day at a resale store. It maintains state between runs and respects business hours, making it ideal for testing, demonstrations, and development.

## Features

- **Buy Queue Simulation**: Creates, progresses, and completes buy transactions
- **Customer Management**: Mixes existing customers (70%) with new customers (30%)
- **Employee Activities**: Assigns employees to buys and tasks
- **Business Hours Awareness**: Operates only during configured store hours (9am-7pm)
- **State Persistence**: Maintains state between runs for continuous simulation
- **Weekend Traffic Modeling**: 1.5x traffic on Saturdays and Sundays
- **Realistic Timing**: Buys progress through stages over 15-30 minutes
- **Time Zone Support**: Respects store's configured timezone

## Installation

The class requires:
- PHP 8.x
- FakerPHP (already installed via composer)
- BuyerKiosk database access
- Store configuration

## Usage

### Basic Usage

```php
<?php
require_once __DIR__ . "/MockDataGenerator.php";

use BuyerKiosk\Mock\MockDataGenerator;

// Initialize for a specific store
$generator = new MockDataGenerator('cm00');

// Run data generation
$stats = $generator->run();

// View results
print_r($stats);
```

### Command Line Usage

```bash
# Run the example script
php example-usage.php cm00
```

### Scheduled Execution

For continuous simulation, set up a cron job:

```cron
# Run every 30 minutes during business hours
*/30 9-18 * * * php /path/to/example-usage.php cm00
```

## Architecture

### State Management

State is persisted to `/tmp/mockdata_{typeNum}_state.json` and tracks:
- Last run timestamp
- Current day buys created/completed
- Cash activity generation status

### Business Logic

**Operating Hours**: 9am - 7pm (configurable via constants)

**Traffic Patterns**:
- Weekdays: 1-3 buys per 30-minute interval
- Weekends: 1.5x weekday traffic
- Adjusts based on elapsed time since last run

**Buy Lifecycle**:
1. `timeEntered` - Customer enters queue
2. `sortStarted` - Employee begins sorting items
3. `sortCompleted` - Sorting finished
4. `timeStarted` - Buyer begins evaluating
5. `timeCompleted` - Buy completed, customer paid

**Customer Mix**:
- 70% existing customers (randomly selected from database)
- 30% new customers (generated with Faker)

## Class Structure

### Constructor

```php
public function __construct(string $typeNum, ?int $lastRunTimestamp = null)
```

**Parameters**:
- `$typeNum`: Store identifier (e.g., 'cm00', 'pa00')
- `$lastRunTimestamp`: Optional override for last run time (defaults to 30 minutes ago)

### Main Methods

#### `run(): array`
Main orchestration method. Returns statistics array with:
- `timestamp`: Run timestamp
- `storeTime`: Current time in store timezone
- `withinBusinessHours`: Boolean
- `isStartOfDay`: Boolean
- `isEndOfDay`: Boolean
- `elapsedMinutes`: Minutes since last run
- `buys`: Buy activity statistics
- `dailySales`: Sales data statistics
- `liveFinancials`: Financial update status
- `tasks`: Task completion statistics
- `cashActivity`: Cash activity records (start/end of day)
- `closeSalesReport`: End of day report status

#### Time & State Methods

- `getStoreCurrentTime(): DateTime` - Current time in store timezone
- `isWithinBusinessHours(): bool` - Check if currently in business hours
- `isStartOfDay(): bool` - Check if first hour of business
- `isEndOfDay(): bool` - Check if last hour of business
- `getElapsedMinutes(): int` - Minutes since last run
- `getState(): array` - Get current state data

#### Data Access Methods

- `getActiveEmployees(): array` - Fetch active employees from database
- `getExistingCustomers(int $limit = 50): array` - Fetch random existing customers

### Stub Methods (To Be Implemented)

These methods currently return empty statistics but are designed to be implemented:

- `generateBuys(): array` - Create and progress buy transactions
- `generateDailySalesData(): array` - Create daily sales records
- `generateLiveFinancials(): array` - Update real-time financial data
- `generateTaskCompletions(): array` - Simulate task completions
- `generateCloseSalesReport(): array` - Generate end-of-day report
- `handleCashActivity(): array` - Generate cash register activity

## Configuration

### Constants

```php
const BUSINESS_START_HOUR = 9;          // 9am
const BUSINESS_END_HOUR = 19;           // 7pm
const MIN_BUYS_PER_INTERVAL = 1;
const MAX_BUYS_PER_INTERVAL = 3;
const EXISTING_CUSTOMER_RATIO = 0.7;    // 70%
const WEEKEND_MULTIPLIER = 1.5;         // 1.5x traffic
const MIN_BUY_DURATION = 15;            // minutes
const MAX_BUY_DURATION = 30;            // minutes
```

## Database Schema

### Required Tables

**employees**:
- `employeeID`, `employeeFirstName`, `employeeLastName`, `role`, `active`

**customers**:
- `customerID`, `firstName`, `lastName`, `phone`, `email`, `address`, `city`, `state`, `zipcode`

**buyQueue**:
- `buyID`, `dailyNum`, `timeEntered`, `sortStarted`, `sortCompleted`, `timeStarted`, `timeCompleted`
- `sorterID`, `buyerID`, `numContainers`, `textMe`, `inStore`

## Implementation Roadmap

### Phase 1: Buy Generation (Priority)
1. Implement `generateBuys()`
2. Create buy entries with realistic data
3. Progress existing buys through stages
4. Assign employees appropriately

### Phase 2: Sales & Financials
1. Implement `generateDailySalesData()`
2. Implement `generateLiveFinancials()`
3. Calculate aggregates and statistics

### Phase 3: Cash Activity Integration
1. Integrate with existing `CashActivityMock.php`
2. Implement `handleCashActivity()`
3. Generate register open/close records

### Phase 4: Tasks & Reports
1. Implement `generateTaskCompletions()`
2. Implement `generateCloseSalesReport()`
3. Create end-of-day summaries

## Example Output

```
[2025-12-02 10:30:45] [cm00] MockDataGenerator initialized for store cm00
[2025-12-02 10:30:45] [cm00] Starting mock data generation run
[2025-12-02 10:30:45] [cm00] Generating buy activity (stub)
[2025-12-02 10:30:45] [cm00] Generating daily sales data (stub)
[2025-12-02 10:30:45] [cm00] Generating live financials (stub)
[2025-12-02 10:30:45] [cm00] Generating task completions (stub)
[2025-12-02 10:30:45] [cm00] State saved successfully
[2025-12-02 10:30:45] [cm00] Mock data generation completed

========================================
Mock Data Generation Results
========================================

Timestamp: 2025-12-02 10:30:45
Store Time: 2025-12-02 10:30:45
Within Business Hours: Yes
Start of Day: No
End of Day: No
Minutes Elapsed: 30

--- Buy Activity ---
Buys Created: 0
Buys Progressed: 0
Buys Completed: 0
```

## Testing

```bash
# Test syntax
php -l MockDataGenerator.php

# Test instantiation
php -r "require 'MockDataGenerator.php'; \$g = new BuyerKiosk\Mock\MockDataGenerator('cm00'); echo 'OK';"

# Run example
php example-usage.php cm00
```

## Troubleshooting

**Store not found**: Verify typeNum exists in stores table
**Database connection error**: Check database credentials in config
**State file permissions**: Ensure /tmp is writable
**Timezone issues**: Verify store timezone is set correctly

## Related Files

- `CashActivityMock.php` - Cash register activity generator (existing)
- `example-usage.php` - Example implementation script
- `../initialize.php` - BuyerKiosk bootstrap file

## License

Part of the BuyerKiosk system. See main project license.

## Version History

- **1.0.0** (2025-12-02): Initial implementation with core framework and stub methods
