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

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

// Get taxonomy data if editing
$is_edit = !empty($_GET['tax']);
$tax_slug = $is_edit ? sanitize_key($_GET['tax']) : '';
$tax_data = [];

if ($is_edit) {
    $taxonomies = get_option('switchboard_custom_taxonomies', []);
    foreach ($taxonomies as $tax) {
        if ($tax['slug'] === $tax_slug) {
            $tax_data = $tax;
            break;
        }
    }

    if (empty($tax_data)) {
        wp_die(esc_html__('Custom taxonomy not found.', 'wpswitchboard'));
    }
}

// Get all post types for selection
$all_post_types = get_post_types(['public' => true], 'objects');
$exclude_types = ['attachment', 'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation'];
$all_post_types = array_diff_key($all_post_types, array_flip($exclude_types));

// Set defaults
$defaults = [
    'name' => '',
    'plural_name' => '',
    'slug' => '',
    'hierarchical' => false,
    'post_types' => ['post'],
    'rewrite_slug' => '',
    'public' => true,
    'show_in_rest' => true,
    'show_admin_column' => true,
    'show_tagcloud' => true,
];

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

<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="tax-form" class="sb-module-form">
    <?php wp_nonce_field('taxonomy_builder_save', 'taxonomy_builder_nonce'); ?>
    <input type="hidden" name="action" value="taxonomy_builder_save">
    <input type="hidden" name="is_edit" value="<?php echo $is_edit ? '1' : '0'; ?>">
    <?php if ($is_edit): ?>
        <input type="hidden" name="original_slug" value="<?php echo esc_attr($tax_slug); ?>">
    <?php endif; ?>

    <!-- 2-Column Layout: Left (big) for Basic Info + Options, Right (small) for Post Types -->
    <div class="sb-module-form-layout">
        <!-- Left Column: Basic Information + Taxonomy Options -->
        <div class="sb-module-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('Basic Information', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Core settings for your custom taxonomy', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-form-grid">
                        <div class="sb-module-form-group">
                            <label for="tax_name" class="sb-module-form-label">
                                <?php esc_html_e('Singular Name', 'wpswitchboard'); ?>
                                <span class="sb-module-required">*</span>
                            </label>
                            <input type="text" name="tax_name" id="tax_name" value="<?php echo esc_attr($tax_data['name']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('e.g., Genre, Brand, Location', 'wpswitchboard'); ?>" required>
                            <p class="sb-module-form-help"><?php esc_html_e('The singular name for your taxonomy', 'wpswitchboard'); ?></p>
                        </div>

                        <div class="sb-module-form-group">
                            <label for="tax_plural_name" class="sb-module-form-label">
                                <?php esc_html_e('Plural Name', 'wpswitchboard'); ?>
                                <span class="sb-module-required">*</span>
                            </label>
                            <input type="text" name="tax_plural_name" id="tax_plural_name" value="<?php echo esc_attr($tax_data['plural_name']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('e.g., Genres, Brands, Locations', 'wpswitchboard'); ?>" required>
                            <p class="sb-module-form-help"><?php esc_html_e('The plural form of the name', 'wpswitchboard'); ?></p>
                        </div>
                    </div>

                    <div class="sb-module-form-grid">
                        <div class="sb-module-form-group">
                            <label for="tax_slug" class="sb-module-form-label">
                                <?php esc_html_e('Slug', 'wpswitchboard'); ?>
                                <span class="sb-module-required">*</span>
                            </label>
                            <input type="text" name="tax_slug" id="tax_slug" value="<?php echo esc_attr($tax_data['slug']); ?>" class="sb-module-input" <?php echo $is_edit ? 'readonly' : ''; ?> placeholder="<?php esc_attr_e('e.g., genre, brand', 'wpswitchboard'); ?>" required pattern="[a-z0-9_-]+">
                            <p class="sb-module-form-help">
                                <?php echo $is_edit ?
                                    esc_html__('Cannot be changed after creation', 'wpswitchboard') :
                                    esc_html__('URL-friendly identifier (auto-generated from name)', 'wpswitchboard');
                                ?>
                            </p>
                        </div>

                        <div class="sb-module-form-group">
                            <label for="tax_type" class="sb-module-form-label"><?php esc_html_e('Type', 'wpswitchboard'); ?></label>
                            <select name="tax_type" id="tax_type" class="sb-module-select">
                                <option value="hierarchical" <?php selected($tax_data['hierarchical'], true); ?>><?php esc_html_e('Hierarchical (like Categories)', 'wpswitchboard'); ?></option>
                                <option value="flat" <?php selected($tax_data['hierarchical'], false); ?>><?php esc_html_e('Flat (like Tags)', 'wpswitchboard'); ?></option>
                            </select>
                            <p class="sb-module-form-help"><?php esc_html_e('Hierarchical allows parent/child relationships', 'wpswitchboard'); ?></p>
                        </div>
                    </div>

                    <div class="sb-module-form-group">
                        <label for="tax_rewrite_slug" class="sb-module-form-label"><?php esc_html_e('Rewrite Slug (Optional)', 'wpswitchboard'); ?></label>
                        <input type="text" name="tax_rewrite_slug" id="tax_rewrite_slug" value="<?php echo esc_attr($tax_data['rewrite_slug']); ?>" class="sb-module-input" placeholder="<?php esc_attr_e('Leave empty to use main slug', 'wpswitchboard'); ?>" pattern="[a-z0-9_-]*">
                        <p class="sb-module-form-help"><?php esc_html_e('Custom URL slug (optional)', 'wpswitchboard'); ?></p>
                    </div>
                </div>
            </div>

            <!-- Taxonomy Options -->
            <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('Taxonomy Options', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Configure behavior and visibility settings', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-options-grid">
                        <label class="sb-module-option-item">
                            <input type="checkbox" name="tax_public" value="1" <?php checked($tax_data['public']); ?>>
                            <div>
                                <strong><?php esc_html_e('Public', 'wpswitchboard'); ?></strong>
                                <span><?php esc_html_e('Make this taxonomy publicly queryable on the frontend', 'wpswitchboard'); ?></span>
                            </div>
                        </label>

                        <label class="sb-module-option-item">
                            <input type="checkbox" name="tax_show_in_rest" value="1" <?php checked($tax_data['show_in_rest']); ?>>
                            <div>
                                <strong><?php esc_html_e('Show in REST API', 'wpswitchboard'); ?></strong>
                                <span><?php esc_html_e('Required for Gutenberg block editor support', 'wpswitchboard'); ?></span>
                            </div>
                        </label>

                        <label class="sb-module-option-item">
                            <input type="checkbox" name="tax_show_admin_column" value="1" <?php checked($tax_data['show_admin_column']); ?>>
                            <div>
                                <strong><?php esc_html_e('Show Admin Column', 'wpswitchboard'); ?></strong>
                                <span><?php esc_html_e('Display taxonomy terms in post type list tables', 'wpswitchboard'); ?></span>
                            </div>
                        </label>

                        <label class="sb-module-option-item">
                            <input type="checkbox" name="tax_show_tagcloud" value="1" <?php checked($tax_data['show_tagcloud']); ?>>
                            <div>
                                <strong><?php esc_html_e('Show Tag Cloud', 'wpswitchboard'); ?></strong>
                                <span><?php esc_html_e('Enable tag cloud widget for this taxonomy', 'wpswitchboard'); ?></span>
                            </div>
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column: Post Types -->
        <div class="sb-module-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('Attach to Post Types', 'wpswitchboard'); ?></h2>
                        <p class="sb-module-card-desc"><?php esc_html_e('Select which post types can use this taxonomy', 'wpswitchboard'); ?></p>
                    </div>
                </div>
                <div class="sb-module-card-body">
                    <div class="sb-module-checkbox-grid" style="grid-template-columns: 1fr;">
                        <?php foreach ($all_post_types as $pt_slug => $pt_obj):
                            $checked = in_array($pt_slug, $tax_data['post_types']);
                        ?>
                            <label class="sb-module-checkbox-item">
                                <input type="checkbox" name="tax_post_types[]" value="<?php echo esc_attr($pt_slug); ?>" <?php checked($checked); ?>>
                                <span><?php echo esc_html($pt_obj->label); ?></span>
                            </label>
                        <?php endforeach; ?>
                    </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): ?>
                <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['action' => 'delete', 'tax' => $tax_slug], admin_url('admin.php?page=custom-taxonomy-builder')), 'delete_tax_' . $tax_slug)); ?>" class="sb-module-button sb-module-button-danger sb-module-button-sm" onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete this custom taxonomy? This will remove the configuration but not delete any existing terms.', 'wpswitchboard'); ?>');">
                    <?php esc_html_e('Delete', 'wpswitchboard'); ?>
                </a>
            <?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 tax-cancel-btn">
                <?php esc_html_e('Cancel', 'wpswitchboard'); ?>
            </button>
            <button type="submit" name="save" class="sb-module-button sb-module-button-primary sb-module-button-sm">
                <?php echo $is_edit ? esc_html__('Update Taxonomy', 'wpswitchboard') : esc_html__('Create Taxonomy', 'wpswitchboard'); ?>
            </button>
        </div>
    </div>
</form>

<script>
jQuery(document).ready(function($) {
    // Auto-generate slug from name (only when creating new)
    <?php if (!$is_edit): ?>
    $('#tax_name').on('input', function() {
        var name = $(this).val();
        var slug = name.toLowerCase()
            .replace(/[^a-z0-9]+/g, '_')
            .replace(/^_|_$/g, '');
        $('#tax_slug').val(slug);

        // Auto-generate plural if empty
        if (!$('#tax_plural_name').val()) {
            var plural = name;
            if (name) {
                if (name.match(/[sxz]$/i) || name.match(/[cs]h$/i)) {
                    plural = name + 'es';
                } else if (name.match(/[^aeiou]y$/i)) {
                    plural = name.replace(/y$/i, 'ies');
                } else {
                    plural = name + 's';
                }
            }
            $('#tax_plural_name').val(plural);
        }
    });
    <?php endif; ?>
});
</script>

