<?php ob_start();
/**
 * Admin View: Contact Form Builder + Submissions
 *
 * Tabs: builder | submissions
 */
$currentTab     = $tab ?? 'builder';
$cfFields       = $fields ?? [];
$cfEnabled      = $enabled ?? true;
$cfSaveToDb     = $saveToDb ?? true;
$cfPaginated    = $paginated ?? ['items' => [], 'total' => 0, 'page' => 1, 'pages' => 1, 'perPage' => 20];
$cfUnread       = $unread ?? 0;
$csrfToken      = csrf_token();
?>

<div class="content-header">
    <div class="content-header-left">
        <h1><?= __('admin.contact_form.title') ?></h1>
        <p class="content-subtitle"><?= __('admin.contact_form.drag_hint') ?></p>
    </div>
    <?php if ($currentTab === 'submissions' && !empty($cfPaginated['total'])): ?>
    <div class="content-header-actions">
        <a href="/admin/contact-form/export" class="btn btn-secondary btn-sm">
            <?= icon('download', 16) ?> <?= __('admin.contact_form.export_csv') ?>
        </a>
    </div>
    <?php endif; ?>
</div>

<!-- ── Tabs ────────────────────────────────────────────────────────────── -->
<div class="tabs-nav">
    <a href="/admin/contact-form?tab=builder"
       class="tab-item <?= $currentTab === 'builder' ? 'active' : '' ?>">
        <?= icon('layout-list', 16) ?> <?= __('admin.contact_form.builder_tab') ?>
    </a>
    <a href="/admin/contact-form?tab=submissions"
       class="tab-item <?= $currentTab === 'submissions' ? 'active' : '' ?>">
        <?= icon('inbox', 16) ?> <?= __('admin.contact_form.submissions_tab') ?>
        <?php if ($cfUnread > 0): ?>
        <span class="nav-badge nav-badge--info"><?= $cfUnread ?></span>
        <?php endif; ?>
    </a>
</div>

<!-- ══════════════════════════════════════════════════════════════════════
     TAB: BUILDER
     ══════════════════════════════════════════════════════════════════════ -->
<?php if ($currentTab === 'builder'): ?>

<form id="cfBuilderForm" method="POST" action="/admin/contact-form/save">
    <?= csrf_field() ?>
    <input type="hidden" name="fields" id="cfFieldsJson" value="<?= e(json_encode($cfFields, JSON_UNESCAPED_UNICODE)) ?>">

    <div class="cf-builder-layout">

        <!-- ── Left: Field list + Settings ── -->
        <div class="cf-builder-main">

            <!-- Settings card -->
            <div class="card" style="margin-bottom:1.25rem;">
                <div class="card-header">
                    <h3 class="card-title"><?= icon('settings', 16) ?> Einstellungen</h3>
                </div>
                <div class="card-body">
                    <div class="form-row-2">
                        <label class="toggle-label">
                            <input type="checkbox" name="enabled" value="1" id="cfEnabled"
                                <?= $cfEnabled ? 'checked' : '' ?>>
                            <span class="toggle-slider"></span>
                            <span class="toggle-text"><?= __('admin.contact_form.enabled_label') ?></span>
                        </label>
                        <label class="toggle-label">
                            <input type="checkbox" name="save_to_db" value="1" id="cfSaveToDb"
                                <?= $cfSaveToDb ? 'checked' : '' ?>>
                            <span class="toggle-slider"></span>
                            <span class="toggle-text"><?= __('admin.contact_form.save_to_db_label') ?></span>
                        </label>
                    </div>
                </div>
            </div>

            <!-- Field list -->
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><?= icon('layout-list', 16) ?> <?= __('admin.contact_form.builder_tab') ?></h3>
                    <span class="card-subtitle"><?= __('admin.contact_form.drag_hint') ?></span>
                </div>
                <div class="card-body" id="cfFieldList" style="min-height:120px;">
                    <?php if (empty($cfFields)): ?>
                    <p class="text-muted" id="cfNoFieldsHint"><?= __('admin.contact_form.no_fields') ?></p>
                    <?php else: ?>
                    <p class="text-muted" id="cfNoFieldsHint" style="display:none"><?= __('admin.contact_form.no_fields') ?></p>
                    <?php endif; ?>

                    <?php foreach ($cfFields as $field): ?>
                    <div class="cf-field-row" data-field-id="<?= e($field['id']) ?>">
                        <div class="cf-field-drag-handle" title="<?= __('admin.contact_form.drag_hint') ?>">
                            <?= icon('grip-vertical', 16) ?>
                        </div>
                        <div class="cf-field-info">
                            <span class="cf-field-label"><?= e($field['label']) ?></span>
                            <span class="cf-field-meta">
                                <?= e(__('admin.contact_form.field_types.' . ($field['type'] ?? 'text')) ?: $field['type'] ?? 'text') ?>
                                · <?= ($field['width'] ?? 'full') === 'half' ? __('admin.contact_form.field_width_half') : __('admin.contact_form.field_width_full') ?>
                                <?= !empty($field['required']) ? ' · <span class="badge badge-required">Pflicht</span>' : '' ?>
                            </span>
                        </div>
                        <div class="cf-field-actions">
                            <button type="button" class="btn btn-ghost btn-sm cf-edit-btn"
                                    data-field='<?= e(json_encode($field, JSON_UNESCAPED_UNICODE)) ?>'
                                    title="<?= __('admin.common.edit') ?>">
                                <?= icon('pencil', 15) ?>
                            </button>
                            <button type="button" class="btn btn-ghost btn-sm cf-delete-btn"
                                    data-confirm="<?= e(__('admin.contact_form.delete_field_confirm')) ?>"
                                    title="<?= __('admin.common.delete') ?>">
                                <?= icon('trash-2', 15) ?>
                            </button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <?= icon('save', 16) ?> <?= __('admin.contact_form.save_config') ?>
                    </button>
                </div>
            </div>

        </div><!-- /.cf-builder-main -->

        <!-- ── Right: Add Field Panel ── -->
        <div class="cf-builder-sidebar">
            <div class="card cf-add-field-card" id="cfAddFieldPanel">
                <div class="card-header">
                    <h3 class="card-title"><?= icon('plus-circle', 16) ?> <?= __('admin.contact_form.add_field') ?></h3>
                </div>
                <div class="card-body">

                    <div class="form-group">
                        <label for="cfNewType"><?= __('admin.contact_form.field_type') ?></label>
                        <select id="cfNewType" class="form-control">
                            <?php foreach (['text','email','tel','textarea','select','checkbox','hidden'] as $type): ?>
                            <option value="<?= $type ?>"><?= e(__('admin.contact_form.field_types.' . $type)) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="cfNewLabel"><?= __('admin.contact_form.field_label') ?></label>
                        <input type="text" id="cfNewLabel" class="form-control" placeholder="z. B. Nachricht">
                    </div>

                    <div class="form-group">
                        <label for="cfNewPlaceholder"><?= __('admin.contact_form.field_placeholder') ?></label>
                        <input type="text" id="cfNewPlaceholder" class="form-control">
                    </div>

                    <div class="form-group cf-options-group" style="display:none">
                        <label for="cfNewOptions"><?= __('admin.contact_form.field_options') ?></label>
                        <input type="text" id="cfNewOptions" class="form-control" placeholder="Option 1, Option 2, Option 3">
                    </div>

                    <div class="form-group cf-value-group" style="display:none">
                        <label for="cfNewValue"><?= __('admin.contact_form.field_value') ?></label>
                        <input type="text" id="cfNewValue" class="form-control">
                    </div>

                    <div class="form-row-2" style="gap:.75rem;">
                        <div class="form-group">
                            <label for="cfNewWidth"><?= __('admin.contact_form.field_width') ?></label>
                            <select id="cfNewWidth" class="form-control">
                                <option value="full"><?= __('admin.contact_form.field_width_full') ?></option>
                                <option value="half"><?= __('admin.contact_form.field_width_half') ?></option>
                            </select>
                        </div>
                        <div class="form-group" style="display:flex;align-items:flex-end;padding-bottom:.25rem;">
                            <label class="toggle-label">
                                <input type="checkbox" id="cfNewRequired" value="1">
                                <span class="toggle-slider"></span>
                                <span class="toggle-text"><?= __('admin.contact_form.field_required') ?></span>
                            </label>
                        </div>
                    </div>

                    <button type="button" id="cfAddFieldBtn" class="btn btn-primary" style="width:100%;">
                        <?= icon('plus', 16) ?> <?= __('admin.contact_form.add_field') ?>
                    </button>
                </div>
            </div>
        </div><!-- /.cf-builder-sidebar -->

    </div><!-- /.cf-builder-layout -->
</form>

<!-- Edit Field Modal -->
<div id="cfEditModal" class="modal-overlay" style="display:none;" aria-hidden="true">
    <div class="modal modal-sm">
        <div class="modal-header">
            <h3><?= __('admin.common.edit') ?></h3>
            <button type="button" class="modal-close" id="cfEditModalClose">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="cfEditFieldId">
            <div class="form-group">
                <label><?= __('admin.contact_form.field_type') ?></label>
                <select id="cfEditType" class="form-control">
                    <?php foreach (['text','email','tel','textarea','select','checkbox','hidden'] as $type): ?>
                    <option value="<?= $type ?>"><?= e(__('admin.contact_form.field_types.' . $type)) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label><?= __('admin.contact_form.field_label') ?></label>
                <input type="text" id="cfEditLabel" class="form-control">
            </div>
            <div class="form-group">
                <label><?= __('admin.contact_form.field_placeholder') ?></label>
                <input type="text" id="cfEditPlaceholder" class="form-control">
            </div>
            <div class="form-group cf-edit-options-group" style="display:none">
                <label><?= __('admin.contact_form.field_options') ?></label>
                <input type="text" id="cfEditOptions" class="form-control">
            </div>
            <div class="form-group cf-edit-value-group" style="display:none">
                <label><?= __('admin.contact_form.field_value') ?></label>
                <input type="text" id="cfEditValue" class="form-control">
            </div>
            <div class="form-row-2" style="gap:.75rem;">
                <div class="form-group">
                    <label><?= __('admin.contact_form.field_width') ?></label>
                    <select id="cfEditWidth" class="form-control">
                        <option value="full"><?= __('admin.contact_form.field_width_full') ?></option>
                        <option value="half"><?= __('admin.contact_form.field_width_half') ?></option>
                    </select>
                </div>
                <div class="form-group" style="display:flex;align-items:flex-end;padding-bottom:.25rem;">
                    <label class="toggle-label">
                        <input type="checkbox" id="cfEditRequired" value="1">
                        <span class="toggle-slider"></span>
                        <span class="toggle-text"><?= __('admin.contact_form.field_required') ?></span>
                    </label>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" id="cfEditSaveBtn" class="btn btn-primary">
                <?= icon('check', 16) ?> <?= __('admin.common.save') ?>
            </button>
            <button type="button" id="cfEditCancelBtn" class="btn btn-secondary">
                <?= __('admin.common.cancel') ?>
            </button>
        </div>
    </div>
</div>

<?php endif; // builder tab ?>


<!-- ══════════════════════════════════════════════════════════════════════
     TAB: SUBMISSIONS
     ══════════════════════════════════════════════════════════════════════ -->
<?php if ($currentTab === 'submissions'): ?>

<?php $items = $cfPaginated['items']; ?>

<?php if (empty($items)): ?>
<div class="empty-state">
    <?= icon('inbox', 48) ?>
    <p><?= __('admin.contact_form.no_submissions') ?></p>
</div>
<?php else: ?>

<form id="cfBulkForm" method="POST" action="/admin/contact-form/bulk">
    <?= csrf_field() ?>

    <!-- Bulk actions bar -->
    <div class="bulk-actions-bar" id="bulkActionsBar" style="display:none">
        <span class="bulk-count" id="bulkCount">0 ausgewählt</span>
        <div class="bulk-actions-buttons">
            <button type="submit" name="bulk_action" value="mark_read" class="btn btn-secondary btn-sm">
                <?= icon('check-circle', 15) ?> <?= __('admin.contact_form.mark_read') ?>
            </button>
            <button type="submit" name="bulk_action" value="delete" class="btn btn-danger btn-sm"
                    data-confirm="<?= e(__('admin.common.bulk_confirm_delete', ['count' => '…'])) ?>">
                <?= icon('trash-2', 15) ?> <?= __('admin.common.delete') ?>
            </button>
        </div>
    </div>

    <div class="card">
        <div class="card-body p-0">
            <table class="data-table">
                <thead>
                    <tr>
                        <th class="col-checkbox">
                            <input type="checkbox" id="selectAll" class="bulk-select-all">
                        </th>
                        <th>Datum</th>
                        <th>Absender</th>
                        <th><?= __('admin.contact_form.ip') ?></th>
                        <th><?= __('admin.common.status') ?></th>
                        <th class="col-actions"><?= __('admin.common.actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $sub):
                        $preview = json_decode($sub['form_data_preview'] ?? '[]', true) ?: [];
                        // Find first email field for display
                        $senderEmail = '';
                        $senderName  = '';
                        foreach ($preview as $entry) {
                            if (($entry['type'] ?? '') === 'email' && $senderEmail === '') {
                                $senderEmail = $entry['value'] ?? '';
                            }
                            if (in_array($entry['type'] ?? '', ['text'], true) && $senderName === '') {
                                $senderName = $entry['value'] ?? '';
                            }
                        }
                        $display = $senderEmail ?: ($senderName ?: '—');
                    ?>
                    <tr class="<?= !$sub['is_read'] ? 'row-unread' : '' ?>">
                        <td class="col-checkbox">
                            <input type="checkbox" name="selected[]" value="<?= $sub['id'] ?>" class="bulk-checkbox">
                        </td>
                        <td>
                            <span class="text-muted text-sm"><?= date('d.m.Y H:i', strtotime($sub['created_at'])) ?></span>
                        </td>
                        <td>
                            <?php if (!$sub['is_read']): ?>
                            <span class="badge badge-info" style="margin-right:.375rem;">Neu</span>
                            <?php endif; ?>
                            <?= e($display) ?>
                        </td>
                        <td><span class="text-muted text-sm"><?= e($sub['ip_address'] ?? '—') ?></span></td>
                        <td>
                            <?php if ($sub['is_read']): ?>
                            <span class="status-badge status-published"><?= __('admin.contact_form.status_read') ?></span>
                            <?php else: ?>
                            <span class="status-badge status-draft"><?= __('admin.contact_form.status_unread') ?></span>
                            <?php endif; ?>
                        </td>
                        <td class="col-actions">
                            <a href="/admin/contact-form/submission/<?= $sub['id'] ?>" class="btn btn-ghost btn-sm">
                                <?= icon('eye', 15) ?> <?= __('admin.common.view') ?>
                            </a>
                            <form method="POST" action="/admin/contact-form/submission/<?= $sub['id'] ?>/delete"
                                  style="display:inline">
                                <?= csrf_field() ?>
                                <button type="submit" class="btn btn-ghost btn-sm text-danger"
                                        data-confirm="<?= e(__('admin.contact_form.confirm_delete')) ?>">
                                    <?= icon('trash-2', 15) ?>
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

</form>

<!-- Pagination -->
<?php if ($cfPaginated['pages'] > 1): ?>
<div class="pagination">
    <?php for ($p = 1; $p <= $cfPaginated['pages']; $p++): ?>
    <a href="/admin/contact-form?tab=submissions&page=<?= $p ?>"
       class="page-btn <?= $p === $cfPaginated['page'] ? 'active' : '' ?>"><?= $p ?></a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<?php endif; // empty ?>
<?php endif; // submissions tab ?>

<script src="/admin/assets/js/contact-form-builder.js?v=<?= cms_version() ?>-<?= @filemtime($_SERVER['DOCUMENT_ROOT'].'/admin/assets/js/contact-form-builder.js') ?: '1' ?>" defer></script>
<?php $content = ob_get_clean(); include dirname(__DIR__) . '/layouts/admin.php'; ?>
