# Shop Manager Pro - PHP Plugin Development Guide

This file provides guidance to Claude Code (claude.ai/code) and other code agents when working with the PHP plugin codebase.

## Plugin Overview

Shop Manager Pro is a WordPress plugin that provides an advanced management interface for WooCommerce shops. The PHP plugin provides:
- REST API endpoints for the Vue.js frontend
- Background job processing using WordPress Action Scheduler
- Integration with WooCommerce products, taxonomies, and metadata
- Support for Advanced Custom Fields (ACF)
- Premium features including export, licensing, and custom fields

## Project Structure

```
apps/shopmanagerpro/plugin/
├── assets/                # Compiled frontend assets (do not edit directly)
├── includes/              # Main PHP source code
│   ├── ACF/              # Advanced Custom Fields integration
│   ├── Filters/          # Product filtering logic
│   ├── Images/           # Image handling and API
│   ├── Jobs/             # Background job processing
│   ├── Premium/          # Premium features (commercial version)
│   ├── Products/         # Product management core
│   │   ├── DTO/          # Data Transfer Objects
│   │   │   └── Generated/  # Auto-generated from schemas
│   │   ├── Fields/       # Product field management
│   │   └── Groups/       # Product group operations
│   ├── Shared/           # Shared utilities and services
│   ├── System/           # System information API
│   ├── TaxClasses/       # Tax class management
│   └── Taxonomies/       # Taxonomy management
├── languages/            # Translation files
├── vendor/               # Composer dependencies
├── composer.json         # Plugin dependencies
├── readme.txt           # WordPress plugin readme
└── shopmanagerpro.php   # Main plugin file
```

## Key Architecture Concepts

### 1. Autoloading
The plugin uses a custom autoloader (defined in `shopmanagerpro.php`) that maps `ShopManagerPro\*` namespaces to the `includes/` directory.

### 2. REST API Pattern
Each major feature has an API class that:
- Registers REST routes in a static `init()` method
- Defines OpenAPI-style schemas as static properties (`$SCHEMA_*`)
- Implements endpoint callbacks as static methods
- Uses `\ShopManagerPro\Shared\CapabilityService` for permissions

Example:
```php
class ProductAPI {
    public static $SCHEMA;
    
    public static function init() {
        // Called from InitService
        self::registerRoutes();
        self::initSchemas();
    }
    
    public static function registerRoutes() {
        register_rest_route(Constants::API_NAMESPACE, '/products/get', [...]);
    }
}
```

### 3. Data Transfer Objects (DTOs)
- DTOs in `DTO/Generated/` directories are auto-generated using `helmich/schema2class`
- Do not edit generated files directly
- Base DTOs extend or compose generated classes
- Generated from OpenAPI schemas defined in API classes

### 4. Repository Pattern
Most features have a Repository class for database operations:
- Handles WordPress database queries
- Returns DTO instances
- Uses `\ShopManagerPro\Shared\Utils\SQL` for query building

### 5. Service Classes
Business logic is encapsulated in Service classes:
- Named with `*Service` suffix
- Handle complex operations
- Coordinate between repositories and APIs

## Development Commands

### Running Tests
```bash
# All tests
phpunit --bootstrap /workspace/apps/shopmanagerpro/plugin-tests/bootstrap.php /workspace/apps/shopmanagerpro/plugin-tests

# Unit tests only
phpunit --bootstrap /workspace/apps/shopmanagerpro/plugin-tests/bootstrap.php /workspace/apps/shopmanagerpro/plugin-tests/unit

# Integration tests only
phpunit --bootstrap /workspace/apps/shopmanagerpro/plugin-tests/bootstrap.php /workspace/apps/shopmanagerpro/plugin-tests/integration

# Specific test file
phpunit --bootstrap /workspace/apps/shopmanagerpro/plugin-tests/bootstrap.php /workspace/apps/shopmanagerpro/plugin-tests/unit/ProductTest.php
```

### Code Quality
```bash
# Run PHPStan (from workspace root)
phpstan --no-progress

# Format code with PHP CS Fixer (run after making changes)
php-cs-fixer fix
```

### Database Access
```bash
# Query the WordPress database
mysql --host mysql --user dev --password=dev --database dev --execute "SELECT * FROM wp_posts WHERE post_type='product' LIMIT 10;"
```

### API Testing
```bash
# Test REST API endpoints
curl "http://caddy/wp-json/shopmanagerpro/v1/products/get"
```

## Coding Standards

### PHP Requirements
- **PHP Version**: 8.1+ required
- **Type Hints**: Always use parameter type hints
- **Return Types**: Do NOT use explicit return types (auto-inferred)
- **PHPDoc**: Use for arrays and complex types
  ```php
  /**
   * @param array<int, string> $items
   * @return array{id: int, name: string}
   */
  public function process(array $items) {
      // Return type auto-inferred, no explicit `: array` needed
  }
  ```

### Error Handling
- Always log errors using `\ShopManagerPro\Util\Logger`
- Never silently ignore exceptions
- Use WordPress error objects (`WP_Error`) for REST API responses

### Code Style
- Tabs for indentation (not spaces)
- Opening braces on same line as declaration
- Symfony coding standards (enforced by PHP CS Fixer)
- Yoda conditions disabled (`if ($var === 'value')` not `if ('value' === $var)`)

## Key Classes and Patterns

### InitService
Central initialization point (`includes/Shared/InitService.php`):
- Loads vendor autoloader
- Runs database migrations
- Initializes all API classes
- Registers admin scripts
- Handles commercial vs free version logic

### Constants
Defined in main plugin file:
- `SHOP_MANAGER_PRO_PLUGIN_DIR`: Plugin directory path
- `SHOP_MANAGER_PRO_PLUGIN_URL`: Plugin URL
- `SHOP_MANAGER_PRO_VERSION`: Current version
- `SHOP_MANAGER_PRO_COMMERCIAL`: Whether premium version

### Background Jobs
Uses WordPress Action Scheduler:
- Job creation: `Jobs\JobRepository`
- Processing: `Jobs\JobProcessorService`
- Monitoring: `Jobs\JobAPI`

### Product Updates
Complex update logic in `Products\ProductUpdateService`:
- Handles bulk operations
- Validates changes
- Logs modifications
- Triggers WooCommerce hooks

## Premium Features

Located in `includes/Premium/` (only in commercial version):
- Custom fields discovery and management
- CSV export functionality
- License validation
- Database management tools
- Advanced filtering

## Testing

### Test Structure
```
plugin-tests/
├── bootstrap.php      # WordPress test bootstrap
├── fixtures/          # Shared test data
├── integration/       # Integration tests
└── unit/             # Unit tests
```

### Writing Tests
- Extend `WP_UnitTestCase` for WordPress integration
- Use fixtures for consistent test data
- Mock external dependencies
- Test both success and failure cases

## Common Tasks

### Adding a New REST Endpoint
1. Create or update the appropriate API class
2. Define the schema as a static property
3. Register the route in `registerRoutes()`
4. Implement the endpoint callback
5. Add permission checks
6. Update frontend OpenAPI client if needed

### Adding a New DTO
1. Define the schema in the relevant API class
2. Generate the DTO (if using schema2class)
3. Create wrapper class if needed
4. Use in repository/service methods

### Modifying Database Schema
1. Update `DatabaseManagerService::runMigrations()`
2. Use `dbDelta()` for schema changes
3. Handle data migration if needed
4. Test on fresh and existing installations

## Debugging Tips

### Logging
```php
\ShopManagerPro\Shared\Utils\Logger::error('Operation failed', [
    'context' => $data,
    'error' => $exception->getMessage()
]);
```

### Database Queries
```php
global $wpdb;
$wpdb->show_errors();
$results = $wpdb->get_results($query);
error_log('Last query: ' . $wpdb->last_query);
```

### REST API Responses
Check responses in browser dev tools or:
```bash
curl -v "http://caddy/wp-json/shopmanagerpro/v1/products/get"
```

## Important Notes

- **Generated Files**: Never edit files in `DTO/Generated/` directories
- **Frontend Assets**: Don't edit files in `assets/` - they're compiled from frontend
- **Translations**: Use `__()` and `_e()` with 'shopmanagerpro' text domain
- **Hooks**: Respect WooCommerce action/filter priorities
- **Performance**: Use pagination for large datasets
- **Security**: Always validate and sanitize user input