<?php
/**
 * ITSWEBER CMS – Page Builder Admin Form: Team Section
 * Loaded via AJAX into section cards.
 * Migrated from plugins/team-section.
 *
 * @author  Benny Weber
 * @copyright ITSWEBER, www.itsweber.de
 *
 * @var array $data    Decoded JSON content
 * @var array $section DB row (id, section_type, instance_label, ...)
 */

$esc = fn(string $v): string => htmlspecialchars($v, ENT_QUOTES, 'UTF-8');

$title       = $data['title'] ?? '';
$subtitle    = $data['subtitle'] ?? '';
$columns     = $data['columns'] ?? '3';
$colorScheme = $data['color_scheme'] ?? '';
$cardStyle   = $data['card_style'] ?? '';
$imageStyle  = $data['image_style'] ?? '';
$members     = (isset($data['members']) && is_array($data['members'])) ? $data['members'] : [];

$sectionId   = (int) $section['id'];
$containerId = 'team-members-container-' . $sectionId;
$addBtnId    = 'ts-add-member-' . $sectionId;
?>

<div class="form-group">
    <label class="form-label"><?= __('admin.section.heading') ?></label>
    <input type="text" name="title" class="form-control" value="<?= $esc($title) ?>" placeholder="<?= __('admin.section.team_ph_title') ?>">
</div>

<div class="form-group">
    <label class="form-label"><?= __('admin.section.subtitle') ?></label>
    <input type="text" name="subtitle" class="form-control" value="<?= $esc($subtitle) ?>" placeholder="<?= __('admin.section.team_ph_subtitle') ?>">
</div>

<?php admin_field_grid_open(5) ?>
    <?php admin_field('select', 'columns', __('admin.section.columns'), $columns, [
        'options' => ['2' => __('admin.section.columns_2'), '3' => __('admin.section.columns_3'), '4' => __('admin.section.columns_4')],
        'wrap_style' => 'margin:0;',
    ]) ?>
    <?php admin_color_scheme_field($colorScheme) ?>
    <?php render_section_text_color_field($data) ?>
    <?php admin_field('select', 'card_style', __('admin.section.card_style'), $cardStyle, [
        'options' => ['' => __('admin.section.card_default'), 'bordered' => __('admin.section.card_bordered'), 'flat' => __('admin.section.card_flat')],
        'wrap_style' => 'margin:0;',
    ]) ?>
    <?php admin_field('select', 'image_style', __('admin.section.team_image_style'), $imageStyle, [
        'options' => ['' => __('admin.section.team_opt_circle'), 'rounded' => __('admin.section.team_opt_rounded'), 'square' => __('admin.section.team_opt_square')],
        'hint' => __('admin.section.team_image_hint'), 'wrap_style' => 'margin:0;',
    ]) ?>
<?php admin_field_grid_close() ?>

<!-- Team Members Repeater -->
<div class="form-group">
    <label class="form-label"><?= __('admin.section.items') ?></label>
    <div class="section-items-sortable" id="<?= $containerId ?>">
        <?php foreach ($members as $idx => $m): ?>
        <div class="section-item-sortable" style="margin-bottom: 1rem; padding: 1rem; background: #f9fafb; border-radius: 8px; border: 1px solid #e5e7eb;">
            <div style="display: flex; gap: 0.5rem; margin-bottom: 0.75rem; align-items: center;">
                <div class="item-move-buttons" style="display: flex; gap: 0.25rem;">
                    <button type="button" class="btn btn-xs item-move-up">&#9650;</button>
                    <button type="button" class="btn btn-xs item-move-down">&#9660;</button>
                </div>
                <strong style="flex: 1; font-size: 0.9rem;"><?= str_replace(':num', $idx + 1, __('admin.section.team_member_label')) ?></strong>
                <button type="button" class="btn btn-xs btn-danger ts-remove-member">&#10005; <?= __('admin.section.remove_item') ?></button>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem;">
                <div class="form-group"><label><?= __('admin.section.team_name') ?></label><input type="text" name="member_name[]" class="form-control" value="<?= $esc($m['name'] ?? '') ?>"></div>
                <div class="form-group"><label><?= __('admin.section.team_role') ?></label><input type="text" name="member_role[]" class="form-control" value="<?= $esc($m['role'] ?? '') ?>"></div>
                <div class="form-group" style="grid-column: 1 / -1;">
                    <label><?= __('admin.section.team_profile_image') ?></label>
                    <div class="section-media-field-wrap" style="display:flex;gap:0.5rem;align-items:start;">
                        <input type="text" name="member_image[]" class="form-control section-media-input" value="<?= $esc($m['image'] ?? '') ?>" placeholder="/uploads/media/photo.jpg" style="flex:1;">
                        <button type="button" class="btn btn-secondary btn-sm section-media-browse"><?= __('admin.section.team_browse') ?></button>
                        <button type="button" class="btn btn-xs section-media-remove" title="Remove image">&times;</button>
                        <div class="section-media-preview" style="<?= empty($m['image']) ? 'display:none;' : '' ?>width:48px;height:48px;border-radius:6px;overflow:hidden;flex-shrink:0;">
                            <img src="<?= $esc($m['image'] ?? '') ?>" alt="" style="width:100%;height:100%;object-fit:cover;">
                        </div>
                    </div>
                </div>
                <div class="form-group"><label><?= __('admin.section.team_email') ?></label><input type="email" name="member_email[]" class="form-control" value="<?= $esc($m['email'] ?? '') ?>"></div>
                <div class="form-group"><label><?= __('admin.section.team_facebook') ?></label><input type="text" name="member_facebook[]" class="form-control" value="<?= $esc($m['facebook'] ?? '') ?>" placeholder="https://facebook.com/..."></div>
                <div class="form-group" style="grid-column: 1 / -1;"><label><?= __('admin.section.team_bio') ?></label><textarea name="member_bio[]" class="form-control" rows="2"><?= $esc($m['bio'] ?? '') ?></textarea></div>
                <div class="form-group"><label><?= __('admin.section.team_linkedin') ?></label><input type="text" name="member_linkedin[]" class="form-control" value="<?= $esc($m['linkedin'] ?? '') ?>"></div>
                <div class="form-group"><label><?= __('admin.section.team_twitter') ?></label><input type="text" name="member_twitter[]" class="form-control" value="<?= $esc($m['twitter'] ?? '') ?>"></div>
                <div class="form-group"><label><?= __('admin.section.team_website') ?></label><input type="text" name="member_website[]" class="form-control" value="<?= $esc($m['website'] ?? '') ?>"></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <button type="button" class="btn btn-secondary btn-sm" id="<?= $addBtnId ?>" style="margin-top: 0.75rem;"><?= __('admin.section.add_item') ?></button>
</div>

<script>
(function() {
    var container = document.getElementById('<?= $containerId ?>');
    if (!container) return;

    function memberHTML(idx) {
        return '<div style="display:flex;gap:0.5rem;margin-bottom:0.75rem;align-items:center;">' +
            '<div class="item-move-buttons" style="display:flex;gap:0.25rem;">' +
                '<button type="button" class="btn btn-xs item-move-up">&#9650;</button>' +
                '<button type="button" class="btn btn-xs item-move-down">&#9660;</button>' +
            '</div>' +
            '<strong style="flex:1;font-size:0.9rem;"><?= str_replace(':num', "' + (idx + 1) + '", __('admin.section.team_member_label')) ?></strong>' +
            '<button type="button" class="btn btn-xs btn-danger ts-remove-member">&#10005; <?= __('admin.section.remove_item') ?></button>' +
        '</div>' +
        '<div style="display:grid;grid-template-columns:1fr 1fr;gap:0.75rem;">' +
            '<div class="form-group"><label><?= __('admin.section.team_name') ?></label><input type="text" name="member_name[]" class="form-control" placeholder="John Doe"></div>' +
            '<div class="form-group"><label><?= __('admin.section.team_role') ?></label><input type="text" name="member_role[]" class="form-control" placeholder="Lead Designer"></div>' +
            '<div class="form-group" style="grid-column:1/-1;">' +
                '<label><?= __('admin.section.team_profile_image') ?></label>' +
                '<div class="section-media-field-wrap" style="display:flex;gap:0.5rem;align-items:start;">' +
                    '<input type="text" name="member_image[]" class="form-control section-media-input" placeholder="/uploads/media/photo.jpg" style="flex:1;">' +
                    '<button type="button" class="btn btn-secondary btn-sm section-media-browse"><?= __('admin.section.team_browse') ?></button>' +
                    '<button type="button" class="btn btn-xs section-media-remove" title="Remove image">&times;</button>' +
                    '<div class="section-media-preview" style="display:none;width:48px;height:48px;border-radius:6px;overflow:hidden;flex-shrink:0;">' +
                        '<img src="" alt="" style="width:100%;height:100%;object-fit:cover;">' +
                    '</div>' +
                '</div>' +
            '</div>' +
            '<div class="form-group"><label><?= __('admin.section.team_email') ?></label><input type="email" name="member_email[]" class="form-control" placeholder="john@example.com"></div>' +
            '<div class="form-group"><label><?= __('admin.section.team_facebook') ?></label><input type="text" name="member_facebook[]" class="form-control" placeholder="https://facebook.com/..."></div>' +
            '<div class="form-group" style="grid-column:1/-1;"><label><?= __('admin.section.team_bio') ?></label><textarea name="member_bio[]" class="form-control" rows="2"></textarea></div>' +
            '<div class="form-group"><label><?= __('admin.section.team_linkedin') ?></label><input type="text" name="member_linkedin[]" class="form-control"></div>' +
            '<div class="form-group"><label><?= __('admin.section.team_twitter') ?></label><input type="text" name="member_twitter[]" class="form-control"></div>' +
            '<div class="form-group"><label><?= __('admin.section.team_website') ?></label><input type="text" name="member_website[]" class="form-control"></div>' +
        '</div>';
    }

    var addBtn = document.getElementById('<?= $addBtnId ?>');
    if (addBtn) {
        addBtn.addEventListener('click', function() {
            var idx = container.querySelectorAll('.section-item-sortable').length;
            var div = document.createElement('div');
            div.className = 'section-item-sortable';
            div.style.cssText = 'margin-bottom:1rem;padding:1rem;background:#f9fafb;border-radius:8px;border:1px solid #e5e7eb';
            div.innerHTML = memberHTML(idx);
            container.appendChild(div);
            attachMemberHandlers(div);
            // Init media picker for the new member
            if (typeof initSectionMediaFields === 'function') initSectionMediaFields(div);
        });
    }

    container.querySelectorAll('.section-item-sortable').forEach(function(item) {
        attachMemberHandlers(item);
    });

    // Re-initialise media fields for server-rendered items.
    function _tsInitMedia() {
        if (typeof initSectionMediaFields === 'function') {
            initSectionMediaFields(container);
            return true;
        }
        return false;
    }
    if (!_tsInitMedia()) {
        var _tsRetry = setInterval(function () {
            if (_tsInitMedia()) clearInterval(_tsRetry);
        }, 80);
        setTimeout(function () { clearInterval(_tsRetry); }, 5000);
    }

    function attachMemberHandlers(item) {
        var upBtn = item.querySelector('.item-move-up');
        var downBtn = item.querySelector('.item-move-down');
        var removeBtn = item.querySelector('.ts-remove-member');

        if (upBtn) upBtn.addEventListener('click', function(e) {
            e.preventDefault();
            var prev = item.previousElementSibling;
            if (prev && prev.classList.contains('section-item-sortable')) {
                container.insertBefore(item, prev);
            }
        });
        if (downBtn) downBtn.addEventListener('click', function(e) {
            e.preventDefault();
            var next = item.nextElementSibling;
            if (next && next.classList.contains('section-item-sortable')) {
                container.insertBefore(next, item);
            }
        });
        if (removeBtn) removeBtn.addEventListener('click', function(e) {
            e.preventDefault();
            item.remove();
        });
    }
})();
</script>
