<?php
/**
 * Custom Field Groups Admin Page Template
 * Modern 2-column layout: Left sidebar for field groups list, Right main area for edit/create
 *
 * @package Switchboard
 * @since 1.0.0
 */

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

// Get field groups data
$groups = get_option('switchboard_field_groups', []);
$post_types = get_post_types(['public' => true], 'objects');

// Determine current action
$action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';
$selected_group = isset($_GET['group']) ? sanitize_key($_GET['group']) : '';

// Get current group data if editing
$current_group = null;
if ($action === 'edit' && $selected_group && isset($groups[$selected_group])) {
    $current_group = $groups[$selected_group];
    $current_group['id'] = $selected_group;
}

// Localize strings for JavaScript
$i18n = [
    'newFieldGroup' => __('New Field Group', 'wpswitchboard'),
    'noFieldGroupsYet' => __('No field groups created yet', 'wpswitchboard'),
    'field' => __('field', 'wpswitchboard'),
    'fields' => __('fields', 'wpswitchboard'),
    'postType' => __('post type', 'wpswitchboard'),
    'postTypes' => __('post types', 'wpswitchboard'),
    'edit' => __('Edit', 'wpswitchboard'),
    'delete' => __('Delete', 'wpswitchboard'),
    'removeThisField' => __('Remove this field?', 'wpswitchboard'),
    'enterGroupTitle' => __('Please enter a group title', 'wpswitchboard'),
    'selectPostType' => __('Please select at least one post type', 'wpswitchboard'),
    'saving' => __('Saving...', 'wpswitchboard'),
    'error' => __('Error: ', 'wpswitchboard'),
    'deleteFieldGroup' => __('Delete this field group? This cannot be undone.', 'wpswitchboard'),
    'deleting' => __('Deleting...', 'wpswitchboard'),
    'saved' => __('Saved', 'wpswitchboard'),
];
?>

<div class="wrap sb-module-wrap">
    <!-- Header -->
    <div class="sb-module-header">
        <div class="sb-module-header-left">
            <svg class="sb-module-title-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
            </svg>
            <div>
                <h1 class="sb-module-title">
                    <?php if ($action === 'add'): ?>
                        <?php esc_html_e('Creating Custom Field Group', 'wpswitchboard'); ?>
                    <?php elseif ($action === 'edit'): ?>
                        <?php esc_html_e('Editing Field Group', 'wpswitchboard'); ?>
                    <?php else: ?>
                        <?php esc_html_e('Custom Field Groups', 'wpswitchboard'); ?>
                    <?php endif; ?>
                    <span class="switchboard-badge">SWITCHBOARD</span>
                </h1>
                <p class="sb-module-subtitle">
                    <?php if ($action === 'add'): ?>
                        <?php esc_html_e('Create a new custom field group and assign it to post types', 'wpswitchboard'); ?>
                    <?php elseif ($action === 'edit'): ?>
                        <?php esc_html_e('Edit your field group settings and fields', 'wpswitchboard'); ?>
                    <?php else: ?>
                        <?php esc_html_e('Create and manage custom field groups for post types with drag-and-drop builder', 'wpswitchboard'); ?>
                    <?php endif; ?>
                </p>
            </div>
        </div>
        <div class="sb-module-header-right">
            <a href="https://docs.wpswitchboard.com/modules/content/custom-field-groups" target="_blank" class="sb-module-help-link">
                <span class="sb-module-help-link-icon dashicons dashicons-editor-help"></span>
                Help
            </a>
            <?php if ($action === 'add' || $action === 'edit'): ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=custom-field-groups')); ?>" class="sb-module-button sb-module-button-secondary">
                    <?php esc_html_e('Go Back', 'wpswitchboard'); ?>
                </a>
            <?php else: ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=custom-field-groups&action=add')); ?>" class="sb-module-button sb-module-button-primary">
                    <?php esc_html_e('Add New', 'wpswitchboard'); ?>
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Main Content -->
    <div class="sb-module-container">
        <?php if ($action === ''): ?>
            <!-- Default Dashboard View: Grid of Field Groups -->
            <!-- Stats Cards -->
            <div class="sb-module-stats">
                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Field Groups', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value"><?php echo count($groups); ?></div>
                    </div>
                </div>

                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Total Fields', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value">
                            <?php
                            $total_fields = 0;
                            foreach ($groups as $group) {
                                $total_fields += count($group['fields']);
                            }
                            echo $total_fields;
                            ?>
                        </div>
                    </div>
                </div>

                <div class="sb-module-stat-card">
                    <div class="sb-module-stat-label"><?php esc_html_e('Post Types', 'wpswitchboard'); ?></div>
                    <div class="sb-module-stat-content">
                        <div class="sb-module-stat-value">
                            <?php
                            $assigned_post_types = [];
                            foreach ($groups as $group) {
                                $assigned_post_types = array_merge($assigned_post_types, $group['post_types']);
                            }
                            echo count(array_unique($assigned_post_types));
                            ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Field Groups Grid -->
            <?php if (empty($groups)): ?>
                <!-- Empty State -->
                <div class="cfg-empty-state">
                    <div class="cfg-empty-state-icon">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                    </div>
                    <h3 class="cfg-empty-state-title"><?php esc_html_e('No field groups yet', 'wpswitchboard'); ?></h3>
                    <p class="cfg-empty-state-desc"><?php esc_html_e('Here are some ideas to get you started', 'wpswitchboard'); ?></p>

                    <!-- Use Cases Grid -->
                    <div class="cfg-use-cases-grid">
                        <div class="cfg-use-case-card">
                            <h4 class="cfg-use-case-title">Product Specifications</h4>
                            <p class="cfg-use-case-desc">Add fields for dimensions, weight, material, and care instructions to WooCommerce products without complex plugins.</p>
                        </div>
                        <div class="cfg-use-case-card">
                            <h4 class="cfg-use-case-title">Recipe Cards</h4>
                            <p class="cfg-use-case-desc">Create custom fields for ingredients, cook time, serving size, and nutritional info on food blog recipe posts.</p>
                        </div>
                        <div class="cfg-use-case-card">
                            <h4 class="cfg-use-case-title">Real Estate Data</h4>
                            <p class="cfg-use-case-desc">Build fields for bedrooms, bathrooms, square footage, lot size, and year built for property listing post type.</p>
                        </div>
                    </div>

                    <a href="<?php echo esc_url(admin_url('admin.php?page=custom-field-groups&action=add')); ?>" class="cfg-empty-state-btn">
                        <span class="dashicons dashicons-plus-alt"></span>
                        <?php esc_html_e('Create Field Group', 'wpswitchboard'); ?>
                    </a>
                </div>
            <?php else: ?>
                <div class="cfg-groups-grid">
                    <?php foreach ($groups as $group_id => $group):
                        $field_count = count($group['fields']);
                        $type_count = count($group['post_types']);
                    ?>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=custom-field-groups&action=edit&group=' . urlencode($group_id))); ?>" class="cfg-group-card">
                            <h3 class="cfg-group-card-title"><?php echo esc_html($group['title']); ?></h3>
                            <div class="cfg-group-card-post-types">
                                <?php
                                $type_names = array_map(function($pt_name) use ($post_types) {
                                    return isset($post_types[$pt_name]) ? $post_types[$pt_name]->label : $pt_name;
                                }, array_slice($group['post_types'], 0, 3));
                                echo esc_html(implode(', ', $type_names));
                                if (count($group['post_types']) > 3) {
                                    echo ' +' . (count($group['post_types']) - 3);
                                }
                                ?>
                            </div>
                            <div class="cfg-group-card-badges">
                                <span class="cfg-group-card-badge"><?php echo $field_count . ' ' . ($field_count !== 1 ? esc_html__('fields', 'wpswitchboard') : esc_html__('field', 'wpswitchboard')); ?></span>
                                <span class="cfg-group-card-badge"><?php echo $type_count . ' ' . ($type_count !== 1 ? esc_html__('types', 'wpswitchboard') : esc_html__('type', 'wpswitchboard')); ?></span>
                            </div>
                            <div class="cfg-group-card-overlay">
                                <span class="dashicons dashicons-edit"></span>
                            </div>
                        </a>
                    <?php endforeach; ?>

                    <!-- Add New Card -->
                    <a href="<?php echo esc_url(admin_url('admin.php?page=custom-field-groups&action=add')); ?>" class="cfg-group-card cfg-group-card-add">
                        <h3 class="cfg-group-card-add-title"><?php esc_html_e('New Field Group', 'wpswitchboard'); ?></h3>
                        <p class="cfg-group-card-add-desc"><?php esc_html_e('Click to create', 'wpswitchboard'); ?></p>
                        <div class="cfg-group-card-add-icon">
                            <span class="dashicons dashicons-plus-alt"></span>
                        </div>
                    </a>
                </div>
            <?php endif; ?>
        <?php else: ?>
            <!-- Add/Edit View: 2-Column Layout -->
            <div class="sb-module-layout" style="grid-template-columns: 1fr;">
                <div class="sb-module-main">
                    <?php include dirname(__FILE__) . '/edit.php'; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<style>
/* Empty State */
.cfg-empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 80px 40px;
    background: white;
    border-radius: 12px;
    margin-top: 24px;
}

.cfg-empty-state-icon {
    width: 80px;
    height: 80px;
    background: var(--primary-50);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 24px;
}

.cfg-empty-state-icon svg {
    width: 40px;
    height: 40px;
    color: var(--primary-500);
}

.cfg-empty-state-title {
    font-size: 20px;
    font-weight: 600;
    color: #0f172a;
    margin: 0 0 8px 0;
}

.cfg-empty-state-desc {
    font-size: 14px;
    color: #64748b;
    margin: 0 0 24px 0;
    line-height: 1.6;
}

.cfg-empty-state-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 24px;
    background: var(--primary-500);
    color: white;
    border-radius: 8px;
    font-weight: 600;
    font-size: 14px;
    transition: all 0.2s ease;
    cursor: pointer;
    text-decoration: none;
}

.cfg-empty-state-btn:hover {
    background: var(--primary-600);
    color: white;
}

.cfg-empty-state-btn .dashicons {
    font-size: 18px;
    width: 18px;
    height: 18px;
}

/* Use Cases Grid */
.cfg-use-cases-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin: 32px 0;
    width: 100%;
    max-width: 900px;
}

.cfg-use-case-card {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 20px;
    text-align: left;
    transition: all 0.2s ease;
}

.cfg-use-case-card:hover {
    border-color: var(--primary-500);
    background: var(--primary-50);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(var(--primary-500-rgb), 0.1);
}

.cfg-use-case-title {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
    margin: 0 0 8px 0;
}

.cfg-use-case-desc {
    font-size: 12px;
    color: #64748b;
    margin: 0;
    line-height: 1.5;
}

@media (max-width: 1024px) {
    .cfg-use-cases-grid {
        grid-template-columns: 1fr;
    }
}

.cfg-groups-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-top: 24px;
}

.cfg-group-card {
    background: white;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 32px 20px;
    transition: all 0.2s ease;
    position: relative;
    cursor: pointer;
    text-decoration: none;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 10px;
}

.cfg-group-card:hover {
    border-color: var(--primary-500);
    background: var(--primary-50);
}

.cfg-group-card-title {
    font-size: 15px;
    font-weight: 600;
    color: #0f172a;
    margin: 0;
    line-height: 1.3;
}

.cfg-group-card-post-types {
    font-size: 12px;
    color: #64748b;
    line-height: 1.4;
}

.cfg-group-card-badges {
    display: flex;
    gap: 6px;
    justify-content: center;
}

.cfg-group-card-badge {
    font-size: 10px;
    font-weight: 600;
    padding: 4px 10px;
    background: var(--primary-100);
    color: var(--primary-700);
    border-radius: 10px;
    text-transform: uppercase;
    letter-spacing: 0.03em;
    white-space: nowrap;
    transition: all 0.2s ease;
}

.cfg-group-card:hover .cfg-group-card-badge {
    background: var(--primary-200);
    color: var(--primary-800);
}

.cfg-group-card-overlay {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 28px;
    height: 28px;
    background: var(--primary-500);
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.cfg-group-card:hover .cfg-group-card-overlay {
    opacity: 1;
}

.cfg-group-card-overlay .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
    color: white;
}

/* Add New Card */
.cfg-group-card-add {
    border: 2px dashed #cbd5e1;
    background: #f8fafc;
}

.cfg-group-card-add:hover {
    border-color: var(--primary-500);
    background: var(--primary-50);
}

.cfg-group-card-add-title {
    font-size: 15px;
    font-weight: 600;
    color: #0f172a;
    margin: 0;
}

.cfg-group-card-add-desc {
    font-size: 12px;
    color: #94a3b8;
    margin: 0;
}

.cfg-group-card-add-icon {
    margin-top: 4px;
    width: 40px;
    height: 40px;
    background: #f1f5f9;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.cfg-group-card-add-icon .dashicons {
    font-size: 20px;
    width: 20px;
    height: 20px;
    color: #cbd5e1;
    transition: color 0.2s ease;
}

.cfg-group-card-add:hover .cfg-group-card-add-icon {
    background: var(--primary-100);
}

.cfg-group-card-add:hover .cfg-group-card-add-icon .dashicons {
    color: var(--primary-500);
}

/* Responsive */
@media (max-width: 1400px) {
    .cfg-groups-grid {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 1024px) {
    .cfg-groups-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 640px) {
    .cfg-groups-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    const i18n = <?php echo json_encode($i18n); ?>;

    // Global ajaxurl for AJAX requests
    window.cfgAjaxUrl = ajaxurl;
    window.cfgI18n = i18n;
});
</script>
