<?php
/**
 * ITSWEBER CMS – Page Builder Admin View
 *
 * Hauptansicht des Page Builders. Zeigt alle platzierten Sections
 * mit Drag & Drop (SortableJS), AJAX-Speichern und Section-Verwaltung.
 *
 * @author    Benny Weber (ITSWEBER)
 * @copyright © ITSWEBER – www.itsweber.de
 * @contact   kontakt@itsweber.de
 */

ob_start();

$sectionCount = count($sections);
$context     = $context ?? 'homepage';
$contextMeta = $contextMeta ?? ['title' => __('admin.nav.pagebuilder'), 'backUrl' => '/admin', 'backLabel' => __('admin.nav.dashboard'), 'label' => 'Homepage'];

// Build context-aware URLs for JS
$pbBaseUrl = '/admin/pagebuilder';
if (preg_match('/^page:(\d+)$/', $context, $_m)) {
    $pbBaseUrl = '/admin/pages/' . $_m[1] . '/pagebuilder';
    $previewUrl = '/admin/preview/page/' . $_m[1];
} elseif (preg_match('/^blog:(\d+)$/', $context, $_m)) {
    $pbBaseUrl = '/admin/blog/' . $_m[1] . '/pagebuilder';
    $previewUrl = '/admin/preview/blog/' . $_m[1];
} else {
    $previewUrl = '/';
}
?>

<!-- ── Page Builder CSS ──────────────────────────────────────────────────── -->
<link rel="stylesheet" href="/admin/assets/css/pagebuilder.css?v=<?= cms_version() ?>-<?= @filemtime($_SERVER['DOCUMENT_ROOT'] . '/admin/assets/css/pagebuilder.css') ?: '' ?>">

<!-- ── Header ────────────────────────────────────────────────────────────── -->
<?php if ($context !== 'homepage'): ?>
<div class="content-header-breadcrumb" style="margin-bottom:.5rem;">
    <a href="<?= e($contextMeta['backUrl']) ?>" class="btn btn-secondary btn-sm">
        <?= icon('arrow-left', 14, 'pb-btn-icon') ?>
        <?= e($contextMeta['backLabel']) ?>
    </a>
</div>
<?php endif; ?>

<div class="content-header">
    <div class="content-header-left">
        <div class="content-header-icon"><?= icon('page-builder', 20) ?></div>
        <div class="content-header-title-group">
            <h2><?= e($contextMeta['title']) ?></h2>
            <div class="content-header-subtitle"><?= __('admin.pagebuilder.subtitle') ?></div>
        </div>
    </div>
    <div class="header-actions">
        <a href="<?= e($previewUrl) ?>" target="_blank" rel="noopener" class="btn btn-secondary pb-preview-btn">
            <?= icon('external-link', 16, 'pb-btn-icon') ?>
            <?= __('admin.pagebuilder.preview') ?>
        </a>
        <button type="button"
                class="btn btn-primary pb-add-section-btn"
                data-open-modal="pb-add-section-modal"
                <?= $sectionCount >= $sectionLimit ? 'disabled title="' . e(__('admin.pagebuilder.limit_reached', ['limit' => $sectionLimit])) . '"' : '' ?>>
            <?= icon('plus', 16, 'pb-btn-icon') ?>
            <?= __('admin.pagebuilder.add_section') ?>
        </button>
    </div>
</div>

<!-- ── Section Counter ───────────────────────────────────────────────────── -->
<div class="pb-section-counter" id="pb-section-counter">
    <span class="pb-section-counter-current"><?= (int) $sectionCount ?></span>
    / <?= (int) $sectionLimit ?> <?= __('admin.pagebuilder.sections_used') ?>
</div>

<!-- ── Sections Container ────────────────────────────────────────────────── -->
<div id="pb-sections-container">

    <?php if (empty($sections)): ?>
        <!-- Empty State -->
        <div class="pb-empty-state" id="pb-empty-state">
            <div class="pb-empty-state-icon">
                <svg viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="48" height="48">
                    <rect x="6" y="6" width="36" height="36" rx="4"/>
                    <line x1="6" y1="18" x2="42" y2="18"/>
                    <line x1="6" y1="30" x2="42" y2="30"/>
                    <line x1="18" y1="18" x2="18" y2="30"/>
                </svg>
            </div>
            <h3 class="pb-empty-state-title"><?= __('admin.pagebuilder.empty_title') ?></h3>
            <p class="pb-empty-state-text"><?= __('admin.pagebuilder.empty_text') ?></p>
            <button type="button"
                    class="btn btn-primary pb-add-section-btn"
                    data-open-modal="pb-add-section-modal">
                <svg class="pb-btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">
                    <line x1="12" y1="5" x2="12" y2="19"/>
                    <line x1="5" y1="12" x2="19" y2="12"/>
                </svg>
                <?= __('admin.pagebuilder.add_first_section') ?>
            </button>
        </div>

    <?php else: ?>
        <!-- Sortable Section List -->
        <div class="pb-sections-list" id="pb-sections-list"
             data-reorder-url="/admin/pagebuilder/reorder"
             data-csrf-token="<?= e($csrf->token()) ?>">

            <?php foreach ($sections as $sIdx => $section): ?>
                <?php
                $reg = \App\Sections\SectionRegistry::get($section['section_type']);
                $data = $section['data'] ?? [];
                $expanded = false;
                ?>
                <?php include __DIR__ . '/section-card.php'; ?>
            <?php endforeach; ?>

        </div>
    <?php endif; ?>

</div>

<!-- ── Hidden CSRF field for AJAX requests ────────────────────────────────── -->
<input type="hidden" id="pb-csrf-token" name="_token" value="<?= e($csrf->token()) ?>">

<!-- ── Config data for JS ────────────────────────────────────────────────── -->
<script>
window.pbConfig = {
    context: <?= json_encode($context, JSON_HEX_TAG) ?>,
    sectionLimit: <?= (int) $sectionLimit ?>,
    sectionCount: <?= (int) $sectionCount ?>,
    urls: {
        addSection:  '<?= e($pbBaseUrl) ?>/section/add',
        importSection: '<?= e($pbBaseUrl) ?>/section/import',
        reorder:     '/admin/pagebuilder/reorder',
        sectionBase: '/admin/pagebuilder/section'
    },
    translations: {
        confirmDelete:  <?= json_encode(__('admin.pagebuilder.confirm_delete'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        savingLabel:    <?= json_encode(__('admin.pagebuilder.saving'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        savedLabel:     <?= json_encode(__('admin.pagebuilder.saved'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        errorLabel:     <?= json_encode(__('admin.pagebuilder.error'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        limitReached:   <?= json_encode(__('admin.pagebuilder.limit_reached', ['limit' => $sectionLimit]), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        reorderSuccess: <?= json_encode(__('admin.pagebuilder.reorder_success'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        reorderError:   <?= json_encode(__('admin.pagebuilder.reorder_error'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        networkError:   <?= json_encode(__('admin.pagebuilder.network_error'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        previewTitle:   <?= json_encode(__('admin.pagebuilder.preview_section'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        revisionsTitle: <?= json_encode(__('admin.pagebuilder.revisions'), JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        noRevisions:    <?= json_encode('Noch keine Versionen vorhanden.', JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        restore:        <?= json_encode('Wiederherstellen', JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>,
        confirmRestore: <?= json_encode('Version wiederherstellen? Der aktuelle Inhalt wird als neue Version gespeichert.', JSON_HEX_TAG | JSON_UNESCAPED_UNICODE) ?>
    }
};
</script>

<!-- ── Add Section Modal ─────────────────────────────────────────────────── -->
<?php include __DIR__ . '/add-section-modal.php'; ?>

<!-- ── Page Builder JS ───────────────────────────────────────────────────── -->
<script src="/admin/assets/js/vendor/Sortable.min.js"></script>
<script src="/admin/assets/js/pagebuilder.js?v=<?= cms_version() ?>-<?= @filemtime($_SERVER['DOCUMENT_ROOT'] . '/admin/assets/js/pagebuilder.js') ?: '' ?>"></script>

<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
