<?php
// phpcs:ignoreFile
if (!defined('ABSPATH')) { exit; }
global $wpdb;
$table  = $wpdb->prefix . 'yatoon_form_fields';
$fields = $wpdb->get_results("SELECT * FROM $table ORDER BY sort_order ASC, id ASC");
$nonce  = wp_create_nonce('yatoon_form_fields');
?>
<div class="wrap" id="yatoon-form-fields-wrap">
<h1>Custom Booking Fields</h1>
<p style="color:#6b7280;margin-top:0;">Add extra fields to Step 5 of the booking form - allergy notes, reference image links, skin type, first-visit question, and more.</p>

<style>
#yatoon-form-fields-wrap *{box-sizing:border-box;}
#yatoon-form-fields-wrap .yff-layout{display:grid;grid-template-columns:1fr 340px;gap:20px;margin-top:16px;}
#yatoon-form-fields-wrap .yff-panel{background:#fff;border:1px solid #e5e7eb;border-radius:10px;overflow:hidden;}
#yatoon-form-fields-wrap .yff-head{padding:14px 18px;border-bottom:1px solid #f3f4f6;display:flex;align-items:center;justify-content:space-between;}
#yatoon-form-fields-wrap .yff-head h2{margin:0;font-size:14px;font-weight:600;color:#111827;}
#yatoon-form-fields-wrap .yff-body{padding:18px;}
#yatoon-form-fields-wrap .yff-field-row{display:flex;align-items:center;gap:10px;padding:12px 14px;border:1px solid #e5e7eb;border-radius:8px;margin-bottom:8px;background:#fff;cursor:grab;}
#yatoon-form-fields-wrap .yff-field-row:hover{border-color:#d1d5db;box-shadow:0 2px 8px rgba(0,0,0,.05);}
#yatoon-form-fields-wrap .yff-drag-handle{color:#9ca3af;cursor:grab;font-size:16px;flex-shrink:0;}
#yatoon-form-fields-wrap .yff-field-info{flex:1;min-width:0;}
#yatoon-form-fields-wrap .yff-field-label{font-size:14px;font-weight:600;color:#111827;margin-bottom:2px;}
#yatoon-form-fields-wrap .yff-field-meta{font-size:12px;color:#9ca3af;}
#yatoon-form-fields-wrap .yff-field-actions{display:flex;gap:6px;flex-shrink:0;}
#yatoon-form-fields-wrap .yff-btn{font-size:12px;padding:4px 10px;border-radius:6px;border:1px solid #e5e7eb;background:#fff;cursor:pointer;color:#374151;}
#yatoon-form-fields-wrap .yff-btn:hover{background:#f9fafb;}
#yatoon-form-fields-wrap .yff-btn-del{color:#dc2626;border-color:#fecaca;}
#yatoon-form-fields-wrap .yff-toggle{position:relative;width:36px;height:20px;flex-shrink:0;}
#yatoon-form-fields-wrap .yff-toggle input{opacity:0;width:0;height:0;}
#yatoon-form-fields-wrap .yff-slider{position:absolute;inset:0;background:#d1d5db;border-radius:20px;cursor:pointer;transition:.2s;}
#yatoon-form-fields-wrap .yff-slider:before{content:'';position:absolute;height:14px;width:14px;left:3px;bottom:3px;background:#fff;border-radius:50%;transition:.2s;}
#yatoon-form-fields-wrap .yff-toggle input:checked + .yff-slider{background:var(--wp-admin-theme-color,#2271b1);}
#yatoon-form-fields-wrap .yff-toggle input:checked + .yff-slider:before{transform:translateX(16px);}
#yatoon-form-fields-wrap .yff-empty{text-align:center;padding:40px;color:#9ca3af;font-size:13px;}
#yatoon-form-fields-wrap .yff-form-row{margin-bottom:14px;}
#yatoon-form-fields-wrap .yff-form-row label{display:block;font-size:13px;font-weight:600;color:#374151;margin-bottom:5px;}
#yatoon-form-fields-wrap .yff-form-row input,
#yatoon-form-fields-wrap .yff-form-row select,
#yatoon-form-fields-wrap .yff-form-row textarea{width:100%;padding:7px 10px;border:1px solid #d1d5db;border-radius:6px;font-size:13px;font-family:inherit;}
#yatoon-form-fields-wrap .yff-form-row textarea{min-height:70px;resize:vertical;}
#yatoon-form-fields-wrap .yff-hint{font-size:11px;color:#9ca3af;margin-top:3px;}
#yatoon-form-fields-wrap .yff-type-badge{display:inline-block;font-size:10px;padding:1px 7px;border-radius:20px;font-weight:600;background:#f3f4f6;color:#6b7280;text-transform:uppercase;letter-spacing:.04em;}
#yatoon-form-fields-wrap .yff-required-badge{background:#fef3c7;color:#92400e;}
@media(max-width:900px){#yatoon-form-fields-wrap .yff-layout{grid-template-columns:1fr;}}
</style>

<div class="yff-layout">
    <!-- Left: field list -->
    <div class="yff-panel">
        <div class="yff-head">
            <h2>Active Fields</h2>
            <span style="font-size:12px;color:#9ca3af;">Drag to reorder</span>
        </div>
        <div class="yff-body">
            <div id="yff-field-list">
                <?php if (empty($fields)): ?>
                <div class="yff-empty" id="yff-empty-msg">No custom fields yet. Add one using the form on the right.</div>
                <?php else: foreach ($fields as $f): ?>
                <div class="yff-field-row" data-id="<?php echo esc_attr($f->id); ?>">
                    <span class="yff-drag-handle">⠿</span>
                    <div class="yff-field-info">
                        <div class="yff-field-label">
                            <?php echo esc_html($f->label); ?>
                            <?php if ($f->required): ?><span class="yff-type-badge yff-required-badge">Required</span><?php endif; ?>
                        </div>
                        <div class="yff-field-meta">
                            <span class="yff-type-badge"><?php echo esc_html($f->type); ?></span>
                            <?php if ($f->placeholder): ?> · <?php echo esc_html(mb_strimwidth($f->placeholder, 0, 40, '...')); ?><?php endif; ?>
                        </div>
                    </div>
                    <label class="yff-toggle" title="<?php echo $f->is_active ? 'Active' : 'Inactive'; ?>">
                        <input type="checkbox" class="yff-active-toggle" data-id="<?php echo esc_attr($f->id); ?>" <?php checked($f->is_active, 1); ?>>
                        <span class="yff-slider"></span>
                    </label>
                    <div class="yff-field-actions">
                        <button type="button" class="yff-btn yff-edit-btn" data-id="<?php echo esc_attr($f->id); ?>"
                            data-label="<?php echo esc_attr($f->label); ?>"
                            data-type="<?php echo esc_attr($f->type); ?>"
                            data-placeholder="<?php echo esc_attr($f->placeholder); ?>"
                            data-options="<?php echo esc_attr($f->options ?? ''); ?>"
                            data-required="<?php echo esc_attr($f->required); ?>">Edit</button>
                        <button type="button" class="yff-btn yff-btn-del yff-delete-btn" data-id="<?php echo esc_attr($f->id); ?>">Delete</button>
                    </div>
                </div>
                <?php endforeach; endif; ?>
            </div>
        </div>
    </div>

    <!-- Right: add/edit form -->
    <div>
        <div class="yff-panel">
            <div class="yff-head"><h2 id="yff-form-title">Add New Field</h2></div>
            <div class="yff-body">
                <input type="hidden" id="yff-edit-id" value="0">
                <div class="yff-form-row">
                    <label>Field Label *</label>
                    <input type="text" id="yff-label" placeholder="e.g. Allergy Notes">
                    <p class="yff-hint">Shown to the customer as the field name.</p>
                </div>
                <div class="yff-form-row">
                    <label>Field Type</label>
                    <select id="yff-type">
                        <option value="text">Short text</option>
                        <option value="textarea">Long text (multi-line)</option>
                        <option value="select">Dropdown</option>
                        <option value="checkbox">Checkbox (yes/no)</option>
                        <option value="radio">Multiple choice</option>
                        <option value="url">URL / Link</option>
                    </select>
                </div>
                <div class="yff-form-row" id="yff-placeholder-row">
                    <label>Placeholder Text</label>
                    <input type="text" id="yff-placeholder" placeholder="e.g. Any allergies we should know?">
                </div>
                <div class="yff-form-row" id="yff-options-row" style="display:none;">
                    <label>Options</label>
                    <textarea id="yff-options" placeholder="First visit&#10;Returning client&#10;Referred by friend"></textarea>
                    <p class="yff-hint">One option per line.</p>
                </div>
                <div class="yff-form-row">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;">
                        <input type="checkbox" id="yff-required" style="width:16px;height:16px;">
                        Required field (customer must fill in)
                    </label>
                </div>
                <div style="display:flex;gap:8px;">
                    <button type="button" id="yff-save-btn" class="button button-primary" style="flex:1;padding:8px;">Save Field</button>
                    <button type="button" id="yff-cancel-btn" class="button" style="display:none;">Cancel</button>
                </div>
            </div>
        </div>

        <div class="yff-panel" style="margin-top:14px;">
            <div class="yff-head"><h2>Quick-add Templates</h2></div>
            <div class="yff-body" style="display:grid;grid-template-columns:1fr 1fr;gap:6px;">
                <?php
                $templates = array(
                    array('Allergy Notes', 'textarea', 'Any skin allergies or sensitivities?', '', 0),
                    array('Reference Image', 'url', 'Paste a link to your reference photo', '', 0),
                    array('First Visit?', 'select', '', "First visit\nReturning client", 0),
                    array('Skin Type', 'select', '', "Normal\nDry\nOily\nSensitive\nCombination", 0),
                    array('Nail Length Preference', 'select', '', "Short\nMedium\nLong\nExtra long", 0),
                    array('Design Complexity', 'radio', '', "Simple\nModerate\nDetailed\nCustom artwork", 0),
                );
                foreach ($templates as $t):
                ?>
                <button type="button" class="button yff-template-btn" style="font-size:12px;text-align:left;padding:6px 10px;"
                    data-label="<?php echo esc_attr($t[0]); ?>"
                    data-type="<?php echo esc_attr($t[1]); ?>"
                    data-placeholder="<?php echo esc_attr($t[2]); ?>"
                    data-options="<?php echo esc_attr($t[3]); ?>"
                    data-required="<?php echo esc_attr($t[4]); ?>">
                    + <?php echo esc_html($t[0]); ?>
                </button>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(function($) {
    const nonce = '<?php echo esc_js($nonce); ?>';

    // Show/hide options textarea based on type
    $('#yff-type').on('change', function() {
        const t = $(this).val();
        $('#yff-options-row').toggle(t === 'select' || t === 'radio');
        $('#yff-placeholder-row').toggle(t !== 'checkbox');
    });

    // Quick templates
    $(document).on('click', '.yff-template-btn', function() {
        $('#yff-edit-id').val(0);
        $('#yff-form-title').text('Add New Field');
        $('#yff-label').val($(this).data('label'));
        $('#yff-type').val($(this).data('type')).trigger('change');
        $('#yff-placeholder').val($(this).data('placeholder'));
        $('#yff-options').val($(this).data('options').replace(/\\n/g,'\n'));
        $('#yff-required').prop('checked', $(this).data('required') == 1);
        $('#yff-cancel-btn').hide();
        $('#yff-label').focus();
    });

    // Edit field
    $(document).on('click', '.yff-edit-btn', function() {
        const $b = $(this);
        $('#yff-edit-id').val($b.data('id'));
        $('#yff-form-title').text('Edit Field');
        $('#yff-label').val($b.data('label'));
        $('#yff-type').val($b.data('type')).trigger('change');
        $('#yff-placeholder').val($b.data('placeholder'));
        $('#yff-options').val($b.data('options').replace(/\\n/g,'\n'));
        $('#yff-required').prop('checked', $b.data('required') == 1);
        $('#yff-cancel-btn').show();
        $('#yff-label').focus();
    });

    $('#yff-cancel-btn').on('click', function() {
        $('#yff-edit-id').val(0);
        $('#yff-form-title').text('Add New Field');
        $('#yff-label, #yff-placeholder, #yff-options').val('');
        $('#yff-required').prop('checked', false);
        $('#yff-type').val('text').trigger('change');
        $(this).hide();
    });

    // Save field
    $('#yff-save-btn').on('click', function() {
        const label = $('#yff-label').val().trim();
        if (!label) { alert('Field label is required.'); return; }
        const $btn = $(this).prop('disabled', true).text('Saving...');
        $.post(ajaxurl, {
            action: 'yatoon_save_form_field',
            nonce,
            id:          $('#yff-edit-id').val(),
            label,
            type:        $('#yff-type').val(),
            placeholder: $('#yff-placeholder').val().trim(),
            options:     $('#yff-options').val().trim(),
            required:    $('#yff-required').is(':checked') ? 1 : 0,
        }, function(resp) {
            $btn.prop('disabled', false).text('Save Field');
            if (resp.success) location.reload();
            else alert('Error: ' + (resp.data?.message || 'Unknown'));
        });
    });

    // Delete field
    $(document).on('click', '.yff-delete-btn', function() {
        if (!confirm('Delete this field? Existing booking data using it won\'t be deleted.')) return;
        const $btn = $(this).prop('disabled', true);
        $.post(ajaxurl, { action: 'yatoon_delete_form_field', nonce, id: $(this).data('id') }, function(resp) {
            if (resp.success) location.reload();
            else { alert('Delete failed'); $btn.prop('disabled', false); }
        });
    });

    // Toggle active
    $(document).on('change', '.yff-active-toggle', function() {
        $.post(ajaxurl, {
            action: 'yatoon_toggle_form_field',
            nonce,
            id:        $(this).data('id'),
            is_active: $(this).is(':checked') ? 1 : 0,
        });
    });

    // Drag to reorder
    if ($.fn.sortable) {
        $('#yff-field-list').sortable({
            handle: '.yff-drag-handle',
            items: '.yff-field-row',
            cursor: 'grabbing',
            update: function() {
                const order = [];
                $('#yff-field-list .yff-field-row').each(function() {
                    order.push($(this).data('id'));
                });
                $.post(ajaxurl, { action: 'yatoon_reorder_form_fields', nonce, order: order.join(',') });
            }
        });
    }
});
</script>
</div>
