# Builder

Provides custom blocks to design page/post layouts for Laravel applications.

## Features

- **764+ Pre-Built Blocks** - Components, designs, and layouts organized into 35 categories
- **Visual Page Builder** - Drag-and-drop interface powered by ContentBuilder JS
- **File-Based Storage** - No database required; blocks stored as Blade templates
- **Override System** - Customize vendor blocks without modifying package files
- **Admin Interface** - Full CRUD management for all block types
- **JSON API** - 21 API endpoints for frontend integration
- **Shortcode Support** - Dynamic content insertion via `[component key="..."]`
- **Icon Library** - 2,050 FontAwesome icons (regular, solid, brand)
- **Rich Integrations** - Works with bongo/post, bongo/image, bongo/gallery, bongo/menu, bongo/form

## Requirements

- PHP 8.2 or higher
- Laravel 10 or higher
- Composer

## Installation

### Via Composer

```bash
composer require bongo/builder
```

### Configuration

The package uses Laravel's auto-discovery feature, so the service provider is automatically registered.

Optionally, publish the configuration file:

```bash
php artisan vendor:publish --provider="Bongo\Builder\BuilderServiceProvider" --tag="config"
```

### Publishing Assets

Publish the frontend assets to your application's public directory:

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

## Quick Start

### Retrieving Blocks

```php
use Bongo\Builder\Facades\ComponentFacade as Component;
use Bongo\Builder\Facades\DesignFacade as Design;
use Bongo\Builder\Facades\LayoutFacade as Layout;

// Get all components
$components = Component::all();

// Find a specific component
$header = Component::find('header-02');

// Get components by category
$headlines = Component::findByCategory('headline');

// Get designs
$designs = Design::all();

// Get layouts
$layouts = Layout::all();
```

### Using Facades (Global Aliases)

The package registers global aliases for convenient access:

```php
// Using global aliases (no imports needed)
$components = Component::all();
$designs = Design::all();
$layouts = Layout::all();
```

### Creating Custom Blocks

```php
use Bongo\Builder\Models\BuilderItem;

$component = new BuilderItem('component');
$component->setName('my-custom-block');
$component->setCategory('headline');
$component->setHtml('<div class="custom-block"><h1>My Block</h1></div>');
$component->setThumbnail(file_get_contents($imagePath));
$component->save();
```

### Using Shortcodes

Include blocks dynamically in your templates:

```blade
<div class="page-content">
    [component key="header-02"]

    <p>Your content here</p>

    [design key="cta-01"]
</div>
```

Ensure the `hasShortCodes` middleware is applied to your routes.

## Block Types

### Components

Small, reusable UI elements organized into 16 categories:

- Achievements
- Basic
- Buttons
- Contact
- Custom
- Features
- Headline
- Help, FAQ
- Photos
- Pricing
- Process
- Products
- Profile
- Quotes
- Services
- Skills

### Designs

Full page sections organized into 16 categories:

- Achievements
- Banners
- Basic
- CTAs
- Contact
- Features
- Headline
- Help, FAQ
- Photos
- Pricing
- Process
- Products
- Profile
- Quotes
- Services
- Skills

### Layouts

Structural elements organized into 3 categories:

- Headers
- Headings
- Footers

## API Endpoints

### Authenticated Endpoints (require auth:sanctum)

```
GET /api/builder              - All components
GET /api/builder/buttons      - Button styles
GET /api/builder/designs      - All designs
GET /api/builder/snippets     - Code snippets
GET /api/builder/files        - File manager
GET /api/builder/fonts        - Web fonts
GET /api/builder/images       - Image library
GET /api/builder/icons        - Icon library (2,050 icons)
GET /api/builder/symbols      - Special symbols
GET /api/builder/styles       - CSS styles
GET /api/builder/modules/{module} - Dynamic modules
```

### Public Endpoints (no authentication)

```
GET /api/builder/post             - Blog post listings
GET /api/builder/project          - Project listings
GET /api/builder/review           - Review listings
GET /api/builder/review-summary   - Review summaries
GET /api/builder/form-builder     - Form builder
GET /api/builder/menu-builder     - Menu builder
GET /api/builder/gallery-builder  - Gallery builder
GET /api/builder/carousels/{carousel} - Carousel content
GET /api/builder/sliders/{slider} - Slider content
GET /api/builder/validation       - Validation rules
```

## Admin Routes

Access the admin interface at:

- `/admin/components` - Manage components
- `/admin/sections` - Manage designs (sections)
- `/admin/layouts` - Manage layouts
- `/admin/icons` - View icon library

**Note**: Requires authentication and employee middleware.

## File Structure

Each block is stored as a directory containing:

```
{type}/{category}/{name}/
    ├── index.blade.php    # The template
    └── preview.png        # Thumbnail image
```

### Storage Locations

**Vendor Path** (original templates):
```
vendor/bongo/builder/src/Views/frontend/
    ├── component/
    ├── design/
    └── layout/
```

**Resource Path** (customizations):
```
resources/views/vendor/builder/frontend/
    ├── component/
    ├── design/
    └── layout/
```

Customizations automatically override vendor versions.

## Frontend Assets

### Development

```bash
# Install dependencies
npm install

# Development build
npm run dev

# Watch for changes
npm run watch

# Production build
npm run production
```

### Compiled Assets

- **Backend Editor**: `public/backend/editor.css`, `public/backend/editor.js`
- **Frontend**: `public/frontend/box.css`, `public/frontend/box.js`

## Configuration

Key configuration options in `config/builder.php`:

```php
// Route prefixes
'component_prefix' => 'components',  // /admin/components
'design_prefix' => 'sections',       // /admin/sections
'layout_prefix' => 'layouts',        // /admin/layouts

// Storage paths
'vendor_path' => 'vendor/bongo/builder/src/Views/',
'resource_path' => 'resources/views/vendor/builder/',

// Asset paths
'backend_asset_path' => '/backend',
'frontend_asset_path' => '/frontend',
```

## Environment Variables

Optionally override asset paths:

```bash
VENDOR_ASSET_PATH=/vendor
BACKEND_ASSET_PATH=/backend
FRONTEND_ASSET_PATH=/frontend

BACKEND_CSS_FILE=editor.css
BACKEND_JS_FILE=editor.js
FRONTEND_CSS_FILE=box.css
FRONTEND_JS_FILE=box.js
```

## Testing

```bash
# Run tests
vendor/bin/phpunit

# Fix code style
vendor/bin/pint

# Check code style
vendor/bin/pint --test
```

## Integration with Other Packages

The builder integrates seamlessly with:

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

## Documentation

- [ARCHITECTURE.md](./ARCHITECTURE.md) - Detailed architecture documentation with class diagrams and data flow
- [CLAUDE.md](./CLAUDE.md) - Claude Code AI guidance
- [.cursorrules](./.cursorrules) - Cursor IDE rules
- [.github/copilot-instructions.md](./.github/copilot-instructions.md) - GitHub Copilot instructions

## Key Features Explained

### File-Based Storage

Blocks are stored as files, not in a database. This provides:
- Version control friendly
- Easy backup and migration
- Fast retrieval with caching
- No database queries needed

### Vendor/Resource Override Pattern

- Vendor blocks are never modified
- Customizations stored in `resources/views/vendor/builder/`
- Resource versions automatically override vendor versions
- Delete operation reverts to vendor version

### Polymorphic Model

Single `BuilderItem` model handles three types:
- `component` - Small UI elements
- `design` - Full page sections
- `layout` - Structural elements (headers/footers)

### Automatic Caching

- File lists cached for 10 minutes
- Cache automatically cleared on save/delete
- Dramatically improves performance with 764+ blocks

### ContentBuilder JS Integration

Powerful WYSIWYG editor featuring:
- Drag-and-drop interface
- Component palette
- Responsive design tools
- 2,050 FontAwesome icons
- Image/file management
- Custom CSS editing

## Common Patterns

### Get All Items by Category

```php
$items = Component::allByCategory();

// Returns array structure:
// [
//   'headline' => [
//     'header-01' => BuilderItem,
//     'header-02' => BuilderItem,
//   ],
//   'buttons' => [...],
// ]
```

### Get Items as JSON

```php
$json = Component::allAsJson();

// Returns:
// [
//   {
//     "name": "header-02",
//     "category": "headline",
//     "html": "<div>...</div>",
//     "thumbnail": "data:image/png;base64,..."
//   },
//   ...
// ]
```

### Get Categories

```php
$categories = Component::categories();

// Returns:
// [
//   'headline' => 'Headline',
//   'buttons' => 'Buttons',
//   ...
// ]
```

### Render Block HTML

```php
$component = Component::find('header-02');
echo $component->getHtml();  // Rendered Blade template
```

## Performance Tips

1. **Caching is automatic** - 10-minute TTL
2. **Keep thumbnails small** - Recommended ~1-2KB PNG
3. **Use production builds** - `npm run production` for optimized assets
4. **Limit blocks per category** - < 100 for best performance

## Security

- API routes require authentication (`auth:sanctum`)
- Backend routes require authentication + employee middleware
- Custom routes are public (use with caution)
- Blade templates auto-escape output
- User input is validated in controllers
- File operations restricted to resource path

## Troubleshooting

### Blocks Not Appearing

```bash
# Clear cache
php artisan cache:clear

# Or programmatically
Cache::forget('component_files');
```

### Routes Not Working

```bash
# Clear route cache
php artisan route:clear

# Verify middleware in route files
```

### Assets Not Compiling

```bash
# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install

# Try verbose build
npm run dev -- --verbose
```

## Contributing

This package is part of the Bongo CMS ecosystem. For bugs, feature requests, or contributions, please contact the development team.

## License

This package is proprietary software licensed under the MIT License.

## Credits

- **Author**: Stuart Elliott (stuart.elliott@bespokeuk.com)
- **Company**: Bespoke UK (https://bespokeuk.com)
- **Homepage**: https://bitbucket.org/designtec/builder

## Support

For support, please contact the development team or consult the documentation files:
- [ARCHITECTURE.md](./ARCHITECTURE.md)
- [CLAUDE.md](./CLAUDE.md)
