# Builder Package - Cursor Rules

## Overview

This is the **bongo/builder** package - a Laravel-based visual page builder providing 764+ pre-built HTML/CSS blocks (components, designs, and layouts) for creating page/post layouts. It integrates with the ContentBuilder JS library for drag-and-drop WYSIWYG editing.

## Project Structure

```
src/
├── Config/builder.php           # Paths, categories, icons configuration
├── Models/BuilderItem.php       # File-based polymorphic model (component/design/layout)
├── Facades/                     # Component, Design, Layout facades
├── Http/
│   ├── Controllers/
│   │   ├── Api/                 # 21 API controllers for JSON/HTML endpoints
│   │   └── Backend/             # 4 admin CRUD controllers
│   └── Middleware/
│       └── HasShortCodes.php    # Processes shortcodes in responses
├── Routes/
│   ├── api.php                  # Authenticated API routes
│   ├── backend.php              # Admin routes
│   └── custom.php               # Public API routes (no auth)
├── Views/
│   ├── frontend/                # 764+ block templates
│   │   ├── component/           # Small UI elements (18 categories)
│   │   ├── design/              # Page sections (14 categories)
│   │   └── layout/              # Headers/footers (3 categories)
│   ├── backend/                 # Admin UI views
│   └── api/                     # API response templates
├── Exceptions/                  # ComponentException, DesignException
├── Seeders/                     # JSON-based data seeders
└── Translations/en/             # Backend translations

resources/
├── backend/                     # Backend editor assets
│   ├── js/contentbuilder/       # ContentBuilder JS library
│   └── sass/
└── frontend/                    # Frontend styles and interactions
    ├── js/
    └── sass/

public/                          # Compiled assets
├── backend/
└── frontend/
```

## Architecture Patterns

### File-Based Storage Pattern

BuilderItem uses a **vendor/resource override architecture**:

- **Vendor path**: `vendor/bongo/builder/src/Views/frontend/{type}/` - Original templates
- **Resource path**: `resources/views/vendor/builder/{type}/` - User customizations
- Customized versions automatically override vendor versions
- Each item is a directory with `index.blade.php` and `preview.png`

### Polymorphic Type Pattern

BuilderItem handles three types via singleton pattern:

```php
// Three types, one model
new BuilderItem('component')  // Small UI elements
new BuilderItem('design')     // Full page sections
new BuilderItem('layout')     // Structural elements (headers/footers)

// Registered as singletons with facades
Component::all()
Design::findByCategory('banners')
Layout::find('header-02')
```

### Automatic Bootstrapping

Extends `AbstractServiceProvider` which auto-registers:
- Config from `src/Config/builder.php`
- Routes from `src/Routes/{api,backend,custom}.php`
- Views from `src/Views/builder/`
- Middleware: `hasShortCodes` for shortcode processing

## Coding Conventions

### Naming

- **Classes**: PascalCase (BuilderItem, ComponentController)
- **Methods**: camelCase (findByCategory, allAsJson)
- **Properties**: camelCase ($absolutePath, $category)
- **Routes**: kebab-case (component.index, design.create)
- **Views**: kebab-case folders (component/headline/header-02/)
- **Config keys**: snake_case (component_path, backend_css_file)

### Method Return Types

Always declare return types:

```php
public function all(): Collection
public function categories(): array
public function allAsJson(): false|string
public function find(string $key): mixed
public function save(): void
```

### Exceptions

- Use `log_exception($e)` helper for logging
- Throw `ComponentException` or `DesignException` for specific errors
- Use `abort('404')` for missing items in `findOrFail()`

### Path Handling

Always use `DIRECTORY_SEPARATOR` constant:

```php
$this->relativePath = $value . DIRECTORY_SEPARATOR;
$path = $category . DIRECTORY_SEPARATOR . $name;
```

### Caching

BuilderItem caches file lists for 10 minutes:

```php
Cache::remember($this->type . '_files', 600, function () {
    // Expensive file system operations
});

// Clear on mutations
Cache::forget($this->type . '_files');
```

## Common Tasks

### Creating a New Block

```php
$component = new BuilderItem('component');
$component->setName('my-new-block');
$component->setKey('my-new-block');
$component->setCategory('headline');
$component->setHtml('<div>Block HTML</div>');
$component->setThumbnail(file_get_contents($imagePath));
$component->save();
```

### Adding a New Category

1. Add to config: `config/builder.php` → `{type}_categories` array
2. Create directory: `src/Views/frontend/{type}/{category-slug}/`
3. Add blocks as `{block-name}/index.blade.php` + `{block-name}/preview.png`

### Adding an API Controller

1. Create controller in `src/Http/Controllers/Api/`
2. Extend `AbstractApiController`
3. Add route to `src/Routes/api.php` (authenticated) or `custom.php` (public)
4. Create optional view template in `src/Views/api/`

### Frontend Asset Compilation

```bash
npm install
npm run dev          # Development build
npm run watch        # Watch for changes
npm run production   # Production build
```

Assets compile to `public/backend/` and `public/frontend/`.

### Publishing Assets

```bash
php artisan vendor:publish --tag=builder:assets --force
```

## Testing

### Running Tests

```bash
vendor/bin/phpunit
```

### Code Style

```bash
vendor/bin/pint         # Fix style issues
vendor/bin/pint --test  # Check style issues
```

### Static Analysis

```bash
vendor/bin/phpstan analyse
```

## Key Files Reference

| File | Purpose |
|------|---------|
| `src/Models/BuilderItem.php` | Core model handling file-based storage for all types |
| `src/BuilderServiceProvider.php` | Service provider with facade registration |
| `src/Config/builder.php` | Paths, categories, icon configuration |
| `src/Http/Middleware/HasShortCodes.php` | Processes shortcodes in responses |
| `src/Routes/api.php` | Authenticated API routes (auth:sanctum) |
| `src/Routes/backend.php` | Admin routes (auth + employee middleware) |
| `src/Routes/custom.php` | Public API routes (no auth) |

## Integration Points

This package integrates with:

- **bongo/framework** - Base service provider, helpers, shortcode processor
- **bongo/image** - Image library for WYSIWYG editor
- **bongo/post** - Blog post listings in templates
- **bongo/gallery** - Gallery builder integration
- **bongo/menu** - Menu builder integration
- **bongo/form** - Form builder integration

## Common Patterns

### Retrieving All Items

```php
Component::all()                    // Collection of all components
Component::allByCategory()          // Array keyed by category
Component::allAsJson()              // JSON for API response
```

### Finding Items

```php
Component::find('header-02')        // Returns item or null
Component::findOrFail('header-02')  // Returns item or 404
Component::findByCategory('headline') // Collection filtered by category
```

### Categories

```php
Component::categories()             // ['slug' => 'Display Name']
Component::categoriesAsJson()       // JSON for API response
```

### File Paths

```php
$item->getBasePath()                // Vendor path (original templates)
$item->getResourcePath()            // Resource path (customizations)
$item->getAllFiles()                // Merged array (resource overrides vendor)
$item->getHtml()                    // Rendered Blade template
$item->getThumbnail()               // Base64-encoded PNG
```

## Environment Variables

```bash
# Asset paths
VENDOR_ASSET_PATH=/vendor
BACKEND_ASSET_PATH=/backend
FRONTEND_ASSET_PATH=/frontend

# Asset filenames
BACKEND_CSS_FILE=editor.css
BACKEND_JS_FILE=editor.js
FRONTEND_CSS_FILE=box.css
FRONTEND_JS_FILE=box.js
```

## Important Notes

- Each block directory must contain `index.blade.php` and `preview.png`
- Preview images should be small (recommended ~1202 bytes)
- Component names and categories are auto-slugified (lowercase, hyphenated)
- Delete operations only remove from resource path (vendor versions remain)
- Cache is automatically cleared on save/delete operations
- Shortcodes in templates: `[component key="header-02"]`
- ContentBuilder JS library is in `resources/backend/js/contentbuilder/`
- FontAwesome icon library: 160 regular + 1,400 solid + 490 brand icons
