<?php
/**
 * Template Builder Module
 * Handles the template builder interface for users
 */

// Check if _ISVALID is already defined (it should be by parser.php)
if (!defined('_ISVALID')) {
    define('_ISVALID', true);
}

$main_dir = realpath(dirname(__FILE__) . '/../../../');
set_include_path($main_dir);

require_once 'f_core/config.core.php';

// Verify user is logged in - this will redirect to signin if not
VLogin::checkFrontend('builder');

// Get user ID from session
$_user_id = isset($_SESSION['USER_ID']) ? (int)$_SESSION['USER_ID'] : 0;

// Load configuration
$cfg_builder = $class_database->getConfigurations('template_builder_enabled,template_builder_max_templates,template_builder_mode');

// Check if template builder is enabled
if (!isset($cfg_builder['template_builder_enabled']) || $cfg_builder['template_builder_enabled'] != 1) {
    header('Location: ' . $cfg['main_url'] . '/error?code=feature_disabled');
    exit;
}

// Load language files
include_once $class_language->setLanguageFile('frontend', 'language.builder');

// Initialize template builder
require_once 'f_core/f_classes/class.templatebuilder.php';
$templateBuilder = new VTemplateBuilder();

// Get user's templates
$user_templates = $templateBuilder->getUserTemplates([
    'user_id' => $_user_id,
    'limit' => 100
]);

// Get available components
$available_components = $templateBuilder->getComponents();

// Get user preferences
$user_prefs = $templateBuilder->getUserPreferences($_user_id);

// Assign to Smarty template
$smarty->assign('template_list', $user_templates);
$smarty->assign('available_components', $available_components);
$smarty->assign('user_preferences', $user_prefs);
$smarty->assign('builder_enabled', true);
$smarty->assign('max_templates', $cfg_builder['template_builder_max_templates'] ?? 10);
$smarty->assign('builder_mode', $cfg_builder['template_builder_mode'] ?? 'simple');

// Load template editor if template ID provided
if (isset($_GET['template_id'])) {
    $template_id = (int)$_GET['template_id'];
    $template = $templateBuilder->getTemplate($template_id);

    if ($template) {
        $smarty->assign('current_template', $template);
        $smarty->assign('template_id', $template_id);
    }
}

// Display the builder interface using the proper method
$class_smarty->displayPage('frontend', 'tpl_builder');
?>
