<?php
$pageTitle = 'Form Builder: ' . $form['name'];
$currentPage = 'forms';
$breadcrumb = [['label'=>'Forms','url'=>url('/forms')],['label'=>e($form['name'])],['label'=>'Builder']];
$headerActions = '
    <a href="'.url('/form/'.$form['slug']).'" target="_blank" class="btn-secondary btn-sm"><i class="fas fa-external-link-alt"></i> Preview</a>
    <button onclick="copyToClipboard(\''.url('/form/'.$form['slug']).'\')" class="btn-secondary btn-sm"><i class="fas fa-link"></i> Copy Link</button>
    <a href="'.url('/forms/'.$form['id'].'/responses').'" class="btn-secondary btn-sm"><i class="fas fa-inbox"></i> Responses</a>
';
require_once APP_PATH . '/views/layouts/header.php';
?>

<style>
.field-type-btn {
    display:flex;align-items:center;gap:.5rem;padding:.625rem .75rem;
    background:#f9fafb;border:1px solid #e5e7eb;border-radius:.75rem;
    cursor:pointer;font-size:.75rem;font-weight:600;color:#374151;
    transition:all .15s;text-align:left;width:100%;
}
.field-type-btn:hover { background:#e0e7ff;border-color:#6366f1;color:#4f46e5; }
.field-card {
    display:flex;align-items:center;gap:.75rem;padding:1rem;
    background:#fff;border:1.5px solid #e5e7eb;border-radius:.875rem;
    transition:border-color .15s;cursor:default;
}
.field-card:hover { border-color:#c7d2fe; }
/* FIX: drag handle must be clearly separated from click targets */
.drag-handle {
    cursor:grab;color:#d1d5db;font-size:1rem;
    padding:.25rem .5rem;flex-shrink:0;touch-action:none;
}
.drag-handle:active { cursor:grabbing; }
</style>

<div style="display:grid;grid-template-columns:320px 1fr;gap:1.25rem;height:calc(100vh - 140px)">

<!-- ═══ LEFT PANEL ═══ -->
<div style="display:flex;flex-direction:column;gap:1.25rem;overflow-y:auto;padding-right:2px">

    <!-- Form Settings -->
    <div class="card" style="padding:1.25rem">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem">
            <h3 style="font-weight:700;font-size:.85rem;color:#111827;margin:0">Form Settings</h3>
            <button onclick="toggleSettings()" style="background:none;border:none;cursor:pointer;color:#6b7280;font-size:.8rem" id="settingsToggle">
                <i class="fas fa-chevron-down"></i>
            </button>
        </div>
        <div id="settingsPanel">
            <form method="POST" action="<?= url('/forms/'.$form['id'].'/update') ?>">
                <?= csrf_field() ?>
                <div style="display:flex;flex-direction:column;gap:.875rem">
                    <div>
                        <label class="form-label">Form Name</label>
                        <input type="text" name="name" class="form-input" value="<?= e($form['name']) ?>" required style="font-size:.8rem">
                    </div>
                    <div>
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-input" rows="2" style="font-size:.8rem"><?= e($form['description']) ?></textarea>
                    </div>
                    <div>
                        <label class="form-label">WhatsApp Number</label>
                        <input type="text" name="whatsapp_number" class="form-input" value="<?= e($form['whatsapp_number']) ?>" placeholder="601234567890" style="font-size:.8rem">
                    </div>
                    <div>
                        <label class="form-label">Thank You Message</label>
                        <textarea name="thank_you_message" class="form-input" rows="2" style="font-size:.8rem"><?= e($form['thank_you_message']) ?></textarea>
                    </div>
                    <div>
                        <label class="form-label">Redirect URL</label>
                        <input type="url" name="redirect_url" class="form-input" value="<?= e($form['redirect_url']) ?>" placeholder="https://..." style="font-size:.8rem">
                    </div>
                    <button type="submit" class="btn-primary btn-sm"><i class="fas fa-save"></i> Save Settings</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add Field -->
    <div class="card" style="padding:1.25rem">
        <h3 style="font-weight:700;font-size:.85rem;color:#111827;margin:0 0 1rem">Add New Field</h3>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:.5rem">
            <?php
            $fieldTypes = [
                ['type'=>'text',     'icon'=>'fa-font',               'label'=>'Text'],
                ['type'=>'email',    'icon'=>'fa-envelope',           'label'=>'Email'],
                ['type'=>'phone',    'icon'=>'fa-phone',              'label'=>'Phone'],
                ['type'=>'number',   'icon'=>'fa-hashtag',            'label'=>'Number'],
                ['type'=>'textarea', 'icon'=>'fa-align-left',         'label'=>'Textarea'],
                ['type'=>'select',   'icon'=>'fa-chevron-circle-down','label'=>'Dropdown'],
                ['type'=>'radio',    'icon'=>'fa-dot-circle',         'label'=>'Radio'],
                ['type'=>'checkbox', 'icon'=>'fa-check-square',       'label'=>'Checkbox'],
                ['type'=>'date',     'icon'=>'fa-calendar',           'label'=>'Date'],
                ['type'=>'file',     'icon'=>'fa-paperclip',          'label'=>'File'],
                ['type'=>'image',    'icon'=>'fa-image',              'label'=>'Image'],
            ];
            foreach ($fieldTypes as $ft): ?>
            <button class="field-type-btn" onclick="openAddField('<?= $ft['type'] ?>')">
                <i class="fas <?= $ft['icon'] ?>" style="width:14px;text-align:center;color:#6366f1;font-size:.8rem"></i>
                <?= $ft['label'] ?>
            </button>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Edit Field Panel (hidden) -->
    <div class="card" style="padding:1.25rem;display:none" id="editFieldPanel">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem">
            <h3 style="font-weight:700;font-size:.85rem;color:#111827;margin:0">Field Settings</h3>
            <button onclick="closeEditPanel()" style="background:#f3f4f6;border:none;cursor:pointer;color:#374151;width:28px;height:28px;border-radius:50%;font-weight:700;font-size:.9rem">&times;</button>
        </div>
        <div style="display:flex;flex-direction:column;gap:.875rem">
            <input type="hidden" id="editFieldId">
            <input type="hidden" id="editFieldType">
            <div>
                <label class="form-label">Label *</label>
                <input type="text" id="editLabel" class="form-input" style="font-size:.8rem">
            </div>
            <div>
                <label class="form-label">Placeholder</label>
                <input type="text" id="editPlaceholder" class="form-input" style="font-size:.8rem">
            </div>
            <!-- Options (text) for select/radio/checkbox -->
            <div id="editOptionsTextWrap" style="display:none">
                <label class="form-label">Options <span style="font-weight:400;text-transform:none;font-size:.7rem">(satu per baris)</span></label>
                <textarea id="editOptions" class="form-input" rows="4" style="font-size:.8rem;resize:vertical" placeholder="Pilihan 1&#10;Pilihan 2&#10;Pilihan 3"></textarea>
            </div>
            <!-- Image options for select/radio/checkbox -->
            <div id="editOptionsImgWrap" style="display:none">
                <label class="form-label" style="margin-bottom:.5rem">Image Options</label>
                <div id="editImgOptionsList" style="display:flex;flex-direction:column;gap:.5rem"></div>
                <button onclick="addImgOptionRow()" style="margin-top:.5rem;background:#e0e7ff;border:none;cursor:pointer;color:#4f46e5;font-size:.75rem;font-weight:700;padding:.5rem .875rem;border-radius:.625rem;width:100%">
                    <i class="fas fa-plus"></i> Add Image Option
                </button>
                <p style="font-size:.65rem;color:#9ca3af;margin:.375rem 0 0">Format disimpan: label|nama_gambar.jpg</p>
            </div>
            <!-- Toggle between text/image options -->
            <div id="editOptionsToggle" style="display:none">
                <label class="form-label">Option Type</label>
                <div style="display:flex;gap:.5rem">
                    <button id="toggleTextBtn" onclick="switchOptionMode('text')" style="flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #6366f1;background:#e0e7ff;color:#4f46e5;font-size:.75rem;font-weight:700;cursor:pointer">
                        <i class="fas fa-list"></i> Text
                    </button>
                    <button id="toggleImgBtn" onclick="switchOptionMode('image')" style="flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #e5e7eb;background:#f9fafb;color:#6b7280;font-size:.75rem;font-weight:700;cursor:pointer">
                        <i class="fas fa-image"></i> Image
                    </button>
                </div>
            </div>
            <div style="display:flex;align-items:center;gap:.5rem">
                <input type="checkbox" id="editRequired" style="width:16px;height:16px;accent-color:#4f46e5">
                <label for="editRequired" style="font-size:.8rem;font-weight:600;color:#374151;cursor:pointer">Required field</label>
            </div>
            <div style="display:flex;gap:.5rem">
                <button onclick="saveFieldEdit()" class="btn-primary btn-sm" style="flex:1;justify-content:center"><i class="fas fa-save"></i> Save</button>
                <button onclick="deleteFieldById()" class="btn-danger btn-sm"><i class="fas fa-trash"></i></button>
            </div>
        </div>
    </div>

</div>

<!-- ═══ RIGHT PANEL: Builder Canvas ═══ -->
<div class="card" style="display:flex;flex-direction:column;overflow:hidden">
    <div style="padding:1rem 1.5rem;border-bottom:1px solid #f3f4f6;display:flex;align-items:center;justify-content:space-between">
        <div>
            <h3 style="font-weight:700;font-size:.9rem;color:#111827;margin:0"><?= e($form['name']) ?></h3>
            <p style="font-size:.7rem;color:#9ca3af;margin:.125rem 0 0" id="fieldCountLabel"><?= count($fields) ?> field(s) &bull; Drag <i class="fas fa-grip-vertical"></i> untuk reorder</p>
        </div>
        <span style="font-size:.7rem;color:#d1d5db;font-weight:500">Form ID: #<?= $form['id'] ?></span>
    </div>

    <div style="flex:1;overflow-y:auto;padding:1.5rem">
        <?php if (empty($fields)): ?>
        <div id="emptyState" style="text-align:center;padding:3rem;color:#9ca3af;border:2px dashed #e5e7eb;border-radius:1rem">
            <i class="fas fa-hand-pointer" style="font-size:2rem;margin-bottom:.75rem;display:block;color:#d1d5db"></i>
            <p style="font-weight:600;font-size:.875rem;margin:0 0 .25rem">Tiada Field Lagi</p>
            <p style="font-size:.75rem;margin:0">Klik jenis field di sebelah kiri untuk tambah.</p>
        </div>
        <?php else: ?>
        <div id="emptyState" style="display:none"></div>
        <?php endif; ?>

        <!-- FIX: fieldList dengan id yang unik, Sortable attach pada div ini -->
        <div id="fieldList" style="display:flex;flex-direction:column;gap:.625rem;min-height:50px">
            <?php foreach ($fields as $field): ?>
            <?php
            $fIcons = ['text'=>'fa-font','email'=>'fa-envelope','phone'=>'fa-phone','number'=>'fa-hashtag','textarea'=>'fa-align-left','select'=>'fa-chevron-circle-down','radio'=>'fa-dot-circle','checkbox'=>'fa-check-square','date'=>'fa-calendar','file'=>'fa-paperclip','image'=>'fa-image'];
            $fBadge = ['text'=>'badge-gray','email'=>'badge-blue','phone'=>'badge-green','number'=>'badge-orange','textarea'=>'badge-gray','select'=>'badge-purple','radio'=>'badge-purple','checkbox'=>'badge-purple','date'=>'badge-blue','file'=>'badge-orange','image'=>'badge-orange'];
            $icon = $fIcons[$field['field_type']] ?? 'fa-input';
            $badge = $fBadge[$field['field_type']] ?? 'badge-gray';
            ?>
            <div class="field-card" data-field-id="<?= $field['id'] ?>">
                <div class="drag-handle" title="Drag untuk reorder"><i class="fas fa-grip-vertical"></i></div>
                <div style="width:36px;height:36px;background:#e0e7ff;border-radius:.625rem;display:flex;align-items:center;justify-content:center;flex-shrink:0">
                    <i class="fas <?= $icon ?>" style="color:#4f46e5;font-size:.8rem"></i>
                </div>
                <div style="flex:1;min-width:0">
                    <div style="font-weight:700;font-size:.875rem;color:#111827">
                        <?= e($field['label']) ?>
                        <?php if ($field['required']): ?><span style="color:#ef4444;margin-left:.25rem">*</span><?php endif; ?>
                    </div>
                    <div style="font-size:.7rem;color:#9ca3af;margin-top:.125rem">
                        <?= $field['field_type'] ?>
                        <?php if (!empty($field['placeholder'])): ?>&bull; <?= e($field['placeholder']) ?><?php endif; ?>
                    </div>
                </div>
                <span class="badge <?= $badge ?>" style="font-size:.65rem;text-transform:capitalize;flex-shrink:0"><?= $field['field_type'] ?></span>
                <button onclick="openEditField(<?= $field['id'] ?>)" style="background:none;border:none;cursor:pointer;color:#9ca3af;padding:.375rem;transition:color .15s;flex-shrink:0" onmouseover="this.style.color='#4f46e5'" onmouseout="this.style.color='#9ca3af'" title="Edit">
                    <i class="fas fa-edit"></i>
                </button>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

</div>

<!-- ═══ ADD FIELD MODAL ═══ -->
<div id="addFieldModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:9999;align-items:center;justify-content:center">
    <div style="background:#fff;border-radius:1.25rem;padding:1.75rem;width:100%;max-width:480px;margin:1rem;max-height:90vh;overflow-y:auto">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.25rem">
            <h3 style="font-weight:800;font-size:1rem;color:#111827;margin:0" id="addFieldTitle">Add Field</h3>
            <button onclick="closeAddModal()" style="background:#f3f4f6;border:none;cursor:pointer;color:#374151;width:32px;height:32px;border-radius:50%;font-weight:700;font-size:1rem;display:flex;align-items:center;justify-content:center;flex-shrink:0">&times;</button>
        </div>
        <input type="hidden" id="addFieldType">
        <div style="display:flex;flex-direction:column;gap:1rem">
            <div>
                <label class="form-label">Label *</label>
                <input type="text" id="addLabel" class="form-input" placeholder="Nama field">
            </div>
            <div>
                <label class="form-label">Placeholder</label>
                <input type="text" id="addPlaceholder" class="form-input" placeholder="Placeholder (optional)">
            </div>

            <!-- Options Toggle (for select/radio/checkbox) -->
            <div id="addOptionsSection" style="display:none">
                <div style="display:flex;gap:.5rem;margin-bottom:.75rem">
                    <button id="addToggleTextBtn" onclick="switchAddOptionMode('text')" style="flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #6366f1;background:#e0e7ff;color:#4f46e5;font-size:.75rem;font-weight:700;cursor:pointer">
                        <i class="fas fa-list"></i> Text Options
                    </button>
                    <button id="addToggleImgBtn" onclick="switchAddOptionMode('image')" style="flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #e5e7eb;background:#f9fafb;color:#6b7280;font-size:.75rem;font-weight:700;cursor:pointer">
                        <i class="fas fa-image"></i> Image Options
                    </button>
                </div>

                <!-- Text options -->
                <div id="addTextOptions">
                    <label class="form-label">Options <span style="font-weight:400;text-transform:none">(satu per baris)</span></label>
                    <textarea id="addOptions" class="form-input" rows="4" placeholder="Pilihan 1&#10;Pilihan 2&#10;Pilihan 3"></textarea>
                </div>

                <!-- Image options -->
                <div id="addImgOptions" style="display:none">
                    <label class="form-label" style="margin-bottom:.5rem">Image Options</label>
                    <div id="addImgOptionsList" style="display:flex;flex-direction:column;gap:.5rem"></div>
                    <button onclick="addModalImgRow()" style="margin-top:.5rem;background:#e0e7ff;border:none;cursor:pointer;color:#4f46e5;font-size:.75rem;font-weight:700;padding:.5rem .875rem;border-radius:.625rem;width:100%">
                        <i class="fas fa-plus"></i> Add Image Option
                    </button>
                    <p style="font-size:.65rem;color:#9ca3af;margin:.375rem 0 0">Upload gambar untuk setiap pilihan</p>
                </div>
            </div>

            <div style="display:flex;align-items:center;gap:.5rem">
                <input type="checkbox" id="addRequired" style="width:16px;height:16px;accent-color:#4f46e5">
                <label for="addRequired" style="font-size:.875rem;font-weight:600;color:#374151;cursor:pointer">Required field</label>
            </div>
            <div style="display:flex;gap:.75rem;padding-top:.5rem;border-top:1px solid #f3f4f6">
                <button onclick="submitAddField()" class="btn-primary" style="flex:1;justify-content:center"><i class="fas fa-plus"></i> Add Field</button>
                <button onclick="closeAddModal()" class="btn-secondary">Cancel</button>
            </div>
        </div>
    </div>
</div>

<script>
var FORM_ID = <?= $form['id'] ?>;
var hasOptions = ['select','radio','checkbox'];
var currentAddMode = 'text';   // 'text' or 'image'
var currentEditMode = 'text';
var fieldCount = <?= count($fields) ?>;

// ─── FIX 1: Sortable — pastikan attach SELEPAS DOM ready, guna filter supaya button tidak trigger drag ───
document.addEventListener('DOMContentLoaded', function() {
    var fieldList = document.getElementById('fieldList');
    if (fieldList) {
        Sortable.create(fieldList, {
            animation: 150,
            handle: '.drag-handle',          // HANYA drag-handle boleh trigger drag
            filter: 'button, a, input',      // Elemen ini TIDAK trigger drag
            ghostClass: 'sortable-ghost',
            chosenClass: 'sortable-chosen',
            dragClass: 'sortable-drag',
            forceFallback: false,
            onEnd: function(evt) {
                var items = fieldList.querySelectorAll('[data-field-id]');
                var order = Array.from(items).map(function(el) { return parseInt(el.dataset.fieldId); });
                apiPost('/fields/reorder', { form_id: FORM_ID, order: order }).then(function(res) {
                    if (res.success) showToast('Susunan disimpan!', 'success');
                    else showToast('Gagal simpan susunan', 'error');
                });
            }
        });
    }
});

// ─── SETTINGS TOGGLE ───
function toggleSettings() {
    var p = document.getElementById('settingsPanel');
    var ic = document.getElementById('settingsToggle').querySelector('i');
    if (p.style.display === 'none') { p.style.display = ''; ic.className = 'fas fa-chevron-up'; }
    else { p.style.display = 'none'; ic.className = 'fas fa-chevron-down'; }
}

// ─── FIX 2: openAddField — TIDAK set required by default, reset semua fields ───
function openAddField(type) {
    currentAddMode = 'text';
    document.getElementById('addFieldType').value = type;
    document.getElementById('addFieldTitle').textContent = 'Add ' + capitalize(type) + ' Field';

    // Reset semua input — ini fix masalah "auto required"
    document.getElementById('addLabel').value = '';
    document.getElementById('addPlaceholder').value = '';
    document.getElementById('addOptions').value = '';
    document.getElementById('addRequired').checked = false;  // MESTI false by default
    document.getElementById('addImgOptionsList').innerHTML = '';

    // Show/hide options section
    var showOpts = hasOptions.includes(type);
    document.getElementById('addOptionsSection').style.display = showOpts ? '' : 'none';

    // Reset to text mode
    if (showOpts) {
        switchAddOptionMode('text');
    }

    document.getElementById('addFieldModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
    setTimeout(function() { document.getElementById('addLabel').focus(); }, 80);
}

function closeAddModal() {
    document.getElementById('addFieldModal').style.display = 'none';
    document.body.style.overflow = '';
}

function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1); }

// ─── Image option rows (Add modal) ───
function addModalImgRow(labelVal, imgName) {
    var list = document.getElementById('addImgOptionsList');
    var row  = document.createElement('div');
    row.setAttribute('data-img-row', '1');
    row.style.cssText = 'background:#f9fafb;border:1px solid #e5e7eb;border-radius:.75rem;padding:.75rem;margin-bottom:.375rem';
    var previewSrc = imgName ? (APP_URL + '/public/uploads/' + imgName) : '';
    row.innerHTML =
        '<img data-preview src="'+previewSrc+'" style="width:100%;max-height:100px;object-fit:cover;border-radius:.5rem;margin-bottom:.375rem;'+(imgName?'display:block':'display:none')+'">' +
        '<input type="text" data-label placeholder="Label pilihan" value="'+(labelVal||'')+'" style="width:100%;border:1px solid #e5e7eb;background:#fff;font-size:.8rem;outline:none;color:#111827;padding:.5rem .75rem;border-radius:.5rem;margin-bottom:.375rem;box-sizing:border-box">' +
        '<div style="display:flex;align-items:center;gap:.5rem">' +
            '<span data-status style="flex:1;font-size:.7rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:'+(imgName?'#059669':'#9ca3af')+'">'+(imgName?'&#10003; '+imgName:'Belum upload gambar')+'</span>' +
            '<label style="cursor:pointer;flex-shrink:0">' +
                '<input type="file" accept=".jpg,.jpeg,.png,.gif,.webp" style="display:none" onchange="doImgUpload(this)">' +
                '<span style="display:inline-block;background:#4f46e5;color:#fff;padding:.375rem .625rem;border-radius:.5rem;font-size:.7rem;font-weight:700">&#128247; Upload</span>' +
            '</label>' +
            '<button type="button" onclick="this.closest(\'[data-img-row]\').remove()" style="background:#fee2e2;border:none;cursor:pointer;color:#dc2626;width:26px;height:26px;border-radius:.375rem;font-weight:700;flex-shrink:0">&times;</button>' +
        '</div>' +
        '<input type="hidden" data-filename value="'+(imgName||'')+'">';
    list.appendChild(row);
}

function handleImgOptionUpload(input) { doImgUpload(input); }

function doImgUpload(input) {
    if (!input.files || !input.files[0]) return;

    // Walk up to the [data-img-row] container
    var row = input.parentElement;
    while (row && !row.hasAttribute('data-img-row')) { row = row.parentElement; }
    if (!row) { showToast('Error: row tidak dijumpai', 'error'); return; }

    var preview  = row.querySelector('[data-preview]');
    var status   = row.querySelector('[data-status]');
    var filename = row.querySelector('[data-filename]');

    var file = input.files[0];
    if (file.size > 5*1024*1024) { showToast('Gambar terlalu besar. Max 5MB.','error'); return; }

    var allowed = ['image/jpeg','image/png','image/gif','image/webp'];
    if (!allowed.includes(file.type)) { showToast('Format tidak disokong. Guna JPG/PNG/GIF/WEBP.','error'); return; }

    // Immediate local preview
    var reader = new FileReader();
    reader.onload = function(e) {
        if (preview) { preview.src = e.target.result; preview.style.display = 'block'; }
    };
    reader.readAsDataURL(file);

    if (status) { status.textContent = 'Uploading...'; status.style.color = '#9ca3af'; }

    var fd = new FormData();
    fd.append('image', file);

    fetch(APP_URL + '/upload/image', { method:'POST', body:fd })
        .then(function(r) {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.json();
        })
        .then(function(data) {
            if (data.success) {
                if (preview)  { preview.src = data.url; preview.style.display = 'block'; }
                if (status)   { status.textContent = '\u2713 ' + data.filename; status.style.color = '#059669'; }
                if (filename) { filename.value = data.filename; }
                showToast('Upload berjaya: ' + data.filename, 'success');
            } else {
                if (status) { status.textContent = '\u2717 Gagal'; status.style.color = '#ef4444'; }
                if (filename) { filename.value = ''; }
                showToast(data.message || 'Upload gagal', 'error');
            }
        })
        .catch(function(err) {
            if (status) { status.textContent = '\u2717 Error: ' + err.message; status.style.color = '#ef4444'; }
            if (filename) { filename.value = ''; }
            showToast('Upload error: ' + err.message, 'error');
        });
}

function addEditImgRow(labelVal, imgName) {
    var list = document.getElementById('editImgOptionsList');
    var row  = document.createElement('div');
    row.setAttribute('data-img-row', '1');
    row.style.cssText = 'background:#f9fafb;border:1px solid #e5e7eb;border-radius:.75rem;padding:.75rem;margin-bottom:.375rem';
    var previewSrc = imgName ? (APP_URL + '/public/uploads/' + imgName) : '';
    row.innerHTML =
        '<img data-preview src="'+previewSrc+'" style="width:100%;max-height:100px;object-fit:cover;border-radius:.5rem;margin-bottom:.375rem;'+(imgName?'display:block':'display:none')+'">' +
        '<input type="text" data-label placeholder="Label" value="'+(labelVal||'')+'" style="width:100%;border:1px solid #e5e7eb;background:#fff;font-size:.8rem;outline:none;color:#111827;padding:.5rem .75rem;border-radius:.5rem;margin-bottom:.375rem;box-sizing:border-box">' +
        '<div style="display:flex;align-items:center;gap:.5rem">' +
            '<span data-status style="flex:1;font-size:.7rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:'+(imgName?'#059669':'#9ca3af')+'">'+(imgName?'&#10003; '+imgName:'Belum upload gambar')+'</span>' +
            '<label style="cursor:pointer;flex-shrink:0">' +
                '<input type="file" accept=".jpg,.jpeg,.png,.gif,.webp" style="display:none" onchange="doImgUpload(this)">' +
                '<span style="display:inline-block;background:#4f46e5;color:#fff;padding:.375rem .625rem;border-radius:.5rem;font-size:.7rem;font-weight:700">&#128247; Upload</span>' +
            '</label>' +
            '<button type="button" onclick="this.closest(\'[data-img-row]\').remove()" style="background:#fee2e2;border:none;cursor:pointer;color:#dc2626;width:26px;height:26px;border-radius:.375rem;font-weight:700;flex-shrink:0">&times;</button>' +
        '</div>' +
        '<input type="hidden" data-filename value="'+(imgName||'')+'">';
    list.appendChild(row);
}
    currentAddMode = mode;
    var textActive = mode === 'text';
    document.getElementById('addTextOptions').style.display = textActive ? '' : 'none';
    document.getElementById('addImgOptions').style.display  = textActive ? 'none' : '';
    document.getElementById('addToggleTextBtn').style.cssText = textActive
        ? 'flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #6366f1;background:#e0e7ff;color:#4f46e5;font-size:.75rem;font-weight:700;cursor:pointer'
        : 'flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #e5e7eb;background:#f9fafb;color:#6b7280;font-size:.75rem;font-weight:700;cursor:pointer';
    document.getElementById('addToggleImgBtn').style.cssText = !textActive
        ? 'flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #6366f1;background:#e0e7ff;color:#4f46e5;font-size:.75rem;font-weight:700;cursor:pointer'
        : 'flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #e5e7eb;background:#f9fafb;color:#6b7280;font-size:.75rem;font-weight:700;cursor:pointer';
}

// ─── FIX 3: submitAddField — handle image options, satu kali sahaja ───
var _submitting = false;
async function submitAddField() {
    if (_submitting) return;  // Prevent double submit (punca field double)
    var label = document.getElementById('addLabel').value.trim();
    var type  = document.getElementById('addFieldType').value;
    if (!label) { showToast('Label diperlukan.', 'error'); return; }

    var optionsValue = '';
    if (hasOptions.includes(type)) {
        if (currentAddMode === 'text') {
            optionsValue = document.getElementById('addOptions').value.trim();
        } else {
            // Build image options using data-attributes: "label|filename" one per line
            var rows = document.getElementById('addImgOptionsList').querySelectorAll('[data-img-row]');
            var lines = [];
            rows.forEach(function(row) {
                var lbl  = row.querySelector('[data-label]');
                var file = row.querySelector('[data-filename]');
                if (lbl && lbl.value.trim()) {
                    lines.push(lbl.value.trim() + (file && file.value ? '|' + file.value : ''));
                }
            });
            optionsValue = lines.join('\n');
        }
    }

    _submitting = true;
    var btn = document.querySelector('#addFieldModal .btn-primary');
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...'; }

    var res = await apiPost('/fields/store', {
        form_id:    FORM_ID,
        label:      label,
        field_type: type,
        placeholder:document.getElementById('addPlaceholder').value,
        options:    optionsValue,
        required:   document.getElementById('addRequired').checked ? 1 : 0
    });

    _submitting = false;
    if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-plus"></i> Add Field'; }

    if (res.success) {
        closeAddModal();
        appendFieldCard(res.field);
        fieldCount++;
        updateFieldCount();
        var es = document.getElementById('emptyState');
        if (es) es.style.display = 'none';
        showToast(res.message, 'success');
    } else {
        showToast(res.message || 'Gagal tambah field.', 'error');
    }
}

function updateFieldCount() {
    var el = document.getElementById('fieldCountLabel');
    if (el) el.innerHTML = fieldCount + ' field(s) &bull; Drag <i class="fas fa-grip-vertical"></i> untuk reorder';
}

// ─── Append field card to list ───
function appendFieldCard(f) {
    var icons = {text:'fa-font',email:'fa-envelope',phone:'fa-phone',number:'fa-hashtag',textarea:'fa-align-left',select:'fa-chevron-circle-down',radio:'fa-dot-circle',checkbox:'fa-check-square',date:'fa-calendar',file:'fa-paperclip',image:'fa-image'};
    var badges = {text:'badge-gray',email:'badge-blue',phone:'badge-green',number:'badge-orange',textarea:'badge-gray',select:'badge-purple',radio:'badge-purple',checkbox:'badge-purple',date:'badge-blue',file:'badge-orange',image:'badge-orange'};
    var el = document.createElement('div');
    el.className = 'field-card';
    el.setAttribute('data-field-id', f.id);
    el.innerHTML =
        '<div class="drag-handle" title="Drag untuk reorder"><i class="fas fa-grip-vertical"></i></div>' +
        '<div style="width:36px;height:36px;background:#e0e7ff;border-radius:.625rem;display:flex;align-items:center;justify-content:center;flex-shrink:0">' +
            '<i class="fas '+(icons[f.field_type]||'fa-input')+'" style="color:#4f46e5;font-size:.8rem"></i>' +
        '</div>' +
        '<div style="flex:1;min-width:0">' +
            '<div style="font-weight:700;font-size:.875rem;color:#111827">' + escStr(f.label) + (f.required=='1'?'<span style="color:#ef4444;margin-left:.25rem">*</span>':'') + '</div>' +
            '<div style="font-size:.7rem;color:#9ca3af;margin-top:.125rem">' + f.field_type + (f.placeholder?' &bull; '+escStr(f.placeholder):'') + '</div>' +
        '</div>' +
        '<span class="badge '+(badges[f.field_type]||'badge-gray')+'" style="font-size:.65rem;text-transform:capitalize;flex-shrink:0">' + f.field_type + '</span>' +
        '<button onclick="openEditField('+f.id+')" style="background:none;border:none;cursor:pointer;color:#9ca3af;padding:.375rem;flex-shrink:0" title="Edit"><i class="fas fa-edit"></i></button>';
    document.getElementById('fieldList').appendChild(el);
}

function escStr(s) {
    return (s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// ─── Edit field panel ───
async function openEditField(id) {
    var res = await apiGet('/fields/' + id);
    if (!res.success) { showToast('Field tidak dijumpai','error'); return; }
    var f = res.field;
    currentEditMode = 'text';

    document.getElementById('editFieldId').value = f.id;
    document.getElementById('editFieldType').value = f.field_type;
    document.getElementById('editLabel').value = f.label;
    document.getElementById('editPlaceholder').value = f.placeholder || '';
    document.getElementById('editRequired').checked = f.required == '1';

    var showOpts = hasOptions.includes(f.field_type);
    document.getElementById('editOptionsToggle').style.display = showOpts ? '' : 'none';

    if (showOpts) {
        // Detect if options contain image format (label|filename)
        var rawOpts = f.options || '';
        var hasImgOpts = rawOpts.split('\n').some(function(l){ return l.indexOf('|') > -1; });

        if (hasImgOpts) {
            switchEditOptionMode('image');
            // Populate image rows
            var list = document.getElementById('editImgOptionsList');
            list.innerHTML = '';
            rawOpts.split('\n').forEach(function(line) {
                line = line.trim();
                if (!line) return;
                var parts = line.split('|');
                addEditImgRow(parts[0] || '', parts[1] || '');
            });
        } else {
            switchEditOptionMode('text');
            document.getElementById('editOptions').value = rawOpts;
        }
    } else {
        document.getElementById('editOptionsTextWrap').style.display = 'none';
        document.getElementById('editOptionsImgWrap').style.display  = 'none';
    }

    document.getElementById('editFieldPanel').style.display = '';
    document.getElementById('editFieldPanel').scrollIntoView({ behavior:'smooth', block:'nearest' });
}

function closeEditPanel() {
    document.getElementById('editFieldPanel').style.display = 'none';
}

function switchEditOptionMode(mode) {
    currentEditMode = mode;
    var textActive = mode === 'text';
    document.getElementById('editOptionsTextWrap').style.display = textActive ? '' : 'none';
    document.getElementById('editOptionsImgWrap').style.display  = textActive ? 'none' : '';
    document.getElementById('toggleTextBtn').style.cssText = textActive
        ? 'flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #6366f1;background:#e0e7ff;color:#4f46e5;font-size:.75rem;font-weight:700;cursor:pointer'
        : 'flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #e5e7eb;background:#f9fafb;color:#6b7280;font-size:.75rem;font-weight:700;cursor:pointer';
    document.getElementById('toggleImgBtn').style.cssText = !textActive
        ? 'flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #6366f1;background:#e0e7ff;color:#4f46e5;font-size:.75rem;font-weight:700;cursor:pointer'
        : 'flex:1;padding:.5rem;border-radius:.625rem;border:1.5px solid #e5e7eb;background:#f9fafb;color:#6b7280;font-size:.75rem;font-weight:700;cursor:pointer';
}

function addImgOptionRow(label, imgName) { addEditImgRow(label, imgName); }

function addEditImgRow(label, imgName) {
    var list = document.getElementById('editImgOptionsList');
    var row = document.createElement('div');
    row.style.cssText = 'display:flex;flex-direction:column;gap:.375rem;background:#f9fafb;border:1px solid #e5e7eb;border-radius:.75rem;padding:.75rem';
    var previewSrc = imgName ? (APP_URL + '/public/uploads/' + imgName) : '';
    row.innerHTML =
        '<img class="img-option-preview" src="'+previewSrc+'" style="width:100%;max-height:100px;object-fit:cover;border-radius:.5rem;'+(imgName?'':'display:none')+'">' +
        '<div style="display:flex;gap:.375rem;align-items:center">' +
            '<input type="text" placeholder="Label" value="'+(label||'')+'" style="flex:1;border:1px solid #e5e7eb;background:#fff;font-size:.8rem;outline:none;color:#111827;padding:.375rem .625rem;border-radius:.5rem">' +
            '<label style="display:flex;align-items:center;gap:.25rem;cursor:pointer;flex-shrink:0">' +
                '<input type="file" accept=".jpg,.jpeg,.png,.gif,.webp" style="display:none" onchange="handleImgOptionUpload(this)">' +
        async function saveFieldEdit() {
    var id    = document.getElementById('editFieldId').value;
    var ftype = document.getElementById('editFieldType').value;
    var label = document.getElementById('editLabel').value.trim();
    if (!label) { showToast('Label diperlukan','error'); return; }

    var optionsValue = '';
    if (hasOptions.includes(ftype)) {
        if (currentEditMode === 'text') {
            optionsValue = document.getElementById('editOptions').value.trim();
        } else {
            var rows = document.getElementById('editImgOptionsList').querySelectorAll('[data-img-row]');
            var lines = [];
            rows.forEach(function(row) {
                var lbl  = row.querySelector('[data-label]');
                var file = row.querySelector('[data-filename]');
                if (lbl && lbl.value.trim()) {
                    lines.push(lbl.value.trim() + (file && file.value ? '|' + file.value : ''));
                }
            });
            optionsValue = lines.join('\n');
        }
    }

    var res = await apiPost('/fields/' + id + '/update', {
        label:       label,
        field_type:  ftype,
        placeholder: document.getElementById('editPlaceholder').value,
        options:     optionsValue,
        required:    document.getElementById('editRequired').checked ? 1 : 0
    });

    if (res.success) {
        // Update card in DOM
        var el = document.querySelector('[data-field-id="'+id+'"]');
        if (el) {
            var nameEl = el.querySelector('div[style*="font-weight:700"]');
            if (nameEl) nameEl.innerHTML = escStr(res.field.label) + (res.field.required=='1'?'<span style="color:#ef4444;margin-left:.25rem">*</span>':'');
        }
        closeEditPanel();
        showToast(res.message, 'success');
    } else {
        showToast(res.message, 'error');
    }
}

async function deleteFieldById() {
    var id = document.getElementById('editFieldId').value;
    confirmDelete('Padam field ini?', async function() {
        var res = await apiPost('/fields/' + id + '/delete', {});
        if (res.success) {
            var el = document.querySelector('[data-field-id="'+id+'"]');
            if (el) el.remove();
            closeEditPanel();
            fieldCount--;
            updateFieldCount();
            showToast(res.message, 'success');
            if (document.getElementById('fieldList').children.length === 0) {
                document.getElementById('emptyState').style.display = '';
            }
        } else {
            showToast(res.message, 'error');
        }
    });
}

// ─── Backdrop click & ESC ───
document.getElementById('addFieldModal').addEventListener('click', function(e) {
    if (e.target === this) closeAddModal();
});
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') { closeAddModal(); closeEditPanel(); }
    if (e.key === 'Enter' && document.getElementById('addFieldModal').style.display === 'flex') {
        if (document.activeElement && document.activeElement.tagName !== 'TEXTAREA' && document.activeElement.tagName !== 'BUTTON') {
            e.preventDefault();
            submitAddField();
        }
    }
});
</script>

<?php require_once APP_PATH . '/views/layouts/footer.php'; ?>
