<?php
/**
 * Custom Field Groups Edit Page Template
 * Modern form design matching Switchboard design system
 *
 * @package Switchboard
 * @since 1.0.0
 */

if (!defined('ABSPATH')) {
    exit;
}

// Get group data if editing
$is_edit = !empty($_GET['group']);
$group_id = $is_edit ? sanitize_key($_GET['group']) : '';
$group_data = [];

if ($is_edit && isset($current_group)) {
    $group_data = $current_group;
} elseif ($is_edit) {
    wp_die(esc_html__('Field group not found.', 'wpswitchboard'));
}

// Set defaults
$defaults = [
    'title' => '',
    'post_types' => [],
    'fields' => [],
];

$group_data = wp_parse_args($group_data, $defaults);
?>

<form method="post" id="cfg-form" class="sb-module-cfg-form">
    <input type="hidden" id="cfg-group-id" value="<?php echo esc_attr($group_id); ?>">
    <input type="hidden" id="cfg-is-edit" value="<?php echo $is_edit ? '1' : '0'; ?>">

    <!-- 3-Column Layout: Left (Post Types), Middle (Fields), Right (Quick Add) -->
    <div class="cfg-form-layout">
        <!-- Left Column: Post Types -->
        <div class="cfg-form-sidebar">
            <div class="sb-module-card">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Post Types', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Select where this appears', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-checkbox-grid" style="grid-template-columns: 1fr;">
                        <?php foreach ($post_types as $pt): ?>
                            <label class="sb-module-checkbox-item">
                                <input type="checkbox" class="cfg-post-type-checkbox" value="<?php echo esc_attr($pt->name); ?>" <?php checked(in_array($pt->name, $group_data['post_types'])); ?>>
                                <span><?php echo esc_html($pt->label); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Middle Column: Group Settings + Fields -->
        <div class="cfg-form-main">
            <!-- Basic Information -->
            <div class="sb-module-card sb-module-form-section">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Group Settings', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Configure your field group name and settings', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-form-group">
                        <label for="cfg-title" class="sb-module-form-label">
                            <?php esc_html_e('Group Title', 'wpswitchboard'); ?>
                            <span class="sb-module-required">*</span>
                        </label>
                        <input type="text" id="cfg-title" value="<?php echo esc_attr($group_data['title']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('e.g., Event Details, Product Info, Team Member Data', 'wpswitchboard'); ?>" required>
                        <p class="sb-module-form-help"><?php esc_html_e('The name of this field group that appears as a metabox in the post editor', 'wpswitchboard'); ?></p>
                    </div>
                </div>
            </div>

            <!-- Fields Builder -->
            <div class="sb-module-card sb-module-form-section">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Fields', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Add and configure custom fields for this group', 'wpswitchboard'); ?></p>
                    </div>
                    <div class="sb-module-card-header-right">
                        <button type="button" id="cfg-add-field-btn" class="sb-module-button sb-module-button-primary sb-module-button-sm">
                            <?php esc_html_e('Add Field', 'wpswitchboard'); ?>
                        </button>
                    </div>
                </div>
                <div class="sb-module-card-body" style="padding: 0;">
                    <div id="cfg-fields-list" class="cfg-fields-list">
                        <?php if (empty($group_data['fields'])): ?>
                            <div id="cfg-no-fields-msg" class="sb-module-empty" style="padding: 40px 20px;">
                                <svg class="sb-module-empty-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width: 48px; height: 48px;">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                </svg>
                                <p class="sb-module-empty-desc"><?php esc_html_e('No fields yet. Click "Add Field" to create your first field.', 'wpswitchboard'); ?></p>
                            </div>
                        <?php else: ?>
                            <!-- Fields will be rendered by JavaScript -->
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column: Quick Add -->
        <div class="cfg-form-sidebar">
            <div class="sb-module-card">
                <div class="sb-module-card-header">
                    <div class="sb-module-card-header-left">
                        <h2 class="sb-module-card-title"><?php esc_html_e('Quick Add', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Common field types', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-quick-add-grid">
                        <button type="button" class="sb-module-quick-add-btn cfg-quick-add-field" data-type="text">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path></svg>
                            <span><?php esc_html_e('Text', 'wpswitchboard'); ?></span>
                        </button>
                        <button type="button" class="sb-module-quick-add-btn cfg-quick-add-field" data-type="textarea">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"></path></svg>
                            <span><?php esc_html_e('Textarea', 'wpswitchboard'); ?></span>
                        </button>
                        <button type="button" class="sb-module-quick-add-btn cfg-quick-add-field" data-type="number">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"></path></svg>
                            <span><?php esc_html_e('Number', 'wpswitchboard'); ?></span>
                        </button>
                        <button type="button" class="sb-module-quick-add-btn cfg-quick-add-field" data-type="date">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                            <span><?php esc_html_e('Date', 'wpswitchboard'); ?></span>
                        </button>
                        <button type="button" class="sb-module-quick-add-btn cfg-quick-add-field" data-type="select">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7"></path></svg>
                            <span><?php esc_html_e('Select', 'wpswitchboard'); ?></span>
                        </button>
                        <button type="button" class="sb-module-quick-add-btn cfg-quick-add-field" data-type="checkbox">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                            <span><?php esc_html_e('Checkbox', 'wpswitchboard'); ?></span>
                        </button>
                        <button type="button" class="sb-module-quick-add-btn cfg-quick-add-field" data-type="image">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
                            <span><?php esc_html_e('Image', 'wpswitchboard'); ?></span>
                        </button>
                        <button type="button" class="sb-module-quick-add-btn cfg-quick-add-field" data-type="url">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"></path></svg>
                            <span><?php esc_html_e('URL', 'wpswitchboard'); ?></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Actions (Full Width) -->
    <div class="sb-module-form-actions">
        <div class="sb-module-form-actions-left">
            <?php if ($is_edit): ?>
                <button type="button" id="cfg-delete-btn" class="sb-module-button sb-module-button-danger sb-module-button-sm">
                    <?php esc_html_e('Delete Group', 'wpswitchboard'); ?>
                </button>
            <?php endif; ?>
        </div>
        <div class="sb-module-form-actions-right">
            <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm cfg-cancel-btn">
                <?php esc_html_e('Cancel', 'wpswitchboard'); ?>
            </button>
            <button type="submit" id="cfg-save-btn" class="sb-module-button sb-module-button-primary sb-module-button-sm">
                <?php echo $is_edit ? esc_html__('Update Field Group', 'wpswitchboard') : esc_html__('Create Field Group', 'wpswitchboard'); ?>
            </button>
        </div>
    </div>
</form>

<script>
jQuery(document).ready(function($) {
    const i18n = window.cfgI18n || {};
    let fieldCounter = 0;
    let currentFields = <?php echo json_encode($group_data['fields']); ?>;

    // Initialize field counter based on existing fields
    if (currentFields.length > 0) {
        // Extract numeric IDs and find the highest
        const maxId = Math.max(...currentFields.map(f => {
            const match = f.id ? f.id.match(/\d+/) : null;
            return match ? parseInt(match[0]) : 0;
        }));
        fieldCounter = maxId;
    }

    // Render initial fields if editing
    if (currentFields.length > 0) {
        renderFields();
    }

    // Cancel button
    $('.cfg-cancel-btn').on('click', function() {
        window.location.href = '<?php echo esc_url(admin_url('admin.php?page=custom-field-groups')); ?>';
    });

    // Add field button (both main and quick add)
    $('#cfg-add-field-btn, .cfg-quick-add-field').on('click', function() {
        const type = $(this).data('type') || 'text';
        addField(type);
    });

    // Add field function
    function addField(type) {
        const field = {
            id: 'field_' + (++fieldCounter),
            type: type,
            label: type.charAt(0).toUpperCase() + type.slice(1) + ' Field',
            key: 'field_' + fieldCounter,
            required: false,
            placeholder: '',
            default_value: '',
            options: type === 'select' ? 'Option 1\nOption 2\nOption 3' : ''
        };
        currentFields.push(field);
        renderFields();
    }

    // Remove field
    $(document).on('click', '.cfg-remove-field', function() {
        if (!confirm(i18n.removeThisField || 'Remove this field?')) return;

        const index = $(this).data('index');
        currentFields.splice(index, 1);
        renderFields();
    });

    // Move field up
    $(document).on('click', '.cfg-move-up', function() {
        const index = $(this).data('index');
        if (index > 0) {
            [currentFields[index], currentFields[index - 1]] = [currentFields[index - 1], currentFields[index]];
            renderFields();
        }
    });

    // Move field down
    $(document).on('click', '.cfg-move-down', function() {
        const index = $(this).data('index');
        if (index < currentFields.length - 1) {
            [currentFields[index], currentFields[index + 1]] = [currentFields[index + 1], currentFields[index]];
            renderFields();
        }
    });

    // Toggle field config
    $(document).on('click', '.cfg-field-header', function(e) {
        // Don't toggle if clicking on action buttons
        if ($(e.target).closest('.cfg-field-actions').length) {
            return;
        }

        const $field = $(this).closest('.cfg-field-item');
        const $body = $field.find('.cfg-field-body');
        const $icon = $(this).find('.cfg-field-toggle-icon');

        $body.slideToggle(200);
        $icon.toggleClass('open');
    });

    // Update field on input change
    $(document).on('input change', '.cfg-field-body input, .cfg-field-body textarea, .cfg-field-body select', function() {
        const $field = $(this).closest('.cfg-field-item');
        const index = $field.data('index');
        const prop = $(this).data('prop');

        if (prop === 'required') {
            currentFields[index][prop] = $(this).is(':checked');
        } else {
            currentFields[index][prop] = $(this).val();
        }

        // Update field title if label changed
        if (prop === 'label') {
            $field.find('.cfg-field-title').text($(this).val() || 'New Field');
        }
    });

    // Render fields
    function renderFields() {
        if (currentFields.length === 0) {
            $('#cfg-fields-list').html('<div id="cfg-no-fields-msg" class="sb-module-empty" style="padding: 40px 20px;"><svg class="sb-module-empty-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width: 48px; height: 48px;"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg><p class="sb-module-empty-desc">No fields yet. Click "Add Field" to create your first field.</p></div>');
            return;
        }

        let html = '';
        currentFields.forEach((field, index) => {
            const typeIcons = {
                text: '',
                textarea: '',
                number: '',
                date: '',
                select: '',
                checkbox: '',
                image: '',
                url: ''
            };
            const icon = typeIcons[field.type] || '';

            html += `
                <div class="cfg-field-item" data-index="${index}">
                    <div class="cfg-field-header">
                        <div class="cfg-field-header-left">
                            <span class="cfg-field-toggle-icon">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width: 14px; height: 14px;">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                                </svg>
                            </span>
                            <span class="cfg-field-icon">${icon}</span>
                            <span class="cfg-field-title">${escapeHtml(field.label)}</span>
                            <span class="cfg-field-type">${escapeHtml(field.type)}</span>
                        </div>
                        <div class="cfg-field-actions">
                            <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm cfg-move-up" data-index="${index}" ${index === 0 ? 'disabled' : ''} title="Move up">
                                <span class="dashicons dashicons-arrow-up-alt2"></span>
                            </button>
                            <button type="button" class="sb-module-button sb-module-button-secondary sb-module-button-sm cfg-move-down" data-index="${index}" ${index === currentFields.length - 1 ? 'disabled' : ''} title="Move down">
                                <span class="dashicons dashicons-arrow-down-alt2"></span>
                            </button>
                            <button type="button" class="sb-module-button sb-module-button-danger sb-module-button-sm cfg-remove-field" data-index="${index}">
                                <span class="dashicons dashicons-trash"></span>
                            </button>
                        </div>
                    </div>
                    <div class="cfg-field-body" style="display: none;">
                        <div class="sb-module-form-grid">
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Field Label</label>
                                <input type="text" class="sb-module-input" data-prop="label" value="${escapeHtml(field.label)}">
                            </div>
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Field Key</label>
                                <input type="text" class="sb-module-input" data-prop="key" value="${escapeHtml(field.key)}">
                            </div>
                        </div>

                        <div class="sb-module-form-grid">
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Placeholder</label>
                                <input type="text" class="sb-module-input" data-prop="placeholder" value="${escapeHtml(field.placeholder || '')}">
                            </div>
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Options</label>
                                <label class="sb-module-checkbox-item">
                                    <input type="checkbox" data-prop="required" ${field.required ? 'checked' : ''}>
                                    <span>Required field</span>
                                </label>
                            </div>
                        </div>

                        ${field.type === 'select' ? `
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Options (one per line)</label>
                                <textarea class="sb-module-textarea" data-prop="options" rows="4">${escapeHtml(field.options || '')}</textarea>
                            </div>
                        ` : ''}
                    </div>
                </div>
            `;
        });

        $('#cfg-fields-list').html(html);
    }

    // Escape HTML helper
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // Save form
    $('#cfg-form').on('submit', function(e) {
        e.preventDefault();

        const title = $('#cfg-title').val().trim();
        if (!title) {
            alert(i18n.enterGroupTitle || 'Please enter a group title');
            return;
        }

        const postTypes = [];
        $('.cfg-post-type-checkbox:checked').each(function() {
            postTypes.push($(this).val());
        });

        if (postTypes.length === 0) {
            alert(i18n.selectPostType || 'Please select at least one post type');
            return;
        }

        const groupId = $('#cfg-group-id').val() || 'group_' + Date.now();
        const $saveBtn = $('#cfg-save-btn');
        const originalText = $saveBtn.html();

        $saveBtn.prop('disabled', true).html('<span class="dashicons dashicons-update-alt" style="animation: spin 1s linear infinite;"></span> ' + (i18n.saving || 'Saving...'));

        $.post(ajaxurl, {
            action: 'switchboard_save_field_group',
            group_id: groupId,
            title: title,
            post_types: postTypes,
            fields: JSON.stringify(currentFields),
            nonce: '<?php echo wp_create_nonce('field_groups'); ?>'
        }, function(response) {
            if (response.success) {
                window.location.href = '<?php echo esc_url(admin_url('admin.php?page=custom-field-groups')); ?>';
            } else {
                alert((i18n.error || 'Error: ') + response.data);
                $saveBtn.prop('disabled', false).html(originalText);
            }
        });
    });

    // Delete group
    $('#cfg-delete-btn').on('click', function() {
        if (!confirm(i18n.deleteFieldGroup || 'Delete this field group? This cannot be undone.')) return;

        const groupId = $('#cfg-group-id').val();
        const $deleteBtn = $(this);
        const originalText = $deleteBtn.html();

        $deleteBtn.prop('disabled', true).html('<span class="dashicons dashicons-update-alt" style="animation: spin 1s linear infinite;"></span> ' + (i18n.deleting || 'Deleting...'));

        $.post(ajaxurl, {
            action: 'switchboard_delete_field_group',
            group_id: groupId,
            nonce: '<?php echo wp_create_nonce('field_groups'); ?>'
        }, function(response) {
            if (response.success) {
                window.location.href = '<?php echo esc_url(admin_url('admin.php?page=custom-field-groups')); ?>';
            } else {
                alert((i18n.error || 'Error: ') + response.data);
                $deleteBtn.prop('disabled', false).html(originalText);
            }
        });
    });
});
</script>

<style>
@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}

/* 3-Column Layout */
.cfg-form-layout {
    display: grid;
    grid-template-columns: 260px 1fr 260px;
    gap: 24px;
    margin-bottom: 24px;
}

.cfg-form-sidebar {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.cfg-form-main {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

/* Fields List */
.cfg-fields-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    padding: 20px;
}

.cfg-field-item {
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.2s ease;
}

.cfg-field-item:hover {
    border-color: var(--primary-500);
    background: var(--primary-50);
    box-shadow: 0 1px 3px 0 rgba(var(--primary-500-rgb), 0.1);
}

.cfg-field-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 16px;
    cursor: pointer;
    user-select: none;
    background: #fafbfc;
    transition: background 0.2s ease;
}

.cfg-field-item:hover .cfg-field-header {
    background: var(--primary-50);
}

.cfg-field-header-left {
    display: flex;
    align-items: center;
    gap: 12px;
    flex: 1;
}

.cfg-field-toggle-icon {
    display: flex;
    align-items: center;
    color: #9ca3af;
    transition: all 0.2s ease;
    flex-shrink: 0;
}

.cfg-field-item:hover .cfg-field-toggle-icon {
    color: var(--primary-500);
}

.cfg-field-toggle-icon.open {
    transform: rotate(90deg);
}

.cfg-field-icon {
    font-size: 20px;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background: white;
    border-radius: 6px;
    border: 1px solid #e5e7eb;
    transition: all 0.2s ease;
}

.cfg-field-item:hover .cfg-field-icon {
    border-color: var(--primary-500);
    background: var(--primary-50);
}

.cfg-field-title {
    font-weight: 600;
    font-size: 14px;
    color: #111827;
    flex: 1;
}

.cfg-field-type {
    font-size: 11px;
    font-weight: 600;
    color: var(--primary-500);
    background: var(--primary-50);
    padding: 4px 10px;
    border-radius: 12px;
    text-transform: uppercase;
    letter-spacing: 0.025em;
    margin-right: 8px;
}

.cfg-field-actions {
    display: flex;
    gap: 6px;
    align-items: center;
}

.cfg-field-actions .sb-module-button {
    min-width: 32px;
    height: 32px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #e5e7eb;
    background: white;
    color: #6b7280;
    transition: all 0.2s ease;
}

.cfg-field-actions .sb-module-button:hover:not(:disabled) {
    background: var(--primary-50);
    border-color: var(--primary-500);
    color: var(--primary-500);
}

.cfg-field-actions .sb-module-button.sb-module-button-danger:hover:not(:disabled) {
    background: #fef2f2;
    border-color: #ef4444;
    color: #ef4444;
}

.cfg-field-actions .sb-module-button .dashicons {
    font-size: 14px;
    width: 14px;
    height: 14px;
}

.cfg-field-actions .sb-module-button:disabled {
    opacity: 0.3;
    cursor: not-allowed;
}

.cfg-field-body {
    padding: 20px;
    border-top: 1px solid #e5e7eb;
    background: #fafbfc;
}

.cfg-field-item:hover .cfg-field-body {
    background: var(--primary-50);
}

/* Responsive */
@media (max-width: 1400px) {
    .cfg-form-layout {
        grid-template-columns: 220px 1fr 220px;
    }
}

@media (max-width: 1200px) {
    .cfg-form-layout {
        grid-template-columns: 1fr;
    }

    .cfg-form-sidebar {
        order: 1;
    }

    .cfg-form-main {
        order: 0;
    }
}
</style>
