# Template Builder - Quick Setup Guide

## 🚀 Quick Start (5 Minutes)

### Step 1: Database Already Set Up! ✅
The template builder tables are **already included** in the main `easystream.sql` file. If you've installed EasyStream, you're ready to go!

If you need to add it to an existing installation:
```bash
mysql -u username -p database_name < __install/add_template_builder.sql
```

### Step 2: Add Navigation Link

Add this link to your user navigation menu (e.g., in `tpl_leftnav/tpl_nav_account.tpl` or your account menu):

```html
<a href="/templates.php">
    <i class="icon-layout"></i> My Templates
</a>
```

Or add directly to account settings:
```html
<li>
    <a href="/f_modules/m_backend/template_manager.php">
        <i class="icon-layout"></i> Template Builder
    </a>
</li>
```

### Step 3: Done! 🎉

Users can now:
1. Click "My Templates" in their account
2. Create new templates with drag-and-drop
3. Customize components
4. Publish and use templates

---

## 📂 Files Created

### Backend (PHP)
- `f_core/f_classes/class.templatebuilder.php` - Core functionality
- `f_modules/m_frontend/templatebuilder_ajax.php` - AJAX API
- `f_modules/m_backend/template_manager.php` - Management interface
- `templates.php` - Entry point

### Frontend (Templates)
- `f_templates/tpl_frontend/tpl_builder/tpl_builder_main.tpl` - Builder UI
- `f_templates/tpl_backend/tpl_template_manager.tpl` - Template list

### Assets (CSS/JS)
- `f_scripts/fe/css/builder/builder.css` - Builder styles
- `f_scripts/fe/js/builder/builder-core.js` - Builder logic

### Database
- `__install/add_template_builder.sql` - Standalone migration
- `__install/easystream.sql` - Includes template builder (updated)

### Documentation
- `TEMPLATE_BUILDER_GUIDE.md` - Complete guide
- `TEMPLATE_BUILDER_SETUP.md` - This file

---

## 🎯 Access URLs

After setup, these URLs are available:

- **Template List**: `/templates.php` or `/f_modules/m_backend/template_manager.php`
- **Create New**: `/f_modules/m_backend/template_manager.php?action=new`
- **Edit Template**: `/f_modules/m_backend/template_manager.php?action=edit&id=123`
- **AJAX API**: `/f_modules/m_frontend/templatebuilder_ajax.php`

---

## 🔧 Troubleshooting

### CSS/JS Not Loading

Check file paths in your config:
```php
$cfg['styles_url'] = '/f_scripts/fe/css';
$cfg['javascript_url'] = '/f_scripts/fe/js';
```

### Database Errors

Make sure tables exist:
```sql
SHOW TABLES LIKE 'db_templatebuilder%';
```

Should show 5 tables:
- `db_templatebuilder_templates`
- `db_templatebuilder_components`
- `db_templatebuilder_assignments`
- `db_templatebuilder_versions`
- `db_templatebuilder_user_prefs`

### Components Not Showing

Check if default components were inserted:
```sql
SELECT COUNT(*) FROM db_templatebuilder_components;
```

Should return `7` (7 default components).

If not, run:
```bash
mysql -u username -p database_name < __install/add_template_builder.sql
```

### Access Denied

Make sure user is logged in:
```php
if (!isset($_SESSION['USER_ID']) || $_SESSION['USER_ID'] <= 0) {
    // User not logged in
}
```

---

## 🎨 Customization

### Add More Components

Insert into database:
```sql
INSERT INTO `db_templatebuilder_components`
(`component_name`, `component_slug`, `component_category`,
 `component_html`, `component_css`, `component_settings_schema`,
 `is_system`, `description`)
VALUES
('My Component', 'my_component', 'custom',
 '<div>{{content}}</div>',
 'div { padding: {{padding}}px; }',
 '{"content": {"type": "text", "default": "Hello"}, "padding": {"type": "number", "default": 20}}',
 1,
 'My custom component');
```

### Customize Styles

Edit `f_scripts/fe/css/builder/builder.css` to match your theme.

### Add to Main Menu

In your main navigation template:
```smarty
{if $smarty.session.USER_ID gt 0}
<li class="nav-item">
    <a href="/templates.php" class="nav-link">
        <i class="icon-layout"></i>
        <span>Templates</span>
    </a>
</li>
{/if}
```

---

## 📊 Database Schema

### Templates Table
Stores user-created templates with JSON structure, settings, and custom CSS/JS.

### Components Table
Library of reusable components with HTML, CSS, and settings schema.

### Assignments Table
Maps templates to specific pages (homepage, channel, browse, etc.).

### Versions Table
Tracks template changes with version numbers and change notes.

### User Preferences Table
Stores per-user builder settings and active templates.

---

## 🔐 Security

The template builder includes:

✅ **Input Validation** - All input sanitized via `VDatabase::sanitizeInput()`
✅ **Ownership Checks** - Users can only edit their own templates
✅ **SQL Injection Protection** - Prepared statements and parameterized queries
✅ **XSS Prevention** - Output escaped in templates
✅ **CSRF Protection** - Inherits from EasyStream's security system
✅ **Authentication** - Requires logged-in user

---

## 🎓 Usage Examples

### Create Template via PHP

```php
$templateBuilder = new VTemplateBuilder();

$result = $templateBuilder->createTemplate([
    'template_name' => 'My Homepage',
    'template_type' => 'homepage',
    'template_structure' => json_encode([
        'sections' => [],
        'max_width' => 1200
    ])
]);

if ($result['success']) {
    echo "Template created with ID: " . $result['template_id'];
}
```

### Render Template

```php
$templateBuilder = new VTemplateBuilder();
$html = $templateBuilder->renderTemplate(123); // By ID
echo $html;

// Or by slug
$html = $templateBuilder->renderTemplate('my-template-slug');
```

### Get User Templates

```php
$templateBuilder = new VTemplateBuilder();
$templates = $templateBuilder->getUserTemplates([
    'template_type' => 'homepage',
    'is_active' => 1
]);

foreach ($templates as $template) {
    echo $template['template_name'];
}
```

---

## 📞 Support

- **Documentation**: See `TEMPLATE_BUILDER_GUIDE.md` for detailed information
- **Issues**: Check browser console and server logs
- **Database**: Use VLogger for debugging queries

---

## ✨ Features

- ✅ Drag-and-drop interface
- ✅ 7 pre-built components
- ✅ Responsive preview (desktop/tablet/mobile)
- ✅ Auto-save (3 seconds)
- ✅ Version history
- ✅ Custom CSS/JS support
- ✅ Component settings
- ✅ Section management
- ✅ Template duplication
- ✅ Dark mode support

---

**Version**: 1.0.0
**Last Updated**: 2025-01-22
**Compatible With**: EasyStream 1.0+
